Pygame class 生成矩形然后消失,我如何让它留下来?
Pygame class spawns rect and then it dissapears, how do I get it to stay?
所以我正在尝试为基本游戏实现 class。它在没有 class 的情况下醒来,但现在不是生成“硬币”,而是弹出然后立即消失。不知道,因为它在主循环中。我有一个移动的“播放器”,效果很好。
这是我的代码:
class Coin_Class:
def __init__(self):
coin_1 = pygame.Rect(425, 30, 40, 40)
pygame.draw.rect(WIN, YELLOW, coin_1)
pygame.display.update()
# def coin_collect():
# if player.colliderect():
# coin_1.x = random.randint(0, 800)
# coin_1.y = random.randint(0, 250)
# pygame.event.post(pygame.event.Event(coin_collected))
# global score
# score += 1
# print(score)
coin_class = Coin_Class()
# main function loop
def main():
score_check = 0
clock = pygame.time.Clock()
run = True
while run:
# game speed
clock.tick(FPS)
# initialise pygame
pygame.init()
# checking all the events in pygame and looping them
for event in pygame.event.get():
# checking quit function is pressed
if event.type == pygame.QUIT:
run = False
pygame.quit()
exit()
keys_pressed = pygame.key.get_pressed() # recognise key presses
player_movement(keys_pressed, player) # movement function
draw_window() # create window function
coin_class
main()
# runs the main file
if __name__ == "__main__":
main()
为硬币添加抽取方法 class(每个 PEP 8 的 class 名称应该在 CapitalCase
而不是 Capital_Snake_Case
中,所以 CoinClass
):
class Coin_Class:
def __init__(self):
self.coin_1 = pygame.Rect(425, 30, 40, 40)
...
def draw(self):
pygame.draw.rect(WIN, YELLOW, self.coin_1)
并在循环中而不是使用
coin_class
您现在将使用
coin_class.draw()
其余的可以保持不变,除了从循环中删除 pygame.init()
并将其放在导入后代码开头的某个地方
所以我正在尝试为基本游戏实现 class。它在没有 class 的情况下醒来,但现在不是生成“硬币”,而是弹出然后立即消失。不知道,因为它在主循环中。我有一个移动的“播放器”,效果很好。
这是我的代码:
class Coin_Class:
def __init__(self):
coin_1 = pygame.Rect(425, 30, 40, 40)
pygame.draw.rect(WIN, YELLOW, coin_1)
pygame.display.update()
# def coin_collect():
# if player.colliderect():
# coin_1.x = random.randint(0, 800)
# coin_1.y = random.randint(0, 250)
# pygame.event.post(pygame.event.Event(coin_collected))
# global score
# score += 1
# print(score)
coin_class = Coin_Class()
# main function loop
def main():
score_check = 0
clock = pygame.time.Clock()
run = True
while run:
# game speed
clock.tick(FPS)
# initialise pygame
pygame.init()
# checking all the events in pygame and looping them
for event in pygame.event.get():
# checking quit function is pressed
if event.type == pygame.QUIT:
run = False
pygame.quit()
exit()
keys_pressed = pygame.key.get_pressed() # recognise key presses
player_movement(keys_pressed, player) # movement function
draw_window() # create window function
coin_class
main()
# runs the main file
if __name__ == "__main__":
main()
为硬币添加抽取方法 class(每个 PEP 8 的 class 名称应该在 CapitalCase
而不是 Capital_Snake_Case
中,所以 CoinClass
):
class Coin_Class:
def __init__(self):
self.coin_1 = pygame.Rect(425, 30, 40, 40)
...
def draw(self):
pygame.draw.rect(WIN, YELLOW, self.coin_1)
并在循环中而不是使用
coin_class
您现在将使用
coin_class.draw()
其余的可以保持不变,除了从循环中删除 pygame.init()
并将其放在导入后代码开头的某个地方