DEV Community

Knick Global Pvt Ltd
Knick Global Pvt Ltd

Posted on

Unleashing the Code: Python Car Game Coding Adventure

Certainly! Here's an example of a simple car game coded in Python using the Pygame library:

import pygame
import time
import random

# Initialize Pygame
pygame.init()

# Set up the game window
width = 800
height = 600
game_display = pygame.display.set_mode((width, height))
pygame.display.set_caption("Car Game")

# Set up colors
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)

# Set up the clock
clock = pygame.time.Clock()

# Set up the car attributes
car_width = 73

# Load the car image
car_img = pygame.image.load("car.png")

def car(x, y):
    game_display.blit(car_img, (x, y))

# Display message
def message(msg, color):
    font_style = pygame.font.SysFont(None, 50)
    message_render = font_style.render(msg, True, color)
    game_display.blit(message_render, [width / 6, height / 3])

# Main game loop
def game_loop():
    game_over = False
    x = width * 0.45
    y = height * 0.8
    x_change = 0

    # Game loop
    while not game_over:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_over = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    x_change = -5
                if event.key == pygame.K_RIGHT:
                    x_change = 5

            if event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                    x_change = 0

        x += x_change

        game_display.fill(white)
        car(x, y)

        # Set boundaries for the car
        if x > width - car_width or x < 0:
            game_over = True

        pygame.display.update()
        clock.tick(60)

    pygame.quit()
    quit()

# Run the game
game_loop()

Enter fullscreen mode Exit fullscreen mode

In this car game, the player controls a car using the left and right arrow keys. The objective is to navigate the car within the game window without hitting the boundaries. The game loop handles user input, updates the car's position, and checks for collisions.

Feel free to modify and enhance the code to add additional features, such as obstacles, scoring, or levels. Game coding allows for endless possibilities, so let your creativity shine and have fun exploring the world of game development!

Top comments (0)