import pygame import sys from pygame.locals import * pygame.init() vec = pygame.math.Vector2 # 2D vector for position and velocity HEIGHT = 450 WIDTH = 400 ACC = 0.5 FRIC = -0.12 FPS = 60 FramePerSec = pygame.time.Clock() displaysurface = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Game") class Player(pygame.sprite.Sprite): def jump(self): hits = pygame.sprite.spritecollide(self, platforms, False) if hits: self.vel.y -= 15 def __init__(self): super().__init__() self.surf = pygame.Surface((30, 30)) self.surf.fill((128, 255, 40)) self.rect = self.surf.get_rect(center=(10, 420)) self.pos = vec((10, 300)) self.vel = vec((0, 0)) self.acc = vec((0, 0)) def move(self): self.acc = vec(0, 0.5) # gravity effect pressed_keys = pygame.key.get_pressed() if pressed_keys[K_LEFT]: self.acc.x = -ACC if pressed_keys[K_RIGHT]: self.acc.x = ACC # Apply friction to velocity if not moving self.acc.x += self.vel.x * FRIC self.vel += self.acc # Update velocity based on acceleration self.pos += self.vel + 0.5 * self.acc # Update position based on velocity and acceleration # Wrap around the screen horizontally if self.pos.x > WIDTH: self.pos.x = 0 if self.pos.x < 0: self.pos.x = WIDTH self.rect.midbottom = self.pos def update(self): hits = pygame.sprite.spritecollide(P1, platforms, False) if P1.vel.y > 0: if hits: self.pos.y = hits[0].rect.top + 1 # Place player on top of platform self.vel.y = 0 # Stop vertical velocity when hitting the ground 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)) # Create player and platform PT1 = Platform() P1 = Player() all_sprites = pygame.sprite.Group() all_sprites.add(PT1) all_sprites.add(P1) platforms = pygame.sprite.Group() platforms.add(PT1) 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() # Fill screen with black to clear previous frame displaysurface.fill((0, 0, 0)) # Update player movement and position P1.move() P1.update() # Draw all sprites for entity in all_sprites: displaysurface.blit(entity.surf, entity.rect) # Update the display to reflect changes pygame.display.update() # Maintain frame rate FramePerSec.tick(FPS)