gpt-4o-mini-2024-07-18· OpenAI
WildChat-4.8M (AI2)
generate code for turn-based snake
- User
generate code for turn-based snake
- Assistant
generate code for turn-based snake
Creating a simple turn-based snake game involves several components, such as the game board, snake movement, food generation, scoring, and basic user input handling. Here’s a basic implementation in Python using the console for input and output. This example focuses on a simple command-line interface to allow for turn-based gameplay.
import random
import os
import sys
import time
# Constants
WIDTH = 20
HEIGHT = 10
INITIAL_SNAKE_LENGTH = 3
SNAKE_SYMBOL = 'O'
FOOD_SYMBOL = '*'
# Directions
UP = 'w'
DOWN = 's'
LEFT = 'a'
RIGHT = 'd'
class Game:
def __init__(self):
self.snake = [(WIDTH // 2, HEIGHT // 2 + i) for i in range(INITIAL_SNAKE_LENGTH)]
self.direction = RIGHT
self.food_position = self.place_food()
self.score = 0
self.game_over = False
def place_food(self):
while True:
pos = (random.randint(0, WIDTH-1), random.randint(0, HEIGHT-1))
if pos not in self.snake:
return pos
def change_direction(self, new_direction):
opposite_directions = {UP: DOWN, DOWN: UP, LEFT: RIGHT, RIGHT: LEFT}
if new_direction in opposite_directions and opposite_directions[new_direction] == self.direction:
return # Prevent reversing direction
self.direction = new_direction
def update(self):
if self.game_over:
return
head_x, head_y = self.snake[0]
if self.direction == UP:
head_y -= 1
elif self.direction == DOWN:
head_y += 1
elif self.direction == LEFT:
head_x -= 1
elif self.direction == RIGHT:
head_x += 1
if (head_x, head_y) in self.snake or \
head_x < 0 or head_x >= WIDTH or \
head_y < 0 or head_y >= HEIGHT:
self.game_over = True
return
self.snake.insert(0, (head_x, head_y))
if (head_x, head_y) == self.food_position:
self.score += 1
self.food_position = self.place_food()
else:
self.snake.pop()
def draw(self):
os.system('cls' if os.name == 'nt' else 'clear')
board = [[' ' for _ in range(WIDTH)] for _ in range(HEIGHT)]
for y in range(HEIGHT):
for x in range(WIDTH):
if (x, y) in self.snake:
board[y][x] = SNAKE_SYMBOL
elif (x, y) == self.food_position:
board[y][x] = FOOD_SYMBOL
for row in board:
print(' '.join(row))
print(f"Score: {self.score}")
def main():
game = Game()
print("Control the snake using 'w', 'a', 's', 'd'.")
print("Press 'q' to quit.")
while not game.game_over:
game.draw()
command = input("Enter command: ").lower()
if command in [UP, DOWN, LEFT, RIGHT]:
game.change_direction(command)
elif command == 'q':
break
game.update()
time.sleep(0.5) # Delay to make it turn-based
print("Game Over! Your final score is:", game.score)
if __name__ == "__main__":
main()
snake_game.py.python snake_game.py.w, a, s, d to control the snake:
w: ups: downa: leftd: rightq to exit the game.Not yet included in a published release.