File size: 2,194 Bytes
ce10311 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 |
# app.py
import pygame
import random
import sys
pygame.init()
# Screen setup
WIDTH, HEIGHT = 600, 400
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Trip n’ Run")
# Colors
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 setup
player = pygame.Rect(50, HEIGHT - 70, 40, 40)
player_vel_y = 0
gravity = 0.8
is_jumping = False
# Obstacles
obstacles = []
obstacle_timer = 0
# Score
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)
# Obstacles
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
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()
# Run the game
game_loop()
|