Python pygame通过类实例循环移动
如果跳转函数没有出现在第一个“while True”块中,我就不知道如何循环跳转函数。到目前为止,提议的替代方案都没有奏效。目前,我让它工作的唯一方法是在跳跃的每一步都按空格键Python pygame通过类实例循环移动,python,pygame,Python,Pygame,如果跳转函数没有出现在第一个“while True”块中,我就不知道如何循环跳转函数。到目前为止,提议的替代方案都没有奏效。目前,我让它工作的唯一方法是在跳跃的每一步都按空格键 import pygame from pygame import Color HEIGHT = 500 WIDTH = 400 surface = pygame.display.set_mode((HEIGHT, WIDTH)) class Bird: def __init__(self):
import pygame
from pygame import Color
HEIGHT = 500
WIDTH = 400
surface = pygame.display.set_mode((HEIGHT, WIDTH))
class Bird:
def __init__(self):
self.x = 10
self.y = 300
self.vy = 5
self.jumpCount = 10
self.isJump = False
def draw(self):
pygame.draw.rect(surface, Color("yellow"), (self.x, self.y, 10, 10))
pygame.display.flip()
def jump(self):
if self.isJump:
# using 'while' doesn't work either
if self.jumpCount >= -10:
# this doesn't work -> pygame.time.delay(100)
print(self.jumpCount)
self.y += (self.jumpCount * abs(self.jumpCount)) * -0.5
self.jumpCount -= 1
else:
self.jumpCount = 10
self.isJump = False
return self.isJump
def move(self):
return
def run():
bird = Bird()
while True:
pygame.time.delay(100)
# only works if I put 'bird.isJump = True, bird.jump()' here, and then it loops continuously
surface.fill(Color("blue"))
bird.draw()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == 32:
bird.isJump = True
bird.jump()
if event.type == pygame.QUIT:
pygame.quit()
pygame.display.flip()
run()
您可以在每次运行游戏循环时调用
move
方法,以及draw
,然后在单击空格时仅调用jump
方法一次
结果将是(还有一些其他小的更改,例如调用pygame.init
,使用quit
而不是pygame.quit
退出并删除多余的类成员):
非常感谢,尽管我很好奇为什么我使用while语句或者在run中循环它都不起作用
import pygame
from pygame import Color
class Bird:
def __init__(self):
self.x = 10
self.y = 300
self.jumpCount = 10
self.isJump = False
def draw(self):
pygame.draw.rect(surface, Color("yellow"), (self.x, self.y, 10, 10))
pygame.display.flip()
def jump(self):
self.jumpCount = 10
self.isJump = True
def move(self):
if self.isJump:
if self.jumpCount >= -10:
self.y += (self.jumpCount * abs(self.jumpCount)) * -0.5
self.jumpCount -= 1
else:
self.isJump = False
def run():
bird = Bird()
while True:
pygame.time.delay(100)
surface.fill(Color("blue"))
bird.move()
bird.draw()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == 32:
bird.jump()
if event.type == pygame.QUIT:
quit()
pygame.display.flip()
pygame.init()
HEIGHT = 500
WIDTH = 400
surface = pygame.display.set_mode((HEIGHT, WIDTH))
run()