【发布时间】:2021-11-07 02:42:03
【问题描述】:
我对 Python 和 Pygame 比较陌生。我正在制作一个游戏,其中一个圆圈出现在窗口上的随机位置,你必须触摸它才能得到一个点。我已经将它编程为当你触摸圆圈时传送到另一个随机位置。问题是当我尝试检测圆圈和玩家之间的碰撞时,它基本上会不停地传送圆圈。我还制作了一个打印功能,当它检测到碰撞时打印 hi 并且它也不停地打印。我通常会尝试找出问题所在,但我真的不知道我做错了什么,我会感谢所有的帮助。
enter code here
import pygame
import random
vel = 2
pygame.init()
pygame.font.init()
fps = 60
win = pygame.display.set_mode((900, 500), pygame.RESIZABLE)
pygame.display.set_caption("Test")
#icon = pygame.image.load('icon.png')
#pygame.display.set_icon(icon)
background = pygame.image.load('Background.png')
ghost = pygame.image.load("ghost.png")
ghostrect = ghost.get_rect()
circle = pygame.image.load("circle.png")
circlerect = circle.get_rect()
def main():
a = random.randint(0, 900)
b = random.randint(0, 500)
clock = pygame.time.Clock()
run = True
while run:
keys_pressed = pygame.key.get_pressed()
if keys_pressed[pygame.K_d] and ghostrect.x + 55 <= 900:
ghostrect.x += vel
if keys_pressed[pygame.K_a] and ghostrect.x + 5 >= 0:
ghostrect.x -= vel
if keys_pressed[pygame.K_s] and ghostrect.y + 63 <= 500:
ghostrect.y += vel
if keys_pressed[pygame.K_w] and ghostrect.y >= 0:
ghostrect.y -= vel
if circlerect.colliderect(ghostrect):
a = random.randint(0, 900)
b = random.randint(0, 500)
win.blit(background, (0, 0))
win.blit(circle, (a, b))
win.blit(ghost, (ghostrect.x + 500, ghostrect.y + 210))
pygame.display.update()
clock.tick(fps)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if __name__ == "__main__":
main()
【问题讨论】:
-
你应该用
win.blit(circle, (circlerect.x, circlerect.y))画圆 -
另外,为什么要在渲染时偏移
ghostrect?win.blit(ghost, (ghostrect.x, ghostrect.y)) -
发生碰撞时,更新圆矩形:
circlerect.x, circlerect.y = a, b