How to make simple Snake game using python
Today we are going to discuss about How to make simple Snake game using python. The games run anywhere Python can be installed which includes desktop computers running Windows, Mac OS, or Linux and older or low-power hardware such as the Raspberry Pi.
Simple Snake game
Snake – classic arcade game. Use the arrow keys to navigate and eat the green food. Each time the food is consumed, the snake grows one segment longer. Avoid eating yourself or going out of bounds!
Source Code
from turtle import *from random import randrangefrom freegames import square, vectorfood = vector(0, 0)snake = [vector(10, 0)]aim = vector(0, -10)def change(x, y):"Change snake direction."aim.x = xaim.y = ydef inside(head):"Return True if head inside boundaries."return -200 < head.x < 190 and -200 < head.y < 190def move():"Move snake forward one segment."head = snake[-1].copy()head.move(aim)if not inside(head) or head in snake:square(head.x, head.y, 9, 'red')update()returnsnake.append(head)if head == food:print('Snake:', len(snake))food.x = randrange(-15, 15) * 10food.y = randrange(-15, 15) * 10else:snake.pop(0)clear()for body in snake:square(body.x, body.y, 9, 'black')square(food.x, food.y, 9, 'green')update()ontimer(move, 100)setup(420, 420, 370, 0)hideturtle()tracer(False)listen()onkey(lambda: change(10, 0), 'Right')onkey(lambda: change(-10, 0), 'Left')onkey(lambda: change(0, 10), 'Up')onkey(lambda: change(0, -10), 'Down')move()done()