gpt4 book ai didi

python - pygame中的动画

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

这个程序的目标是让一个绿色圆圈在屏幕上循环地上下弹跳。我已经让它下降并再次上升,但不是让它再次下降。

import pygame, sys, time, random
from pygame.locals import *
from time import *

pygame.init()
windowSurface = pygame.display.set_mode((500, 400), 0, 32)
pygame.display.set_caption("Bounce")

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

info = pygame.display.Info()
sw = info.current_w
sh = info.current_h
y= 0
yy= sh

while True:
windowSurface.fill(BLACK)
pygame.draw.circle(windowSurface, GREEN , (250,y), 13, 0)
sleep(.006)
y+= 1
if y>sh:
pygame.draw.circle(windowSurface, GREEN , (250,yy), 13, 0)
sleep(.0001)
yy +=-1
if yy<-.00001:
y=0
y+= 1
pygame.draw.circle(windowSurface, GREEN , (250,y), 13, 0)

pygame.display.update()

for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()

最佳答案

在你的if yy < -.00001: block ,我认为你正在尝试将状态重置回程序开始时的状态。如果是这样,您忘记设置 yy = sh .

换句话说:

if yy<-.00001:
y=0
yy=sh # <- add this line
y+= 1
pygame.draw.circle(windowSurface, GREEN , (250,y), 13, 0)

但总的来说,我同意半身人的观点。这段代码太复杂了。我建议使用状态变量来记录球是向上还是向下移动,然后在循环中检查该变量并增加或减少位置。当您到达屏幕的另一端时,交换状态变量以改变球的方向。

编辑:试试这个:

import pygame, sys, time, random
from pygame.locals import *
from time import *

pygame.init()
windowSurface = pygame.display.set_mode((500, 400), 0, 32)
pygame.display.set_caption("Bounce")

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

info = pygame.display.Info()
sw = info.current_w
sh = info.current_h
y = 0

# Initial direction is down
direction = 1

while True:
windowSurface.fill(BLACK)
pygame.draw.circle(windowSurface, GREEN , (250,y), 13, 0)
#print "Drawing at 250,", y
sleep(.006)
y += direction
if y >= sh:
# Changes the direction from down to up
direction = -1
elif y <= 0:
# Changes the direction from up to down
direction = 1

pygame.display.update()

for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()

注意:希望这对您有用。我没有安装 pygame,所以我只在注释掉 pygame 内容和 print 的情况下运行它调用替换而不是绘制命令。无论如何,它对我有用。

关于python - pygame中的动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15868992/

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