|
|
|
|
|
import pygame |
|
|
import random |
|
|
import sys |
|
|
|
|
|
pygame.init() |
|
|
|
|
|
|
|
|
WIDTH, HEIGHT = 600, 400 |
|
|
screen = pygame.display.set_mode((WIDTH, HEIGHT)) |
|
|
pygame.display.set_caption("Trip n’ Run") |
|
|
|
|
|
|
|
|
WHITE = (255, 255, 255) |
|
|
BLACK = (0, 0, 0) |
|
|
SKY = (135, 206, 235) |
|
|
GROUND = (139, 69, 19) |
|
|
RED = (255, 0, 0) |
|
|
|
|
|
clock = pygame.time.Clock() |
|
|
FPS = 60 |
|
|
|
|
|
font = pygame.font.SysFont(None, 36) |
|
|
|
|
|
|
|
|
player = pygame.Rect(50, HEIGHT - 70, 40, 40) |
|
|
player_vel_y = 0 |
|
|
gravity = 0.8 |
|
|
is_jumping = False |
|
|
|
|
|
|
|
|
obstacles = [] |
|
|
obstacle_timer = 0 |
|
|
|
|
|
|
|
|
score = 0 |
|
|
|
|
|
def game_loop(): |
|
|
global player_vel_y, is_jumping, obstacle_timer, score |
|
|
running = True |
|
|
while running: |
|
|
screen.fill(SKY) |
|
|
pygame.draw.rect(screen, GROUND, (0, HEIGHT - 30, WIDTH, 30)) |
|
|
|
|
|
for event in pygame.event.get(): |
|
|
if event.type == pygame.QUIT: |
|
|
running = False |
|
|
|
|
|
keys = pygame.key.get_pressed() |
|
|
if keys[pygame.K_SPACE] and not is_jumping: |
|
|
player_vel_y = -12 |
|
|
is_jumping = True |
|
|
|
|
|
player_vel_y += gravity |
|
|
player.y += player_vel_y |
|
|
|
|
|
if player.y >= HEIGHT - 70: |
|
|
player.y = HEIGHT - 70 |
|
|
is_jumping = False |
|
|
|
|
|
pygame.draw.rect(screen, RED, player) |
|
|
|
|
|
|
|
|
obstacle_timer += 1 |
|
|
if obstacle_timer > 60: |
|
|
obstacle = pygame.Rect(WIDTH, HEIGHT - 50, 30, 30) |
|
|
obstacles.append(obstacle) |
|
|
obstacle_timer = 0 |
|
|
|
|
|
for obstacle in obstacles: |
|
|
obstacle.x -= 6 |
|
|
pygame.draw.rect(screen, BLACK, obstacle) |
|
|
if player.colliderect(obstacle): |
|
|
game_over(score) |
|
|
|
|
|
|
|
|
score += 1 |
|
|
score_text = font.render(f"Score: {score}", True, BLACK) |
|
|
screen.blit(score_text, (10, 10)) |
|
|
|
|
|
pygame.display.flip() |
|
|
clock.tick(FPS) |
|
|
|
|
|
pygame.quit() |
|
|
sys.exit() |
|
|
|
|
|
def game_over(score): |
|
|
screen.fill(WHITE) |
|
|
text = font.render(f"Game Over! Score: {score}", True, BLACK) |
|
|
screen.blit(text, (WIDTH // 2 - 100, HEIGHT // 2)) |
|
|
pygame.display.flip() |
|
|
pygame.time.wait(2000) |
|
|
pygame.quit() |
|
|
sys.exit() |
|
|
|
|
|
|
|
|
game_loop() |
|
|
|