您好,登錄后才能下訂單哦!
這篇文章主要講解了“怎么用Python代碼實現貪吃蛇小游戲”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“怎么用Python代碼實現貪吃蛇小游戲”吧!
執行之后,在當前目錄下就多了一個snake.py文件,打開就能查看游戲對應的邏輯
"""Snake, classic arcade game. Exercises 1. How do you make the snake faster or slower? 2. How can you make the snake go around the edges? 3. How would you move the food? 4. Change the snake to respond to arrow keys. """ 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()
感謝各位的閱讀,以上就是“怎么用Python代碼實現貪吃蛇小游戲”的內容了,經過本文的學習后,相信大家對怎么用Python代碼實現貪吃蛇小游戲這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。