图8
查看源码还有更多的游戏这里就不再一一介绍,Turtle我们并不陌生,所以当我们玩游戏时应该思考开发者是怎样实现的。使用下面的代码即可在当前目录下生成对应游戏的源码
"免费的python游戏将游戏和学习结合在一个灵活的环境中 减少编程等困难主题的压力"
python3 -m freegames copy snake
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
复制
现在我们就可以学习源码并进行修改来实现更多的功能与玩法,抓紧试试吧!