gpt-3.5-turbo-0301· openai
Suzhen/CodeChat
Hi, can you give sample pygame code for a simple game?
- User
Hi, can you give sample pygame code for a simple game?
- Assistant
Sure, here is an example of a very simple Pygame game that involves moving a character and avoiding obstacles:
import pygame # initialize Pygame pygame.init() # set screen dimensions screen_width = 800 screen_height = 600 screen = pygame.display.set_mode((screen_width, screen_height)) # set title and icon pygame.display.set_caption("Simple Game") icon = pygame.image.load('icon.png') pygame.display.set_icon(icon) # set character position and movement speed character_img = pygame.image.load('character.png') character_width = 64 character_height = 64 character_x = screen_width / 2 - character_width / 2 character_y = screen_height - character_height - 10 character_speed = 5 # set obstacle position and movement speed obstacle_img = pygame.image.load('obstacle.png') obstacle_width = 32 obstacle_height = 32 obstacle_x = screen_width / 2 - obstacle_width / 2 obstacle_y = 0 obstacle_speed = 5 # set game loop to run until user quits running = True while running: # check for events for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # move character left or right based on key input keys = pygame.key.get_pressed() if keys[pygame.K_LEFT] and character_x > 0: character_x -= character_speed elif keys[pygame.K_RIGHT] and character_x < screen_width - character_width: character_x += character_speed # move obstacle down the screen and reset if it goes off-screen obstacle_y += obstacle_speed if obstacle_y > screen_height: obstacle_x = pygame.time.get_ticks() % (screen_width - obstacle_width) obstacle_y = 0 # draw screen screen.fill((255, 255, 255)) screen.blit(character_img, (character_x, character_y)) screen.blit(obstacle_img, (obstacle_x, obstacle_y)) # check for collision between character and obstacle character_rect = pygame.Rect(character_x, character_y, character_width, character_height) obstacle_rect = pygame.Rect(obstacle_x, obstacle_y, obstacle_width, obstacle_height) if character_rect.colliderect(obstacle_rect): print("Game over!") running = False # update screen pygame.display.update() # quit Pygame pygame.quit()