[英]Using a function closes pygame window
下面是String
类。 在我的主循环中使用此类中的 draw 函数会立即关闭游戏而不会出现任何错误,只要我不包含它,游戏就可以正常运行。 它确实给了我以下警告。
Warning (from warnings module):
File "C:\Users\rahul\OneDrive\Documents\A level python codes\shootingGame.py", line 44
D.blit(self.player, (self.pos[0], self.pos[1]))
DeprecationWarning: an integer is required (got type float). Implicit conversion to integers using __int__ is deprecated, and may be removed in a future version of Python.
import math, sys, os, pygame
from pygame.locals import *
pygame.init()
win = pygame.display
D = win.set_mode((1200, 600))
class String:
def __init__(self, x, y):
self.pos = [x, y]
self.dx = 0
self.dy = 0
self.string = pygame.Surface((1, 1)).convert_alpha()
self.string.fill((0, 255, 0))
def draw(self):
angle = pygame.transform.rotate(self.string, (player.orbital_angle))
length = math.hypot(self.dx, self.dy)
self.string = pygame.Surface((3, length))
D.blit(angle, (self.pos[0], self.pos[1]))
string = String(600, 300)
While True:
string.draw()
我最初在不同的函数中使用了draw
函数中的所有内容,但是在调试时它有点混乱。 具体来说,是draw()
中的最后两行导致窗口崩溃,即
self.string = pygame.Surface((3, length))
D.blit(angle, (self.pos[0], self.pos[1]))
pygame.Surface.blit()
的 position ( dest ) 参数应该是 2 个整数的元组。
在您的情况下self.pos[0]
和/或self.pos[1]
似乎是一个浮点数。
您可以通过将浮点坐标四舍五入为整数坐标 ( round
) 来消除警告:
D.blit(self.player, (round(self.pos[0]), round(self.pos[1])))
为了完整起见,必须提到参数也可以是矩形。 具有 4 个组件(左、上、宽、高)的元组。
此外,您创建了一个具有整数长度的 Surface,并且必须在(重新)创建后旋转该曲面:
class String:
# [...]
def draw(self):
# compute INTEGRAL length
length = math.hypot(self.dx, self.dy)
length = max(1, int(length))
# create surface
self.string = pygame.Surface((1, length)).convert_alpha()
self.string.fill((0, 255, 0))
# roatet surface
angle = pygame.transform.rotate(self.string, player.orbital_angle)
# blit rotated surface
D.blit(angle, (round(self.pos[0]), round(self.pos[1])))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.