gpt4 book ai didi

python - 无法在 Pong 游戏中正确刷新显示

转载 作者:太空宇宙 更新时间:2023-11-04 00:22:06 25 4
gpt4 key购买 nike

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 的地步,尽管我不确定为什么矩形(平台)只是变得更高而不是继续前进上下(我知道两个平台会一起上升,会解决这个问题,这只是为了测试)

最佳答案

您的代码有几个问题:

  1. 您只需调用一次pygame.display.update,而不是在每次pygame.draw之后,
  2. clock.tick 设置在主游戏循环中,而不是在其他地方,
  3. 您必须在绘图前清空屏幕。

以下可能会如您所愿:

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

一些建议:

  1. 不要使用global!它是坏代码的味道。肯定有更好的方法可以在不使用它的情况下实现您想要的效果。
  2. 尽量避免大量条件嵌套。这本书很难读,一两天后需要大量脑力才能阅读。

编码愉快!

关于python - 无法在 Pong 游戏中正确刷新显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48755293/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com