Facebook
From Toxic Tamarin, 1 Year ago, written in Python.
Embed
Download Paste or View Raw
Hits: 116
  1.  
  2. #Initialize the pygame library
  3. pygame.init()
  4.  
  5. #Create the display screen
  6. screen = pygame.display.set_mode((800, 600))
  7.  
  8. #Set the caption for the display screen
  9. pygame.display.set_caption("Controlable Character")
  10.  
  11. #Set the clock
  12. clock = pygame.time.Clock()
  13.  
  14. #Define the colors
  15. white = (255, 255, 255)
  16. black = (0, 0, 0)
  17.  
  18. #Define the player
  19. player_image = pygame.image.load("player.png")
  20. player_x_position = 350
  21. player_y_position = 500
  22. velocity_x_position = 0
  23. velocity_y_position = 0
  24.  
  25. #Create the main game loop
  26. while True:
  27.     #Iterate over events
  28.     for event in pygame.event.get():
  29.         #Check if the event is a quit event
  30.         if event.type == pygame.QUIT:
  31.             #Close the game
  32.             pygame.quit()
  33.             quit()
  34.  
  35.         #Check if a key is pressed
  36.         if event.type == pygame.KEYDOWN:
  37.             #Check which key is pressed
  38.             if event.key == pygame.K_LEFT:
  39.                 velocity_x_position = -5
  40.             if event.key == pygame.K_RIGHT:
  41.                 velocity_x_position = 5
  42.             if event.key == pygame.K_UP:
  43.                 velocity_y_position = -5
  44.             if event.key == pygame.K_DOWN:
  45.                 velocity_y_position = 5
  46.  
  47.         #Check if a key is released
  48.         if event.type == pygame.KEYUP:
  49.             #Check which key is released
  50.             if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
  51.                 velocity_x_position = 0
  52.             if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
  53.                 velocity_y_position = 0
  54.    
  55.     #Update the player position
  56.     player_x_position += velocity_x_position
  57.     player_y_position += velocity_y_position
  58.  
  59.     #Fill the background
  60.     screen.fill(white)
  61.  
  62.     #Draw the player
  63.     screen.blit(player_image, (player_x_position, player_y_position))
  64.  
  65.     #Update the display
  66.     pygame.display.update()
  67.     clock.tick(60)