pygame搭配tkinter使用时圆形边缘反弹碰撞检测失效无画面求助
Pygame圆形移动回弹问题修复说明
错误原因
- 碰撞检测逻辑内嵌无限死循环:当任意圆形横坐标满足
circleobj.x >= 475时,代码进入while True循环后无法跳出,程序卡死,永远执行不到屏幕渲染的pygame.display.update()步骤,因此屏幕始终为空白。 - 缺少移动方向控制逻辑:当前代码仅实现圆形单向向右移动,没有为每个圆形存储移动方向的属性,碰到边缘后没有反向移动的规则,无法实现回弹效果。
- 未处理左边界碰撞:仅检测了右侧屏幕边缘,没有判断圆形碰到左侧边缘的情况,不符合完整回弹需求。
修复后完整代码
import random import pygame pygame.init() from pygame.locals import * screen = pygame.display.set_mode((500,500)) pygame.display.set_caption("THING") blue = (0,0,255) black = (0,0,0) listy = [] x = 25 y = 25 clock = pygame.time.Clock() class Circle: def __init__(self,radius,x,y,color): self.radius = radius self.x = x self.y = y self.color = color # 新增横向移动速度属性,正负代表方向,数值代表步长 self.speed_x = random.randint(1,5) def draw_circle(self): pygame.draw.circle(screen,self.color,(self.x,self.y),self.radius,3) for thingamabobber in range(1,4,1): x = 25 for loop in range(1,11,1): circleobj = Circle(25,x,y,blue) listy.append(circleobj) x = x + 50 y = y + 50 while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() exit() clock.tick(60) screen.fill(black) for circleobj in listy: circleobj.draw_circle() # 按预设速度移动 circleobj.x = circleobj.x + circleobj.speed_x # 碰撞左右边缘时反向 if circleobj.x >= 475 or circleobj.x <= 25: circleobj.speed_x *= -1 pygame.display.update()
内容的提问来源于stack exchange,提问作者VirtualSquares
相关产品推荐
相关产品推荐

