Python - Pygame - Class __init___ 问题/不绘图

标签 python pygame

我正在学习 OOP,我有几个问题。 调用initiliazer时,是否自动处理代码? 因为如果是这样的话,我不明白为什么我的游戏没有绘制我要求它在播放器类的 init 部分绘制的矩形。 我对 OOP 很陌生,因此在某种程度上我不确定自己在做什么。 这是我的代码:

import pygame

white = (255, 255, 255)
black = (0, 0, 0)

class Game():
    width = 800
    height = 600
    screen = pygame.display.set_mode((width, height))
    def __init__(self):
        pass
    def fill_screen(self, color):
        self.color = color
        self.screen.fill(self.color)

class Player(pygame.sprite.Sprite):
    lead_x = 800/2
    lead_y = 600/2
    velocity = 0.002
    block_size = 10
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.draw.rect(game.screen, black, [self.lead_x, self.lead_y, self.block_size, self.block_size])

    def move_player_x_left(self):
        self.lead_x += -self.velocity

    def move_player_x_right(self):
        self.lead_x += self.velocity

    def move_player_y_up(self):
        self.lead_y += -self.velocity

    def move_player_y_down(self):
        self.lead_y += self.velocity

game = Game()
player = Player()

exitGame = False
while not exitGame:
    game.fill_screen(white)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exitGame = True
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_w:
                player.move_player_y_up()
            if event.key == pygame.K_s:
                player.move_player_y_down()
            if event.key == pygame.K_d:
                player.move_player_x_right()
            if event.key == pygame.K_a:
                player.move_player_x_left()
    pygame.display.update()
pygame.quit()
quit()

最佳答案

您在主循环中不断地用白色填充屏幕。 Player 类仅利用 __init__。这意味着矩形被绘制了一瞬间,然后被白色覆盖。

您关于自动调用 __init__ 中的代码的假设是正确的。这些带有双下划线的方法在特殊情况下由python调用,它们被称为魔术方法。您可以找到它们的列表 here .

def __init__(self):
    pygame.sprite.Sprite.__init__(self)
    # The rect drawing part was moved from here.
def update(self):
    # You were previously assigning this to a variable, this wasn't necessary.
    pygame.draw.rect(game.screen, black, [self.lead_x, self.lead_y, self.block_size, self.block_size])

填满屏幕后,您需要在主循环中调用新的更新方法。

while True:
    game.fill_screen(white)
    player.update()

关于Python - Pygame - Class __init___ 问题/不绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52104513/

相关文章:

python - 狮身人面像 : link to an internal file declared as html_extra_path

python - 从 gpx 数据中滤除噪音

python - 带有 optirun 的 IPython 笔记本

python - 在pygame中切换菜单

python - 无法在此数据源中查找

python - 在 plone 上上传文件并通过 python 脚本下载它们?

python - 升级到 Django 1.7。 AssertionError : To use StatusField, 模型 'ShellRequest' 必须具有 STATUS 选择类属性

python - 如何阻止 pygame Sprite 离开 'tail'

python - 遵循 pygame 教程时,我遇到了未定义名称的问题

python - Pygame 碰撞一次发生 19 次 - Python 3.x