File size: 2,046 Bytes
5a64e21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# Define the grid size and the snake's starting position
grid_size = 10
snake_start_x = 5
snake_start_y = 3

# Define the snake's direction and length
snake_direction = 'right'
snake_length = 3

# Create an empty list to store the grid values
grid = [None] * (grid_size * grid_size)

# Initialize the grid with walls
for y in range(grid_size):
 for x in range(grid_size):
 if x == snake_start_x and y == snake_start_y:
 grid[y * grid_size + x] = 1
 else:
 grid[y * grid_size + x] = 0

# Define the game loop
while True:
 # Get the user's input
 input_direction = input("Enter a direction (left, right, up, or down): ")

 # Check if the user has entered a valid direction
 if input_direction not in ['left', 'right', 'up', 'down']:
 print("Invalid direction. Please enter a valid direction.")
 continue

 # Update the snake's direction
 snake_direction = input_direction

 # Move the snake
 for _ in if snake_direction == 'right':
 grid[(grid_size - 1) * grid_size + snake_start_x] = 2
 grid[grid_size * snake_start_x + snake_start_y] = 2
 elif snake_direction == 'left':
 grid[grid_size * snake_start_x + snake_start_y] = 2
 grid[(grid_size - 1) * grid_size + snake_start_x] = 2
 elif snake_direction == 'up':
 grid[grid_size * snake_start_x + snake_start_y - 1] = 2
 grid[(grid_size - 1) * grid_size + snake_start_x] = 2
 elif snake_direction == 'down':
 grid[grid_size * snake_start_x + snake_start_y + 1] = 2
 grid[(grid_size - 1) * grid_size + snake_start_x] = 2

 # Check for collisions with the wall or the snake's tail
 if grid[grid_size * snake_start_x + snake_start_y] == 2:
 print("Game over! You have crashed into the wall.")
 break
 elif grid[(grid_size - 1) * grid_size + snake_start_x] == 2:
 print("Game over! You have crashed into your own tail.")
 break

 # Print the updated grid
 for y in range(grid_size):
 for x in range(grid_size):
 print(grid[y * grid_size + x], end=' ')
 print()

 # Ask the user if they want to play again
 ask_again = input("Do you want to play again? (yes/no): ")
 if ask_again.lower() != 'yes':
 break