问题描述
我在网上查看了许多 YouTube 视频和信息,但似乎找不到答案。每次我运行代码时,文本都会显示零,但是当点击敌人获得积分时,数字 1 与零重叠并且不会改变。这个问题一遍又一遍地重复。我/我能做什么?我是 Python 代码的新手,可能会有一些不必要的代码,所以如果您看到新手错误,请记住这一点,谢谢。
import pygame
import time
import random
pygame.init()
from pygame.locals import *
white = (255,255,255)
window = pygame.display.set_mode((800,600))
pygame.display.set_caption("Extended Essay game")
BADGUY = pygame.image.load('enemy.png')
pygame.font.init()
#Enemy char
class Enemy():
def __init__(self,x,y):
self.x = x
self.y = y
def main():
run = True
FPS = 60
x = 0
enemies = 0
clock = pygame.time.Clock()
font = pygame.font.Font('freesansbold.ttf',32)
window.fill((255,255))
window.blit(BADGUY,(0,0))
def update():
text = font.render("Enemies: " + str(enemies),True,0))
window.blit(text,(200,300))
pygame.display.update()
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
window.blit(BADGUY,(random.randint(0,700),random.randint(0,700)))
enemies += 1
update()
main()
解决方法
您需要先清除屏幕,然后才能在屏幕上放置新东西。将其放在 update()
的开头或在循环中调用它之前:
window.fill((255,255,255))