Heres the code:
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()
I have it so, when I press the right/left key the image goes left and right 10 pixels. But how would I make it so when I hold the keys down, it repeats the the function, and if I let the keys go, it would stop. I have tried adding a while loop, all that does is make the guys infinitetly go to the right/left, so is there a pygame module to add this?