0% found this document useful (0 votes)
97 views

CAR GAME - Py

This document defines a function to play a simple car driving game. The function initializes a 20 unit long road with the car positioned in the middle. It then enters a loop where it displays the road, gets user input to move the car left or right, checks if the car has gone off the road, generates a random obstacle, and checks for collisions. The game ends if the user crashes or chooses to quit.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
97 views

CAR GAME - Py

This document defines a function to play a simple car driving game. The function initializes a 20 unit long road with the car positioned in the middle. It then enters a loop where it displays the road, gets user input to move the car left or right, checks if the car has gone off the road, generates a random obstacle, and checks for collisions. The game ends if the user crashes or chooses to quit.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

import random

def drive_car():
road_length = 20
car_position = road_length // 2
game_over = False

while not game_over:


# Display the road and car position
road = [' '] * road_length
road[car_position] = 'X'
print(''.join(road))

# Ask for user input


action = input("Enter 'L' to move left, 'R' to move right, or 'Q' to quit:
")
if action.upper() == 'L':
car_position -= 1
elif action.upper() == 'R':
car_position += 1
elif action.upper() == 'Q':
game_over = True
else:
print("Invalid input! Please try again.")

# Check if the car has reached the edge of the road


if car_position < 0 or car_position >= road_length:
game_over = True
print("Game over! You crashed.")

# Generate random obstacles


obstacle_position = random.randint(0, road_length - 1)
road[obstacle_position] = '#'

# Check if the car collided with an obstacle


if car_position == obstacle_position:
game_over = True
print("Game over! You crashed into an obstacle.")

drive_car()

You might also like