我正在尝试在 pygame 中制作一个目标训练器。然而,当我点击敌人时,程序不会执行击中(我不认为)我可以听到声音,但敌人并没有消失。当我单击目标时,它应该消失,并在屏幕上生成一组新的目标。我对编码非常陌生,因此非常感谢任何帮助。
def game(difficulty):
config = populateConfig(difficulty)
pygame.mouse.set_visible(False)
mouseY = (WINDOWHEIGHT / 2)
mouseX = (WINDOWWIDTH / 2)
pointerImg_rect = pointerImg.get_rect()
tickCounter = 0
enemies = []
amountOfEnemies = 0
score = 0
FPS = 75
hitShots = 0
totalShots = 0
STARTINGTIME = config.get("time")
CIRCLERADIUS = 150
while True:
if(config.get("time") <= 0):
gameOver(totalShots, hitShots, difficulty, score)
tickCounter += 1
if(tickCounter % FPS == 0):
config["time"] -= 1
windowSurface.fill(WHITE)
if (amountOfEnemies == 0):
config["time"] = STARTINGTIME
while(amountOfEnemies != config.get("maxAmountOfEnemies")):
enemies.append(pygame.Rect((random.randint(0,WINDOWWIDTH - config.get("enemySize"))),
(random.randint(0,WINDOWHEIGHT - config.get("enemySize"))),
config.get("enemySize"), config.get("enemySize")))
if enemies[amountOfEnemies].topleft[0] < 135 and enemies[amountOfEnemies].topleft[1] < 65:
enemies.pop(amountOfEnemies)
else:
amountOfEnemies += 1
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
pass
if event.type == KEYUP:
if event.key == K_ESCAPE:
terminate()
if event.type == MOUSEMOTION:
pointer_rect.center = event.pos
if event.type == MOUSEBUTTONDOWN:
pygame.mixer.Channel(0).play(shootSound)
totalShots += 1
for enemy in enemies[:]:
if mouseX > enemy.topleft[0] and mouseX < enemy.bottomright[0]\ **this is the issue*
and mouseY > enemy.topleft[1] and mouseY < enemy.bottomright[1]:
pygame.mixer.Channel(1).play(hitSound)
enemies.remove(enemy)
amountOfEnemies -= 1
score += 1
hitShots += 1
for enemy in enemies:
windowSurface.blit(targetImage, enemy)
windowSurface.blit(pointerImg, pointer_rect)
drawText("Time: " + str(config.get("time")), windowSurface, 8,8)
drawText("Score: " + str(score), windowSurface, 8,38)
pygame.display.update()
mainClock.tick(FPS)
Menu()```
最佳答案
MOUSEBUTTONDOWN
事件有一个 pos
属性,其中包含按下按钮时鼠标光标的位置。
使用它来代替 mouseX
和 mouseY
(您永远不会更新到当前鼠标位置,因此毫无用处)。
此外,由于 enemies
是 Rect
实例的列表,因此您可以利用此类的一些方便的函数,例如 collidepoint
.
所以你的代码可能如下所示:
...
for enemy in enemies[:]:
if enemy.collidepoint(event.pos):
pygame.mixer.Channel(1).play(hitSound)
...
关于python - pygame 中的命中检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61207051/