给我turtle吃豆人的程序
时间: 2023-06-03 14:07:25 浏览: 148
当然可以,以下是Python代码:
```python
import turtle
# 设置画布
turtle.setup(400,400)
# 定义方向
directions = [(0, 20), (0, -20), (-20, 0), (20, 0)]
# 定义函数,绘制豆子
def draw_bean(x, y):
turtle.up()
turtle.goto(x, y)
turtle.down()
turtle.begin_fill()
turtle.circle(10)
turtle.end_fill()
# 定义函数,绘制墙
def draw_wall(x, y):
turtle.up()
turtle.goto(x, y)
turtle.down()
turtle.setheading(0)
turtle.forward(40)
turtle.left(90)
turtle.forward(40)
turtle.left(90)
turtle.forward(40)
turtle.left(90)
turtle.forward(40)
# 定义函数,移动小乌龟并判断碰撞
def move_turtle():
turtle.onkey(None,'Up')
turtle.onkey(None,'Left')
turtle.onkey(None,'Down')
turtle.onkey(None,'Right')
turtle.clear()
turtle.setheading(turtle.direction)
turtle.forward(20)
x, y = turtle.position()
# 判断是否碰墙
hit_wall = False
if x < -180 or x > 160 or y < -180 or y > 160:
hit_wall = True
turtle.write('Game Over!', font=('Arial', 30, 'normal'))
# 判断是否碰豆子
for bean in beans:
if bean.isvisible() and turtle.distance(bean) < 20:
bean.ht()
beans.remove(bean)
# 判断是否吃完豆子
if len(beans) == 0:
turtle.write('You Win!', font=('Arial', 30, 'normal'))
turtle.onkey(lambda: change_direction(0), 'Up')
turtle.onkey(lambda: change_direction(1), 'Left')
turtle.onkey(lambda: change_direction(2), 'Down')
turtle.onkey(lambda: change_direction(3), 'Right')
if hit_wall == False:
turtle.ontimer(move_turtle, 200)
# 定义函数,改变方向
def change_direction(idx):
turtle.direction = directions[idx]
# 绘制地图
map_grid = [
"+++++++++++++++",
"+o+o+o+o+o+o+o+o+",
"+o+o+o+++++o+o+o+",
"+o+o+o+o+o+o+o+o+",
"+o+o+++o++o+++o+o+",
"+o+o+o+o++o+o+o+o+",
"+o++++++oo+o+++++",
"+o+o+o+++o+o+o+o+",
"+o+o+o+o+o+o+o+o+",
"+o+o+o++o++o+o+o+",
"+o+o+o+o+o+o+o+o+",
"+o+o++++o++++o+o+",
"+o+o+o+o+o+o+o+o+",
"+o+o+o+o+o+o+o+o+",
"+++++++++++++++"
]
# 绘制地图中的豆子和墙
beans = []
for i in range(len(map_grid)):
for j in range(len(map_grid[i])):
if map_grid[i][j] == 'o':
beans.append(turtle.Turtle(visible=False))
beans[-1].penup()
beans[-1].goto(j * 20 - 180, 180 - i * 20)
beans[-1].pendown()
beans[-1].begin_fill()
beans[-1].circle(10)
beans[-1].end_fill()
elif map_grid[i][j] == '+':
draw_wall(j * 20 - 200, 200 - i * 20)
# 准备小乌龟
turtle.shape('turtle')
turtle.color('blue')
turtle.penup()
turtle.goto(0, 0)
turtle.pendown()
turtle.direction = directions[3]
# 设置键盘事件
turtle.onkey(lambda: change_direction(0), 'Up')
turtle.onkey(lambda: change_direction(1), 'Left')
turtle.onkey(lambda: change_direction(2), 'Down')
turtle.onkey(lambda: change_direction(3), 'Right')
# 启动循环
turtle.listen()
move_turtle()
turtle.done()
```
该程序实现了吃豆人游戏,地图和方格大小可调整。玩家通过方向键控制小乌龟移动吃掉豆子,碰到墙壁会游戏结束。
阅读全文