|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- #导入库
- import pygame
- import sys
- from pygame.locals import *
- #初始化pygame
- pygame.init()
- #设置变量
- size = width, height = 600, 400
- bg = (255, 255, 255)
- turtle = pygame.image.load(r"C:\Users\24734\Desktop\code\img\turtle.png")
- position = turtle.get_rect()#获取图片
- screen = pygame.display.set_mode(size)
- pygame.display.set_caption('fihc demo')
- #游戏循环
- while True:
- #获取事件
- for event in pygame.event.get():
- #如果pygame事件为quit,那么久退出
- if event.type == pygame.QUIT:
- sys.exit()
- if event.type == pygame.KEYDOWN:
- if event.key == K_w:
- position = position.move((0, -5))
- #刷新
- screen.fill(bg)#刷新背景
- screen.blit(turtle, position)#刷新图像
- pygame.display.flip()#刷新
复制代码
小乌龟动不了,按下W键后乌龟还是没动
你的代码问题在于只处理了按键按下(KEYDOWN)事件,且每次按键只移动5像素(可能不明显)。同时缺少其他方向的控制和持续移动逻辑。以下是修正方案:
主要问题:
1. 只处理了W键向上移动,未处理其他方向
2. 移动步长太小(5像素)不易察觉
3. 未实现按键持续移动(需状态跟踪)
改进代码:
- import pygame
- import sys
- from pygame.locals import *
- pygame.init()
- size = width, height = 600, 400
- bg = (255, 255, 255)
- # 使用默认乌龟代替外部图片(避免路径问题)
- turtle = pygame.Surface((50, 50), pygame.SRCALPHA)
- pygame.draw.circle(turtle, (0, 200, 0), (25, 25), 20) # 绿色圆形作为乌龟
- position = turtle.get_rect(center=(300, 200)) # 初始位置居中
- speed = 8 # 增大移动速度
- screen = pygame.display.set_mode(size)
- pygame.display.set_caption('FishC Demo')
- # 移动状态跟踪
- move = {"up": False, "down": False, "left": False, "right": False}
- while True:
- for event in pygame.event.get():
- if event.type == QUIT:
- pygame.quit()
- sys.exit()
-
- # 按键按下
- if event.type == KEYDOWN:
- if event.key == K_w: move["up"] = True
- if event.key == K_s: move["down"] = True
- if event.key == K_a: move["left"] = True
- if event.key == K_d: move["right"] = True
-
- # 按键释放
- if event.type == KEYUP:
- if event.key == K_w: move["up"] = False
- if event.key == K_s: move["down"] = False
- if event.key == K_a: move["left"] = False
- if event.key == K_d: move["right"] = False
-
- # 根据状态持续移动
- if move["up"]: position.y -= speed
- if move["down"]: position.y += speed
- if move["left"]: position.x -= speed
- if move["right"]: position.x += speed
-
- # 边界检查
- position.x = max(0, min(position.x, width - position.width))
- position.y = max(0, min(position.y, height - position.height))
-
- screen.fill(bg)
- screen.blit(turtle, position)
- pygame.display.flip()
- pygame.time.delay(30) # 控制帧率
复制代码
关键改进:
1. 使用内置绘图代替外部图片(避免路径错误)
2. 增加方向键 WASD控制
3. 添加移动状态跟踪实现 持续移动
4. 移动速度提高到 8像素/帧
5. 添加边界限制防止移出屏幕
6. 增加帧率延迟使移动更平滑
按 WASD键试试,现在乌龟应该可以自由移动了!如果仍有问题,请检查PyGame是否安装正确(可通过 pip install pygame安装)
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
|
-
|