所以我最终需要为我的一个班级创建一个游戏,我想使用 pygame。所以我试图按照教程进行操作,而 pygame 无法识别键盘输入。游戏加载没有错误,但 m 角色不动。有什么帮助吗?我的代码:
#Import
import pygame
from pygame.locals import*
#initialization
pygame.init()
width, height = 640, 480
screen=pygame.display.set_mode((width, height))
#keys
keys = [False, False, False, False]
playerpos=[100,100]
#images
player = pygame.image.load("resources/images/dude.png")
grass = pygame.image.load("resources/images/grass.png")
castle = pygame.image.load("resources/images/castle.png")
#loop
while 1:
#clear screen
screen.fill(0)
#screen elements
for x in range(width/grass.get_width()+1):
for y in range(height/grass.get_height()+1):
screen.blit(grass,(x*100,y*100))
screen.blit(castle,(0,30))
screen.blit(castle,(0,135))
screen.blit(castle,(0,240))
screen.blit(castle,(0,345))
screen.blit(player,playerpos)
#update screen
pygame.display.flip()
#loop events
for event in pygame.event.get():
#check if event is the X button
if event.type==pygame.QUIT:
#key_input
if event.type == pygame.KEYDOWN:
if event.key==K_w:
keys[0]=True
elif event.key==K_a:
keys[1]=True
elif event.key==K_s:
keys[2]=True
elif event.key==K_d:
keys[3]=True
if event.type == pygame.KEYUP:
if event.key==pygame.K_w:
keys[0]=False
elif event.key==pygame.K_a:
keys[1]=False
elif event.key==pygame.K_s:
keys[2]=False
elif event.key==pygame.K_d:
keys[3]=False
#if it quits
pygame.quit()
exit(0)
#9-Move player
if keys[0]:
playerpos[1]-=5
elif keys[2]:
playerpos[1]+=5
if keys[1]:
playerpos[0]-=5
elif keys[3]:
playerpos[0]+=5
同样,当我按下 wasd 时,加载的字符不会移动。任何帮助将不胜感激,因为我正在尝试了解有关游戏开发的更多信息(:
繁星点点滴滴
相关分类