How to realize gluttonous Snake Game with Python
This article introduces the relevant knowledge of "how to achieve the Snake Game in Python". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Game action picture:
Source code
From turtle import *
From random import randrange
From freegames import square, vector
Food = vector (0,0)
Snake = [vector (10,0)]
Aim = vector (0,-10)
Def change (x, y):
"Change snake direction."
Aim.x = x
Aim.y = y
Def inside (head):
"Return True if head inside boundaries."
Return-200 < head.x < 190 and-200 < head.y < 190
Def 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 ()
Return
Snake.append (head)
If head = = food:
Print ('Snake:', len (snake))
Food.x = randrange (- 15,15) * 10
Food.y = randrange (- 15,15) * 10
Else:
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 () runs
Copy the above code to a file with the suffix py and name it snake.py.
Open the console in the directory where the file is located: run pip install freegames, then run python snake.py
This is the end of the content of "how to realize the Snake Game in Python". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!