#!/usr/bin/env python # coding: utf-8 # ## Snake Game using turtle module in python # - This is a simple snake game using turtle module in python. Important python modules used in this project are turtle, random, tkinter, and time. # - The snake game is a single-player game. The objective of the game is to feed the snake with food that randomly appears on the screen. The snake grows in length as it eats the food. The game ends when the snake either collides with the wall or with itself. # # ## How to play the game # # - The snake can be controlled using the arrow keys on the keyboard. # - The game can be restarted by pressing the enter key. # - The game can be exited by clicking on the screen. # > Below is the snapshot of the game. # # ![Snake Game](game_demo.png) # In[1]: # define Food from turtle import Turtle import random class Food(Turtle): """ The Food class represents the food in the snake game. It inherits from the Turtle class. """ def __init__(self): """ Initialize a new Food object. The food is represented as a green circle. """ super().__init__() self.shape("circle") self.penup() self.shapesize(stretch_len=0.5, stretch_wid=0.5) self.color("green") self.speed("fastest") self.refresh() def refresh(self): """ Move the food to a new random location within the game boundaries. """ random_x = random.randint(-280, 280) random_y = random.randint(-280, 280) self.goto(random_x, random_y) # In[2]: # define scoreboard from turtle import Turtle ALIGNMENT = "center" FONT = ("Courier", 24, "normal") class Scoreboard(Turtle): """ The Scoreboard class represents the scoreboard in the snake game. It inherits from the Turtle class. """ def __init__(self): """ Initialize a new Scoreboard object. The scoreboard starts with a score of 0 and is displayed at the top of the screen. """ super().__init__() self.score = 0 self.color("white") self.penup() self.goto(0, 270) self.hideturtle() self.update_scoreboard() def update_scoreboard(self): """ Update the display of the scoreboard to show the current score. """ self.write(f"Current Score: {self.score}", align=ALIGNMENT, font=FONT) def game_over(self, message): """ Display a "GAME OVER" message at the center of the screen. """ self.goto(0, 0) self.write("GAME OVER!" + f" You {message}", align=ALIGNMENT, font=FONT) def increase_score(self): """ Increase the score by 1 and update the scoreboard to reflect the new score. """ self.score += 1 self.clear() self.update_scoreboard() # In[3]: ## snake properties from turtle import Turtle STARTING_POSITIONS = [(0, 0), (-20, 0), (-40, 0)] MOVE_DISTANCE = 10 UP = 90 DOWN = 270 LEFT = 180 RIGHT = 0 def reset_game(): """ Reset the game by creating new instances of Snake, Food, and Scoreboard. """ print("reset") snake = Snake() food = Food() scoreboard = Scoreboard() return snake, food, scoreboard class Snake: """ The Snake class represents the snake in the snake game. """ def __init__(self): """ Initialize a new Snake object. The snake starts with a few segments and a head. """ self.segments = [] self.create_snake() self.head = self.segments[0] def create_snake(self): """ Create the initial snake at the starting positions. """ for position in STARTING_POSITIONS: self.add_segment(position) def add_segment(self, position): """ Add a new segment to the snake at the given position. """ new_segment = Turtle("square") new_segment.color("white") new_segment.penup() new_segment.goto(position) self.segments.append(new_segment) def extend(self): """ Extend the snake by adding a new segment at the position of the last segment. """ self.add_segment(self.segments[-1].position()) def move(self): """ Move the snake forward by moving each segment to the position of the previous segment. """ for seg_num in range(len(self.segments) - 1, 0, -1): new_x = self.segments[seg_num - 1].xcor() new_y = self.segments[seg_num - 1].ycor() self.segments[seg_num].goto(new_x, new_y) self.head.forward(MOVE_DISTANCE) def up(self): """ Change the heading of the snake's head to up, unless it's currently heading down. """ if self.head.heading() != DOWN: self.head.setheading(UP) def down(self): """ Change the heading of the snake's head to down, unless it's currently heading up. """ if self.head.heading() != UP: self.head.setheading(DOWN) def left(self): """ Change the heading of the snake's head to left, unless it's currently heading right. """ if self.head.heading() != RIGHT: self.head.setheading(LEFT) def right(self): """ Change the heading of the snake's head to right, unless it's currently heading left. """ if self.head.heading() != LEFT: self.head.setheading(RIGHT) def reset(self): """ Reset the snake by creating new instances of Snake, Food, and Scoreboard. """ # for seg in self.segments: # seg.goto(1000, 1000) print("reset") snake, food, scoreboard = reset_game() return snake, food, scoreboard # In[4]: ## run game from turtle import Screen import time # Set up the screen for the game screen = Screen() screen.setup(width=600, height=600) # Set the screen size to 600x600 screen.bgcolor("black") # Set the background color to black screen.title("Snake Game") # Set the title of the screen to "Snake Game" screen.tracer(0) # Turn off the screen updates # Create the snake, food, and scoreboard snake = Snake() food = Food() scoreboard = Scoreboard() # Listen for key presses screen.listen() screen.onkey(snake.up, "Up") # Move the snake up when the "Up" key is pressed screen.onkey(snake.down, "Down") # Move the snake down when the "Down" key is pressed screen.onkey(snake.left, "Left") # Move the snake left when the "Left" key is pressed screen.onkey(snake.right, "Right") # Move the snake right when the "Right" key is pressed # Pause for 2 seconds before starting the game time.sleep(2) # Start the game game_is_on = True while game_is_on: screen.update() # Update the screen time.sleep(0.1) # Pause for 0.1 seconds snake.move() # Move the snake # Detect collision with food if snake.head.distance(food) < 15: food.refresh() # Move the food to a new location snake.extend() # Extend the snake scoreboard.increase_score() # Increase the score # Detect collision with wall if snake.head.xcor() > 280 or snake.head.xcor() < -280 or snake.head.ycor() > 280 or snake.head.ycor() < -280: game_is_on = False # End the game print("hit wall") scoreboard.game_over(message='Hit wall') # Display the game over message # Detect collision with tail for segment in snake.segments: if segment == snake.head: pass # Ignore the head segment elif snake.head.distance(segment) < 1: game_is_on = False # End the game print("hit tail") scoreboard.game_over(message='Hit self') # Display the game over message # Restart game with enter key if game_is_on == False: print("press enter to restart") screen.onkey(snake.reset, "Return") # Reset the game when the "Return" key is pressed # Exit the game when the screen is clicked screen.exitonclick() # In[ ]: