我希望能按住键,移动我的小黑点,然后松开键,让它停下来。但是,即使我按住键,我的if语句for key up也在执行中。这是我的代码:
manmovemaster = 0
l = 1
f1 = 0
from random import randint
from math import sin, cos, tan, pi
import pygame
from pygame.locals import*
Fps = pygame.time.Clock()
#starting variables
sw = 1200
sh = 650
r = 250
g = 250
b = 250
framerate = 40
#beginning of a man
man1x = 650
man1y = 50
mancolor=(0,0,0)
manlocation = (man1x, man1y)
Diamaterofhead = (5)
man1ymovedown = 0
man1ymoveup = False
man1xmoveright = False
man1xmoveleft = False
#game logic
while l:
pygame.init()
screen = pygame.display.set_mode((sw,sh))
pygame.display.set_caption("WGD THE GAME")
background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((r,g,b))
man1 = pygame.draw.circle(background,mancolor,(man1x,man1y),Diamaterofhead)
if man1ymovedown== True:
man1y += 1
manmovemaster = 0
if man1ymoveup == True:
man1y -= 1
if man1xmoveright == True:
man1x +=1
if man1xmoveleft == True:
man1x -=1
#screen refresh
for event in pygame.event.get():
if event.type ==pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
man1xmoveleft = True
if event.key == pygame.K_RIGHT:
man1xmoveright = True
if event.key == pygame.K_UP:
man1ymoveup = True
if event.key == pygame.K_DOWN:
man1ymovedown = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
man1xmoveleft = False
if event.key == pygame.K_RIGHT:
man1xmoveright = False
if event.key == pygame.K_UP:
man1ymoveup = False
if event.key == pygame.K_DOWN:
man1ymovedown = False
else:
screen.blit(background, (0,0))
pygame.display.flip()
pygame.time.get_ticks
Fps.tick(framerate)
改用这个:
使用pygame.key.按下()而不是pygame.event.get()始终返回按键的状态,而不仅仅是按时的状态。所以你可以按住一个键,它就会,当你释放它时,它就会停止。这也适用于对角线运动。因为它检查所有按键的状态,所以它会检查左键和右键,所以这两个键都是真的(按下)并且字符将沿对角线移动。在
https://www.pygame.org/docs/ref/key.html#pygame.key.get_pressed
然后你可以去掉所有的事件检查和布尔移动标志。而且,每次通过循环调用游戏机初始化(). 这没必要。你也不需要每次在游戏循环中设置模式,以及标题和背景
相关问题 更多 >
编程相关推荐