In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
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!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.