升级版Turtle Race

其实这个项目来自一位我的新疆的学生。原本的Turtle Race项目只是画出赛道,创建两支画笔然后进行一个赛跑。但是学生后边学习了Turtle的事件、监听、绑定按键等知识以后,将原有的Turtle Race升级,做成一个人机交互小游戏。

游戏规则很简单:

一共有3只海龟,你控制其中的tina(红色),剩下两只海龟会自动前进。但是跑道旁边有一个红绿灯🚥,只有绿灯、黄灯亮起时才允许前进。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
import random
import turtle

s = turtle.Screen()
s.setup(width=500, height=300)
t = turtle.Turtle()
turtle.bgcolor('skyblue')
t.speed(0)

# 打印规则
print('游戏规则:红灯停绿灯行,闯红灯有惩罚')

# 赛道
t.goto(-150, 50)
t.color('gray')
t.begin_fill()
for i in range(2):
t.fd(300)
t.rt(90)
t.fd(100)
t.rt(90)
t.end_fill()

# 画出终点线
t.goto(150, 50)
t.color('red')
t.begin_fill()
for i in range(2):
t.fd(10)
t.rt(90)
t.fd(100)
t.rt(90)
t.end_fill()

# 画出分割线
t.pu()
t.goto(-150, -16)
t.color('white')
t.pd()
t.fd(300)
t.pu()
t.goto(-150, 17)
t.pd()
t.fd(300)

t.hideturtle()

# 创建海龟运动员
tina = turtle.Turtle()
tina.shape('turtle')
bob = turtle.Turtle()
bob.shape('turtle')
frank = turtle.Turtle()
frank.shape('turtle')
tina.pu()
bob.pu()
frank.pu()
tina.color('red')
bob.color('blue')
frank.color('orange')

# 移动到起点
tina.goto(-150, 40)
bob.goto(-150, -40)
frank.goto(-150, 0)

# 写出名字
tina.write('tina', font=('楷体', 15))
bob.write('bob', font=('楷体', 15))
frank.write('frank', font=('楷体', 15))

# 开始赛跑并判断胜负
a = turtle.Turtle()
a.pu()
a.hideturtle()
a.goto(50, 100)
x = 0
y = 0
r = 0
z = 4


def speed():
tina.speed(0)
tina.fd(5)


a.color('green')
a.dot(30)

while True:
x += 1
if x > 15 and y < 6:
a.pd()
a.color('yellow')
a.dot(30)
y += 1
if x > 15 and y > 5:
a.color('red')
a.dot(30)
r = 1
if tina.xcor() != tina_x:
tina.bk(30)
tina_x = tina.xcor()
z += 1
if z > 50:
x = 0
y = 0
z = 0
r = 0
a.color('green')
a.dot(30)
s.onkey(speed, 'Right')
s.listen()
tina_x = tina.xcor()
if tina_x >= 150:
print('tina win')
break
n = random.randint(0, 2)
if r == 1:
continue
bob.fd(n - n * 2)
bob.fd(random.randint(n, 10))
bob_x = bob.xcor()
if bob_x >= 150:
print('bob win')
break
for i in range(random.randint(0, 6)):
frank.fd(random.randint(1, 1))
frank_x = frank.xcor()
if frank_x >= 150:
print('frank win')
break

turtle.mainloop()