# Imports import pygame import sys from pygame.locals import * from pygame.sprite import AbstractGroup # Initializing pygame pygame.init() # Two-dimensional vector utility vec = pygame.math.Vector2 # Constants and variables HEIGHT = 450 WIDTH = 400 ACC = 0.5 FRIC = -0.12 FPS = 60 # Set up the game clock FramePerSec = pygame.time.Clock() # Create the display window displaysurface = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Platformer Game") # Creating the Player class class Player(pygame.sprite.Sprite): def __init__(self): super().__init__() self.surf = pygame.Surface((30, 30)) self.surf.fill((128, 255, 40)) self.rect = self.surf.get_rect() self.pos = vec((10, 385)) self.vel = vec(0, 0) self.acc = vec(0, 0) def move(self): # Reset the value of acceleration to zero self.acc = vec(0, 0.5) pressed_keys = pygame.key.get_pressed() # Left and Right Movement if pressed_keys[K_LEFT]: self.acc.x = -ACC if pressed_keys[K_RIGHT]: self.acc.x = ACC # Apply velocity and friction self.acc.x += self.vel.x * FRIC self.vel += self.acc self.pos += self.vel + 0.5 * self.acc # Handle "screen warping" if self.pos.x > WIDTH: self.pos.x = 0 if self.pos.x < 0: self.pos.x = WIDTH # Update the rect object to the new position self.rect.midbottom = self.pos def update(self): hits = pygame.sprite.spritecollide(P1 , platforms, False) if P1.vel.y > 0: if hits: self.vel.y = 0 self.pos.y = hits[0].rect.top + 1 def jump(self): hits = pygame.sprite.spritecollide(self, platforms, False) if hits: self.vel.y = -15 # Creating the Platform class class platform(pygame.sprite.Sprite): def __init__(self): super().__init__() self.surf = pygame.Surface((WIDTH, 20)) self.surf.fill((255, 0, 0)) self.rect = self.surf.get_rect(center=(WIDTH/2, HEIGHT - 10)) # Create instances of Player and Platform PT1 = platform() P1 = Player() # Create a group for all game sprites and add them all_sprites = pygame.sprite.Group() all_sprites.add(PT1) all_sprites.add(P1) platforms = pygame.sprite.Group() platforms.add(PT1) # Main game loop while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: P1.jump() # Move the player P1.move() # Update the player's collision and position P1.update() displaysurface.fill((0, 0, 0)) # Draw all entities on the display surface for entity in all_sprites: displaysurface.blit(entity.surf, entity.rect) # Update the display pygame.display.update() FramePerSec.tick(FPS)