Итак, я использовал другой ответ , чтобы помочь мне найти простой способ перевести мой игровой спрайт в Pygame. Единственная проблема заключается в том, что кнопки перемещения должны быть спамированы, чтобы спрайт перемещался больше, чем на пять пикселей, указанных при каждом нажатии кнопки.
Вот код в полном объеме. Рассматриваемые области - класс Player () и "player". Области в цикле:
import pygame
player_path = "downChara.png" #specifies image path
class Player(object): #representitive of the player's overworld sprite
def __init__(self):
self.image = pygame.image.load(player_path).convert_alpha() #creates image, the player_path variable allowing it to be updated
self.X = 284; # x co-ord of player
self.Y = 184; # y co-ord of player
def handle_keys(self): #handling the keys/inputs
key = pygame.key.get_pressed()
dist = 5 #distance travelled in one frame of the program
if key[pygame.K_DOWN]: #if down
self.Y += dist #move down the length of dist
player_path = "downChara.png" #change image to down
self.image = pygame.image.load(player_path).convert_alpha()
elif key[pygame.K_UP]: #if up
self.Y -= dist #move up the length of dist
player_path = "upChara.png" #change to up
self.image = pygame.image.load(player_path).convert_alpha()
if key[pygame.K_RIGHT]: #etc.
self.X += dist
player_path = "rightChara.png"
self.image = pygame.image.load(player_path).convert_alpha()
elif key[pygame.K_LEFT]:
self.X -= dist
player_path = "leftChara.png"
self.image = pygame.image.load(player_path).convert_alpha()
def draw(self, surface): #draw to the surface/screen
surface.blit(self.image, (self.X, self.Y))
pygame.init() (width, height) = (600, 400) #specify window resolution bg_colour = (100,20,156) #specify bg colour
screen = pygame.display.set_mode((width, height)) #create window pygame.display.set_caption('EduGame') #specify window name
player = Player() clock = pygame.time.Clock()
pygame.display.flip() #paints screen gameRun = True #allow game events to loop/be carried out more than once
while gameRun: #while game is running:
for event in pygame.event.get(): #all the events (movement, etc) to be here.
if event.type == pygame.QUIT: #if the "x" is pressed
pygame.quit() #quit game
gameRun = False #break the loop.
quit()
player.handle_keys() #handle keys
screen.fill(bg_colour) #draw background colour
player.draw(screen) #draws player
pygame.display.update()
clock.tick(40)
вот конкретные области, которые я упомянул:
class Player(object): #representitive of the player's overworld sprite
def __init__(self):
self.image = pygame.image.load(player_path).convert_alpha() #creates image, the player_path variable allowing it to be updated
self.X = 284; # x co-ord of player
self.Y = 184; # y co-ord of player
def handle_keys(self): #handling the keys/inputs
key = pygame.key.get_pressed()
dist = 5 #distance travelled in one frame of the program
if key[pygame.K_DOWN]: #if down
self.Y += dist #move down the length of dist
player_path = "downChara.png" #change image to down
self.image = pygame.image.load(player_path).convert_alpha()
elif key[pygame.K_UP]: #if up
self.Y -= dist #move up the length of dist
player_path = "upChara.png" #change to up
self.image = pygame.image.load(player_path).convert_alpha()
if key[pygame.K_RIGHT]: #etc.
self.X += dist
player_path = "rightChara.png"
self.image = pygame.image.load(player_path).convert_alpha()
elif key[pygame.K_LEFT]:
self.X -= dist
player_path = "leftChara.png"
self.image = pygame.image.load(player_path).convert_alpha()
def draw(self, surface): #draw to the surface/screen
surface.blit(self.image, (self.X, self.Y))
и
player.handle_keys() #handle keys
screen.fill(bg_colour) #draw background colour
player.draw(screen) #draws player
"игрок". отсутствует в цикле event.type if / elif, однако, когда я пытаюсь поместить его в "event.type == pygame.KEYDOWN", это, похоже, не дает никакого эффекта.
Это не обязательно серьезная ошибка, поскольку я могу попытаться адаптировать свою игру к ней, однако я думаю, что игра будет работать и выглядеть более гладко, если игрок сможет просто удерживать соответствующую клавишу (ы) вместо спама - ловим их на десятилетие, чтобы попытаться ориентироваться.
(в качестве бонуса не стесняйтесь пытаться найти лучший способ обновления пути / местоположения спрайтов, чем то, что я делал в функции "def handle_keys (self)")
ура