我对Pygame很新。
我正在尝试使用Pygame在Python中重新创建Pong,但我遇到了障碍。
这是我的代码:
import pygame
pygame.init()
UP = "up"
DOWN = "down"
white = (255,255,255)
black = (0,0,0)
pygame.mouse.set_visible(True)
resolution = (800,600)
window = pygame.display.set_mode(resolution)
pygame.display.set_caption("Pong!")
clock = pygame.time.Clock()
sprites_list = pygame.sprite.Group()
running = True
class Paddle(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.Surface((25,100))
self.image.fill(white)
pygame.draw.rect(self.image,white, (0,0,25,100))
self.rect = self.image.get_rect()
def move(self,direction,pixels):
if direction == DOWN:
self.rect.y -= pixels
if direction == UP:
self.rect.y += pixels
player1 = Paddle()
player1.rect.x = 0
player1.rect.y = 200
sprites_list.add(player1)
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_DOWN]:
player1.move(DOWN, 5)
if keys[pygame.K_UP]:
player1.move(UP, 5)
sprites_list.update()
sprites_list.draw(window)
pygame.display.flip()
clock.tick(60)
pygame.quit()
我试图让player1,一个Paddle对象,根据按下的键移动或向上移动。当我运行此代码时,在按下向上或向下箭头后,player1伸出;将5个像素添加到player1.rect上。
我做错了什么,为什么sprites_list.update()不会将player1置于新的位置?
答案 0 :(得分:1)
在新循环中绘制元素之前,必须清除屏幕
您可以使用黑色window.fill((0,0,0))
填充窗口或在每个循环中绘制背景图像。
重新组织并添加window.fill(BLACK)
import pygame
# --- constants --- (UPPER_CASE_NAMES)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
UP = "up"
DOWN = "down"
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
# --- classes ---- (CamelCaseNames)
class Paddle(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = pygame.Surface((25,100))
self.image.fill(WHITE)
# you don't have to draw white rect if all surface already is white
#pygame.draw.rect(self.image,white, (0,0,25,100))
self.rect = self.image.get_rect()
def move(self, direction, pixels):
if direction == DOWN:
self.rect.y += pixels
if direction == UP:
self.rect.y -= pixels
# --- functions --- (lower_case_names)
# empty
# --- main --- (lower_case_names)
# - init -
pygame.init()
pygame.mouse.set_visible(True)
window = pygame.display.set_mode(resolution)
pygame.display.set_caption("Pong!")
# - objects -
sprites_list = pygame.sprite.Group()
player1 = Paddle()
player1.rect.x = 0
player1.rect.y = 200
sprites_list.add(player1)
# - mainloop -
clock = pygame.time.Clock()
running = True
while running:
# - events -
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_DOWN]:
player1.move(DOWN, 5)
if keys[pygame.K_UP]:
player1.move(UP, 5)
# - updates (without draws) -
sprites_list.update()
# - draws (without updates) -
window.fill(BLACK) # <--- clear screen
sprites_list.draw(window)
pygame.display.flip()
clock.tick(60)
# - end -
pygame.quit()