我正在使用Pygame在Python中制作RPG。我的第一步是创建我的主角并让它移动。但它不是。这是我的代码:
import pygame,random
from pygame.locals import *
pygame.init()
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
blue = (0,255,0)
green = (0,0,255)
global screen, size, winWidth, winHeight, gameExit, pressed, mainChar, x, y
size = winWidth,winHeight = (1350,668)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("RPG")
gameExit = False
pressed = pygame.key.get_pressed()
mainChar = pygame.image.load("Main Character.png")
x,y = 655,500
def surroundings():
stoneTile = pygame.image.load("Stone Tile.png")
stoneTileSize = stoneTile.get_rect()
def move():
if pressed[K_LEFT]: x -= 1
if pressed[K_RIGHT]: x += 1
if pressed[K_UP]: y -= 1
if pressed[K_DOWN]: y += 1
def player():
move()
screen.fill(black)
screen.blit(mainChar,(x,y))
while not gameExit:
for event in pygame.event.get():
if event.type == QUIT:
gameExit = True
surroundings()
move()
player()
pygame.display.update()
pygame.quit()
quit()
请帮助我解释为什么它也不起作用。感谢。
答案 0 :(得分:1)
您必须在每次运行中更新您按下的变量
while not gameExit:
for event in pygame.event.get():
if event.type == QUIT:
gameExit = True
pressed = pygame.key.get_pressed()
surroundings()
move()
player()
pygame.display.update()
您在该移动函数中使用的值x和y被视为局部变量,您必须告诉解释器它们是全局变量
def move():
global x,y
if pressed[K_LEFT]: x -= 1
if pressed[K_RIGHT]: x += 1
if pressed[K_UP]: y -= 1
if pressed[K_DOWN]: y += 1