【问题标题】:Using a function closes pygame window使用函数关闭 pygame 窗口
【发布时间】:2020-03-01 10:50:20
【问题描述】:

以下是String 类。在我的主循环中使用此类中的绘图函数会立即关闭游戏而不会出现任何错误,只要我不包含它,游戏就可以正常运行。它确实给了我以下警告。

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]))

【问题讨论】:

    标签: python pygame crash pygame-surface


    【解决方案1】:

    pygame.Surface.blit() 的位置 (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])))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-09
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      • 2019-09-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多