我正在使用python 3.4.3。 在pygame事件中遇到一些麻烦。 按下提到的键(向上,向下,向左或向右)后,99%的时间,程序没有反应。绑定一个(或多个)密钥似乎是解决这个问题的唯一方法,但即使这样也是不可靠的。
代码:
import pygame
pygame.init()
size = width, height = 1024, 768
screen = pygame.display.set_mode(size,pygame.FULLSCREEN)
g = pygame.image.load(
'X:\\Projects\\Rogue\\Game Project\\src\\img\\Tiles\grass.JPG')
player = pygame.image.load('untitled.PNG')
pygame.display.set_caption('WINDOW_NAME')
run = True
def resolve(x,y):#x=32 y=20
return (x*32, y*32)
def get_tiles():
tiles = []
for y in range(0,20):
for x in range(0,32):
tiles.append(resolve(x,y))
return tiles
p = [5,5]
def draw_player(p):
screen.blit(player, resolve(p[0],p[1]))
clock = pygame.time.Clock()
def move(direction):
if direction == 'U':
if p[1]-1 < 0:
print('fail')
else:
p[1] = p[1] - 1
elif direction == 'D':
if p[1] + 1 > 20:
print('fail')
else:
p[1] = p[1] + 1
elif direction == 'L':
if p[0] - 1 < 0:
print('fail')
else:
p[0] = p[0] - 1
elif direction == 'R':
if p[0] + 1 > 32:
print('fail')
else:
p[0] = p[0] + 1
def event_handler():
for event in pygame.event.get():
print('event:',event)
if event.type == pygame.KEYDOWN or event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
quit()
elif event.key == pygame.K_p:
print('fish')
elif event.key == pygame.K_UP:
move('U')
elif event.key == pygame.K_DOWN:
move('D')
elif event.key == pygame.K_LEFT:
move('L')
elif event.key == pygame.K_RIGHT:
move('R')
elif event.type == pygame.MOUSEBUTTONDOWN:
print('a')
print(pygame.display.get4_driver())
for item in pygame.display.list_modes():
print(item)
def render(sprites):
for item in sprites:
screen.blit(g,item)
from random import randint
while run:
#if len(pygame.event.get()) > 0:
print(p)
print(pygame.event.get())
event_handler()
render(get_tiles())
draw_player(p)
#screen.fill(255,255,255)#wipe to black
pygame.display.flip()#screen updates all areas that have been blited
clock.tick(30)#30 FPS for now
pygame.quit()
此外,pygame.quit()
对我没有任何作用,因此逃脱的部分会立即杀死该程序。
答案 0 :(得分:0)
摆脱print(pygame.event.get())。摆脱事件循环中的or,因为您只是再次检查同一件事,所以它不会做任何事情,并且if语句检查鼠标按钮应该在if语句之外以检查击键。