ewalkowka

player

Jan 8th, 2023
855
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.02 KB | None | 0 0
  1. import pygame
  2.  
  3. pygame.init()
  4.  
  5. SCREEN_WIDTH = 800
  6. SCREEN_HEIGH = 600
  7.  
  8. screen_surface = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGH))
  9. pygame.display.set_caption("Pierwsza Gra")
  10.  
  11. game_status = True
  12.  
  13. clock = pygame.time.Clock()
  14.  
  15. def load_image(img_path, position):
  16.     image = pygame.image.load(img_path)
  17.     surface = image.convert()
  18.  
  19.     transparent_color = (0,0,0)
  20.     surface.set_colorkey(transparent_color)
  21.  
  22.     rect = surface.get_rect(center=position)
  23.  
  24.     return [image, surface, rect]
  25.  
  26. def print_image(img_list):
  27.     #image, surface, rect
  28.     image, surface, rect = img_list
  29.     screen_surface.blit(surface, rect)
  30.     pass
  31.  
  32. def set_position(img_list, position):
  33.     image, surface, rect = img_list
  34.     rect = surface.get_rect(center=position)
  35.     return [image, surface, rect]
  36.  
  37. def calculate_player_movement(keys):
  38.     speed = 10
  39.     x = 0
  40.     y = 0
  41.  
  42.     if keys[pygame.K_LSHIFT]:
  43.         speed*=5
  44.     if keys[pygame.K_w]:
  45.         y-=speed
  46.     if keys[pygame.K_s]:
  47.         y+=speed
  48.     if keys[pygame.K_d]:
  49.         x+=speed
  50.     if keys[pygame.K_a]:
  51.         x-=speed
  52.  
  53.  
  54.     return [x, y]
  55.  
  56. def limit_position(position):
  57.     x,y = position
  58.     x = max(0, min(x, SCREEN_WIDTH))
  59.     y = max(0, min(y, SCREEN_HEIGH))
  60.  
  61.     return [x,y]
  62.  
  63. player_pos = [SCREEN_WIDTH//2, SCREEN_HEIGH//2]
  64. player = load_image('player.png', player_pos)
  65. background_color = [50, 136, 89]
  66.  
  67. while game_status:
  68.  
  69.     events = pygame.event.get()
  70.  
  71.     for event in events:
  72.         print(event)
  73.  
  74.         if event.type == pygame.QUIT:
  75.             game_status = False
  76.    
  77.     pressed_keys = pygame.key.get_pressed()
  78.  
  79.     delta_x, delta_y = calculate_player_movement(pressed_keys)
  80.  
  81.     player_pos[0] += delta_x
  82.     player_pos[1] += delta_y
  83.  
  84.     player_pos = limit_position(position=player_pos)
  85.  
  86.     player = set_position(player, player_pos)
  87.  
  88.     screen_surface.fill(background_color)
  89.     print_image(player)
  90.  
  91.     pygame.display.update()
  92.     clock.tick(10)
  93.  
  94. print("Zamykanie aplikacji")
  95. pygame.quit()
  96. quit()
Advertisement
Add Comment
Please, Sign In to add comment