Write a snake game in Python, instead of WASD, use on-screen buttons
- User
Write a snake game in Python, instead of WASD, use on-screen buttons
- Assistant
Write a snake game in Python, instead of WASD, use on-screen buttons
Creating a Snake game with on-screen buttons instead of keyboard controls can be an engaging way to make the game more accessible, especially for touch interfaces or users who prefer clicking over typing. Below is a Python implementation of the classic Snake game using the tkinter library for the GUI, which includes on-screen buttons for controlling the snake's direction.
tkinter for GUI components, random for apple placement, and time for controlling the game speed.Up, Down, Left, Right) to control the snake's direction.import tkinter as tk
import random
# Constants
GAME_WIDTH = 600
GAME_HEIGHT = 400
SNAKE_SIZE = 20
APPLE_SIZE = 20
INITIAL_SNAKE_LENGTH = 3
MOVE_DELAY = 100 # milliseconds
class SnakeGame:
def __init__(self, master):
self.master = master
self.master.title("Snake Game with On-Screen Buttons")
# Initialize game state
self.direction = "Right"
self.running = True
self.snake = []
self.create_snake()
self.create_apple()
# Create Canvas
self.canvas = tk.Canvas(master, width=GAME_WIDTH, height=GAME_HEIGHT, bg="black")
self.canvas.pack()
# Draw initial snake and apple
self.draw_snake()
self.draw_apple()
# Create control buttons
self.create_buttons()
# Start the game loop
self.master.after(MOVE_DELAY, self.move_snake)
def create_buttons(self):
button_frame = tk.Frame(self.master)
button_frame.pack()
btn_up = tk.Button(button_frame, text="Up", width=10, command=lambda: self.change_direction("Up"))
btn_up.grid(row=0, column=1)
btn_left = tk.Button(button_frame, text="Left", width=10, command=lambda: self.change_direction("Left"))
btn_left.grid(row=1, column=0)
btn_down = tk.Button(button_frame, text="Down", width=10, command=lambda: self.change_direction("Down"))
btn_down.grid(row=1, column=1)
btn_right = tk.Button(button_frame, text="Right", width=10, command=lambda: self.change_direction("Right"))
btn_right.grid(row=1, column=2)
def create_snake(self):
start_x = GAME_WIDTH // 2
start_y = GAME_HEIGHT // 2
self.snake = []
for i in range(INITIAL_SNAKE_LENGTH):
self.snake.append((start_x - i * SNAKE_SIZE, start_y))
def draw_snake(self):
self.canvas.delete("snake")
for segment in self.snake:
x, y = segment
self.canvas.create_rectangle(x, y, x + SNAKE_SIZE, y + SNAKE_SIZE, fill="green", tag="snake")
def create_apple(self):
self.apple_position = (
random.randint(0, (GAME_WIDTH - APPLE_SIZE) // APPLE_SIZE) * APPLE_SIZE,
random.randint(0, (GAME_HEIGHT - APPLE_SIZE) // APPLE_SIZE) * APPLE_SIZE,
)
def draw_apple(self):
self.canvas.delete("apple")
x, y = self.apple_position
self.canvas.create_oval(x, y, x + APPLE_SIZE, y + APPLE_SIZE, fill="red", tag="apple")
def change_direction(self, new_direction):
# Prevent the snake from reversing
opposite_directions = {"Up": "Down", "Down": "Up", "Left": "Right", "Right": "Left"}
if new_direction == opposite_directions.get(self.direction):
return
self.direction = new_direction
def move_snake(self):
if not self.running:
return
head_x, head_y = self.snake[0]
if self.direction == "Up":
new_head = (head_x, head_y - SNAKE_SIZE)
elif self.direction == "Down":
new_head = (head_x, head_y + SNAKE_SIZE)
elif self.direction == "Left":
new_head = (head_x - SNAKE_SIZE, head_y)
elif self.direction == "Right":
new_head = (head_x + SNAKE_SIZE, head_y)
else:
new_head = (head_x, head_y)
# Check for collisions
if (new_head[0] < 0 or new_head[0] >= GAME_WIDTH or
new_head[1] < 0 or new_head[1] >= GAME_HEIGHT or
new_head in self.snake):
self.game_over()
return
self.snake.insert(0, new_head)
# Check if apple is eaten
if self.snake[0] == self.apple_position:
self.create_apple()
self.draw_apple()
else:
# Remove the tail
self.snake.pop()
self.draw_snake()
self.master.after(MOVE_DELAY, self.move_snake)
def game_over(self):
self.running = False
self.canvas.create_text(GAME_WIDTH//2, GAME_HEIGHT//2, text="GAME OVER", fill="white", font=("Helvetica", 24))
# Optionally, disable buttons
for widget in self.master.winfo_children():
if isinstance(widget, tk.Frame):
for btn in widget.winfo_children():
btn.config(state=tk.DISABLED)
def main():
root = tk.Tk()
game = SnakeGame(root)
root.mainloop()
if __name__ == "__main__":
main()
Initialization:
SnakeGame class initializes the game state, including the snake's initial position, direction, and placing the first apple.tkinter.Canvas is created to serve as the game area where the snake and apple are drawn.tk.Button widgets and arranged in a grid layout for directional control.Snake Representation:
(x, y) coordinates of a segment.Drawing on Canvas:
draw_snake() method renders all snake segments as green squares.draw_apple() renders the apple as a red circle at its current position.Movement Logic:
move_snake() method calculates the new head position based on the current direction.master.after(MOVE_DELAY, self.move_snake), which schedules the next move.Direction Control:
change_direction() method updates the snake's direction based on button clicks.Game Over:
Prerequisites:
tkinter is usually included with standard Python installations. If not, you may need to install it separately.Execution:
snake_game.py.snake_game.py.python snake_game.py
You can customize various aspects of the game, such as:
MOVE_DELAY constant to make the snake move faster or slower.fill parameter in create_rectangle and create_oval methods.GAME_WIDTH and GAME_HEIGHT for a larger or smaller game area.SNAKE_SIZE and APPLE_SIZE to make the snake and apple larger or smaller.To further enhance the game, consider implementing the following features:
This implementation provides a basic yet functional Snake game with on-screen buttons using Python's tkinter library. It's a great starting point for building more complex games and can be expanded with additional features and improvements based on your preferences.
Not yet included in a published release.