import pygame, sys
pygame.init()
display_width = 800
display_height = 500
white = (255, 255, 255)
display = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('Pong')
clock = pygame.time.Clock()
platform_y = display_height * 0.38
def platform(color, x, y):
global platform_y
pygame.draw.rect(display, color, (x, y, 25, 100))
pygame.display.update()
clock.tick(80)
def ball():
pygame.draw.circle(display, white, (400, 250), 12)
pygame.display.update()
def game():
global platform_y
y_change = 0
while True:
platform(white, 100, platform_y)
platform(white, 675, platform_y)
ball()
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit(0)
elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
sys.exit(0)
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
y_change -= 2
if event.key == pygame.K_DOWN:
y_change += 2
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
y_change = 0
platform_y += y_change
pygame.display.update()
clock.tick(80)
if __name__ == '__main__':
game()
我想这不是最好的代码,但我一直在摆弄 pygame 并达到了必须创建 Pong 的地步,尽管我不确定为什么矩形(平台)只是变得更高而不是更高上下(我知道两个平台会一起上升,会解决这个问题,这只是为了测试)
最佳答案
您的代码存在几个问题:
- 您只需调用
pygame.display.update
一次,而不是在每次pygame.draw
之后调用, clock.tick
在主游戏循环中设置,而不是在其他地方设置,- 绘图前必须先清空屏幕。
以下内容可能会按您的预期工作:
import pygame, sys
pygame.init()
display_width = 800
display_height = 500
white = (255, 255, 255)
display = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('Pong')
clock = pygame.time.Clock()
platform_y = display_height * 0.38
def platform(color, x, y):
global platform_y
pygame.draw.rect(display, color, (x, y, 25, 100))
def ball():
pygame.draw.circle(display, white, (400, 250), 12)
def game():
global platform_y
y_change = 0
while True:
platform(white, 100, platform_y)
platform(white, 675, platform_y)
ball()
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit(0)
elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
sys.exit(0)
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
y_change -= 2
if event.key == pygame.K_DOWN:
y_change += 2
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
y_change = 0
platform_y += y_change
pygame.display.update()
clock.tick(80)
display.fill((0, 0, 0))
if __name__ == '__main__':
game()
一些建议:
- 不要使用
全局
!这是糟糕代码的味道。当然有更好的方法来实现您想要的而不使用它。 - 尽量避免大量条件嵌套。这本书很难读,一两天后需要很大的脑力才能读完。
祝你编码愉快!
关于python - 无法正确刷新 Pong 游戏中的显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48755293/