import pygame import sys # Initialize Pygame pygame.init() # Constants WIDTH, HEIGHT = 800, 600 FPS = 60 GRAVITY = 0.5 JUMP_STRENGTH = 10 # Colors WHITE = (255, 255, 255) BLACK = (0, 0, 0) BLUE = (0, 0, 255) # Player class class Player: def __init__(self): self.rect = pygame.Rect(100, HEIGHT - 150, 50, 50) self.color = BLUE self.velocity_y = 0 self.on_ground = False def jump(self): if self.on_ground: self.velocity_y = -JUMP_STRENGTH self.on_ground = False def move(self): self.velocity_y += GRAVITY self.rect.y += self.velocity_y # Ground collision if self.rect.y >= HEIGHT - self.rect.height: self.rect.y = HEIGHT - self.rect.height self.on_ground = True self.velocity_y = 0 def draw(self, surface): pygame.draw.rect(surface, self.color, self.rect) # Platform class class Platform: def __init__(self, x, y, width, height): self.rect = pygame.Rect(x, y, width, height) def draw(self, surface): pygame.draw.rect(surface, BLACK, self.rect) # Main function def main(): screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Jumping Game") clock = pygame.time.Clock() player = Player() platforms = [ Platform(50, HEIGHT - 100, 300, 20), Platform(400, HEIGHT - 200, 200, 20), Platform(650, HEIGHT - 300, 150, 20) ] while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: player.jump() player.move() # Check for collisions with platforms for platform in platforms: if player.rect.colliderect(platform.rect) and player.velocity_y >= 0: player.rect.y = platform.rect.top - player.rect.height player.on_ground = True player.velocity_y = 0 # Clear the screen screen.fill(WHITE) # Draw platforms and player for platform in platforms: platform.draw(screen) player.draw(screen) pygame.display.flip() clock.tick(FPS) if __name__ == "__main__": main()