0% found this document useful (0 votes)
22 views1 page

CAR Py

This Python code defines functions to clear the screen, draw a car and obstacle at specified positions, and move the car across the screen. It uses these functions in a game loop to randomly generate obstacle positions, check for collisions, handle keyboard input to move the car, and end the game if a collision occurs by printing the score. The car position, obstacle position, and score are updated each iteration as the car moves and the player avoids obstacles.
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)
22 views1 page

CAR Py

This Python code defines functions to clear the screen, draw a car and obstacle at specified positions, and move the car across the screen. It uses these functions in a game loop to randomly generate obstacle positions, check for collisions, handle keyboard input to move the car, and end the game if a collision occurs by printing the score. The car position, obstacle position, and score are updated each iteration as the car moves and the player avoids obstacles.
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 os

import time
import random
import msvcrt

def clear_screen():
# Function to clear the screen
os.system('cls' if os.name == 'nt' else 'clear')

def draw_car(position):
# Function to draw the car at the specified position
print(' ' * position + '🚗')

def draw_obstacle(obstacle_position):
# Function to draw an obstacle at the specified position
print(' ' * obstacle_position + '🚧')

def move_car():
# Function to move the car across the screen
position = 0
score = 0
game_over = False

while not game_over:


clear_screen()
draw_car(position)

# Generate random obstacle position


obstacle_position = random.randint(0, 20)
draw_obstacle(obstacle_position)

# Check for collision


if position == obstacle_position:
game_over = True
print('Game Over!')
print(f'Your score: {score}')
break

# Handle keyboard input


if msvcrt.kbhit():
key = msvcrt.getch()
if key == b'K' and position > 0:
position -= 1
elif key == b'M' and position < 20:
position += 1

time.sleep(0.1) # Adjust the sleep duration to change the speed of the car
score += 1

if position >= 20: # Adjust the limit to change when the car reaches the
end
position = 0

# Main program
move_car()

You might also like