|
发表于 2024-5-5 08:42:46
|
显示全部楼层
看起来你已经实现了一个可移动的地图,这是个不错的开始!不过我注意到你在代码中有几处缺失,让我帮你填一下:
首先,在精灵定义的部分,你没有给Jl类的初始化方法传递speed参数。我建议你在创建jl对象时,传入一个起始速度值,比如(0, 0),表示一开始jl对象不会移动。
其次,你在事件处理的部分,当按下键盘的上下左右键时,你应该为jl.speed赋予一个合适的速度值,比如(-1, 0)表示向左移动,或者(1, 0)表示向右移动。
最后,当按键弹起时,你可以将jl.speed设置为(0, 0),以停止jl对象的移动。
下面是修改后的代码:
- import pygame
- import sys
- from pygame.locals import *
- class Jl(pygame.sprite.Sprite):
- def __init__(self, image, speed):
- pygame.sprite.Sprite.__init__(self)
- self.image = pygame.image.load(image)
- self.rects = pygame.Rect(0, 0, 300, 300)
- self.speed = speed
- self.width = self.image.get_width()
- self.height = self.image.get_height()
- def move(self):
- self.rects.move_ip(self.speed)
- size = w, h = 300, 300
- pygame.init()
- screen = pygame.display.set_mode(size)
- pygame.display.set_caption("第一个游戏")
- jl = Jl("background.png", (0, 0))
- clock = pygame.time.Clock()
- while True:
- for event in pygame.event.get():
- if event.type == QUIT:
- pygame.quit()
- sys.exit()
- if event.type == KEYDOWN:
- if event.key == K_LEFT:
- jl.speed = (-1, 0)
- if event.key == K_RIGHT:
- jl.speed = (1, 0)
- if event.key == K_UP:
- jl.speed = (0, -1)
- if event.key == K_DOWN:
- jl.speed = (0, 1)
- if event.type == KEYUP:
- jl.speed = (0, 0)
-
- jl.move()
- if jl.rects.left < 0:
- jl.rects.left = 0
- if jl.rects.right > jl.width:
- jl.rects.right = jl.width
- if jl.rects.top < 0:
- jl.rects.top = 0
- if jl.rects.bottom > jl.height:
- jl.rects.bottom = jl.height
- screen.fill((255, 255, 255))
- screen.blit(jl.image.subsurface(jl.rects), (0, 0))
- pygame.display.flip()
- clock.tick(50)
复制代码
希望这次能顺利运行!记得将图片文件 `background.png` 放在正确的路径下,并在代码中指定它的位置。祝你好运!
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|