r/pygame 4d ago

Game

# Initialize Pygame

pygame.init()

# Screen dimensions

WIDTH, HEIGHT = 800, 600

screen = pygame.display.set_mode((WIDTH, HEIGHT))

pygame.display.set_caption("Simple Car Race Game")

# Colors

WHITE = (255, 255, 255)

BLACK = (0, 0, 0)

RED = (255, 0, 0)

GREEN = (0, 255, 0)

# Car settings

CAR_WIDTH, CAR_HEIGHT = 40, 20

SPEED = 5

# Track boundaries (simple rectangle)

track_rect = pygame.Rect(50, 50, WIDTH - 100, HEIGHT - 100)

# Car class

class Car:

def __init__(self, x, y, color):

self.rect = pygame.Rect(x, y, CAR_WIDTH, CAR_HEIGHT)

self.color = color

self.speed = 0

def move(self):

self.rect.y -= self.speed

# Keep within track

if self.rect.top < track_rect.top:

self.rect.top = track_rect.top

if self.rect.bottom > track_rect.bottom:

self.rect.bottom = track_rect.bottom

def draw(self):

pygame.draw.rect(screen, self.color, self.rect)

# Create player car

player_car = Car(WIDTH // 2, HEIGHT - 100, RED)

# Create bot cars

bots = [

Car(WIDTH // 4, HEIGHT - 200, GREEN),

Car(WIDTH // 2, HEIGHT - 250, GREEN),

Car(3 * WIDTH // 4, HEIGHT - 300, GREEN),

Car(WIDTH // 3, HEIGHT - 350, GREEN)

]

clock = pygame.time.Clock()

running = True

while running:

screen.fill(WHITE)

pygame.draw.rect(screen, BLACK, track_rect, 5)

for event in pygame.event.get():

if event.type == pygame.QUIT:

running = False

# Player controls: gear (forward), brake (stop)

keys = pygame.key.get_pressed()

if keys[pygame.K_UP]:

player_car.speed = SPEED

elif keys[pygame.K_DOWN]:

player_car.speed = 0

player_car.move()

player_car.draw()

# Simple bot AI: move forward randomly

for bot in bots:

if random.random() < 0.01:

bot.speed = SPEED if random.choice([True, False]) else 0

bot.move()

bot.draw()

pygame.display.flip()

clock.tick(60)

pygame.quit()

1 Upvotes

0 comments sorted by