Untitled
unknown
plain_text
a year ago
2.0 kB
5
Indexable
import random import time import os # Define the size of the game area WIDTH = 20 HEIGHT = 5 # Initialize car position car_x = WIDTH // 2 car_y = HEIGHT - 1 # Initialize game variables score = 0 game_over = False # Function to draw the game area def draw_game(): global score # Clear the screen os.system('cls' if os.name == 'nt' else 'clear') # Draw obstacles obstacles = generate_obstacles() for y in range(HEIGHT): for x in range(WIDTH): if (x, y) == (car_x, car_y): print("C", end="") elif (x, y) in obstacles: print("#", end="") else: print(".", end="") print() # Print score print("Score:", score) # Function to generate random obstacles def generate_obstacles(): obstacles = set() for _ in range(5): # Adjust the number of obstacles as needed x = random.randint(0, WIDTH - 1) y = random.randint(0, HEIGHT - 1) obstacles.add((x, y)) return obstacles # Function to move the car def move_car(direction): global car_x if direction == "left" and car_x > 0: car_x -= 1 elif direction == "right" and car_x < WIDTH - 1: car_x += 1 # Main game loop while not game_over: draw_game() # Get user input user_input = input("Move left (l) or right (r): ").lower() # Clear the input prompt os.system('cls' if os.name == 'nt' else 'clear') # Move the car based on user input if user_input == "l": move_car("left") elif user_input == "r": move_car("right") # Update game state score += 1 # Check for collision (if car hits an obstacle) if (car_x, car_y) in generate_obstacles(): game_over = True print("Game Over!") print("Final Score:", score) break # Adjust game speed (optional) time.sleep(0.1) # Adjust speed by changing the sleep time
Editor is loading...
Leave a Comment