Untitled
pip install pygame import pygame import sys # Initialize pygame pygame.init() # Set up display SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption("Super Mario-like Game") # Define colors WHITE = (255, 255, 255) BLACK = (0, 0, 0) BLUE = (0, 0, 255) GREEN = (0, 255, 0) # Define the player class class Mario(pygame.sprite.Sprite): def __init__(self): super().__init__() self.image = pygame.Surface((50, 50)) self.image.fill(BLUE) self.rect = self.image.get_rect() self.rect.x = 100 self.rect.y = SCREEN_HEIGHT - 150 self.velocity_y = 0 self.on_ground = False def update(self): # Handle movement keys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: self.rect.x -= 5 if keys[pygame.K_RIGHT]: self.rect.x += 5 # Handle jumping if self.on_ground and keys[pygame.K_SPACE]: self.velocity_y = -15 # Jump speed self.on_ground = False # Gravity effect self.velocity_y += 1 # Gravity self.rect.y += self.velocity_y # Prevent player from falling through the ground if self.rect.bottom > SCREEN_HEIGHT - 50: self.rect.bottom = SCREEN_HEIGHT - 50 self.velocity_y = 0 self.on_ground = True # Create sprite groups all_sprites = pygame.sprite.Group() player = Mario() all_sprites.add(player) # Main game loop clock = pygame.time.Clock() while True: # Event handling for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() # Update all sprites all_sprites.update() # Fill the screen with a background color screen.fill(WHITE) # Draw all sprites all_sprites.draw(screen) # Update the display pygame.display.flip() # Set the game frame rate clock.tick(60) python mario_game.py
Leave a Comment