我刚开始使用pygame。即使我的Player实例的x值已相应更改,其位置也不在曲面上更新。
'''__main__.py'''
import script
if __name__ == '__main__':
script.setup()
script.update()
-
'''script.py'''
import pygame
from player import Player
from enemy import Enemy
from ball import Ball
def setup():
global window, player, enemy, ball
pygame.init()
pygame.display.set_caption('Pong')
window = pygame.display.set_mode((800, 600))
player = Player(40, window.get_height() / 2 - 100 / 2, 20, 100)
enemy = Enemy(window.get_width() - 40 - 20, window.get_height() / 2 - 100 / 2, 20, 100)
def draw():
player.update()
enemy.update()
pygame.display.update()
player.draw(window)
enemy.draw(window)
def update():
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
player.up = True
if keys[pygame.K_DOWN]:
player.down = True
if not keys[pygame.K_UP]:
player.up = False
if not keys[pygame.K_DOWN]:
player.down = False
draw()
pygame.quit()
-
'''player.py'''
import pygame
class Player:
'''Player'''
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
self.color = (255, 255, 255)
self.rect = (self.x, self.y, self.width, self.height)
self.vel = 10
self.up = False
self.down = False
def draw(self, surface):
pygame.draw.rect(surface, self.color, self.rect)
def update(self):
if self.up:
self.x -= self.vel
if self.down:
self.x += self.vel
当我向上或向下按下时,实例的x值会更改,但由于某种原因,它不会在屏幕上绘制。我尝试过移动draw方法和player.update方法,但似乎无法使其正常工作。
答案 0 :(得分:0)
查看Player.draw
方法。它使用self.rect
绘制。
您的update
方法的问题在于它永远不会更新self.rect
。因此,self.rect
与after构造函数相同。
删除self.rect
作为属性,然后将其替换为简单方法(选项A)或属性(选项B):
class Player:
# Options A:
def get_rect(self):
return (self.x, self.y, self.width, self.height)
# Option B:
@property
def rect(self):
return (self.x, self.y, self.width, self.height)
或在self.rect
方法内更新update
。但我不建议这样做。单独拥有它是您首先遇到无位置错误的原因。