我试图在pygame中进行塔防游戏。当我点击屏幕时,我希望它能够将塔精灵移动到该位置。目前,当我运行程序时,它会在没有点击的情况下将精灵移动到光标,然后不允许我再次移动它。
import pygame
import time
pygame.init()
WINDOWWIDTH = 1800
WINDOWHEIGHT = 1800
screen = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
background_colour = (188,69,80)
GAMETITLE = "Tower Defence"
def main():
pygame.display.set_caption(GAMETITLE)
clock = pygame.time.Clock()
spritegroup =pygame.sprite.Group()
sprite =pygame.sprite.Sprite()
tower = sprite.image = pygame.image.load("tower.png")
sprite.image = tower
sprite.rect = sprite.image.get_rect()
sprite.rect.x = 10
sprite.rect.y = 10
sprite.add(spritegroup)
while True:
screen.fill(background_colour)
pygame.draw.rect(screen, (255,255,255), ((0, 100), (1100, 90)))
pygame.draw.rect(screen, (255, 255,255), ((1010, 100), (100, 600)))
pygame.draw.rect(screen, (255,255,255), ((1010, 700), (2400, 90)))
spritegroup.draw(screen)
pygame.display.update()
clock.tick(30)
if pygame.mouse.get_pressed():
cursorPos = pygame.mouse.get_pos()
sprite.rect.x = cursorPos[0]
sprite.rect.y = cursorPos[1]
main()的
答案 0 :(得分:0)
正在发生的事情是pygame.mouse.get_pressed()
返回一个元组。如果语句不为null,则返回true。这意味着无论是否按下它都将返回True。则pygame事件队列将充满鼠标事件,并且永远不会得到处理。您的事件循环应类似于:
for event in pygame.event.get():
if event.type == pygame.event.QUIT:
pygame.quit()
if event.type == pygame.MOUSEBUTTONDOWN:
#stuff to do on click