繼承人的代碼:Pygame鍵按住?
import pygame, sys
from pygame.locals import *
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
WHITE = (255, 255, 255)
GRASSCOLOR = GREEN
BGCOLOR = WHITE
WINDOWWIDTH = 500
WINDOWHEIGHT = 300
def main():
pygame.init()
global DISPLAYSURF
DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_caption('Platformer')
player = pygame.image.load('megaman_running_sprites_by_cobalt_blue_knight-d2y1i8s.png')
playerx = 140
playery = 10
DISPLAYSURF.fill(BGCOLOR)
DISPLAYSURF.blit(player, (10, 140))
while True: # Event handling loop
ground()
mousex, mousey = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == QUIT:
terminate()
elif event.type == KEYDOWN:
if event.key == K_RIGHT:
DISPLAYSURF.fill(BGCOLOR)
playery += 10
DISPLAYSURF.blit(player, (playery, playerx))
elif event.key == K_LEFT:
DISPLAYSURF.fill(BGCOLOR)
playery -= 10
DISPLAYSURF.blit(player, (playery, playerx))
elif event.key == K_SPACE:
DISPLAYSURF.fill(BGCOLOR)
playerx -= 15
DISPLAYSURF.blit(player, (playery, playerx))
DISPLAYSURF.fill(BGCOLOR)
playerx -= 15
DISPLAYSURF.blit(player, (playery, playerx))
DISPLAYSURF.fill(BGCOLOR)
playerx -= 10
DISPLAYSURF.blit(player, (playery, playerx))
DISPLAYSURF.fill(BGCOLOR)
playerx -= 5
DISPLAYSURF.blit(player, (playery, playerx))
elif event.type == KEYUP:
if event.key == K_SPACE:
pygame.time.wait(100)
DISPLAYSURF.fill(BGCOLOR)
playerx += 45
DISPLAYSURF.blit(player, (playery, playerx))
elif event.key == K_RIGHT:
DISPLAYSURF.fill(BGCOLOR)
DISPLAYSURF.blit(player, (playery, playerx))
pygame.display.update()
def terminate(): # Terminates the program
pygame.quit()
sys.exit()
def ground():
pygame.draw.rect(DISPLAYSURF, GRASSCOLOR, (0, 250, WINDOWWIDTH, 100))
if __name__ == '__main__':
main()
我有這樣,當我按下左/右按鍵的那張圖像左,右10個像素。但是我怎麼做到這一點,當我按下鍵時,它會重複該功能,如果我讓鍵移動,它將停止。我已經嘗試添加一個while循環,所有這些都會讓這些人無限地向右/向左移動,所以有pygame模塊來添加它嗎?
您可以使用['pygame.key'](https://www.pygame.org/docs/ref/key.html)模塊和函數['get_pressed()'](https:// www .pygame.org/docs/ref/key.html#pygame.key.get_pressed),它將返回所有正在按住的鍵。一個例子可以在這裏找到(http://stackoverflow.com/documentation/pygame/5110/event-handling/18049/state-checking#t=201612270158074583064),*鍵盤事件*下。 –