好的,以下是一个简单的小乌龟游戏的Python代码:
import turtle
import random
# 设置窗口大小和背景颜色
turtle.setup(500, 500)
turtle.bgcolor('lightblue')
# 创建乌龟
player = turtle.Turtle()
player.shape('turtle')
player.color('darkblue')
player.penup()
# 创建食物
food = turtle.Turtle()
food.shape('circle')
food.color('red')
food.penup()
food.goto(random.randint(-200, 200), random.randint(-200, 200))
# 设置乌龟的移动速度
speed = 10
# 定义乌龟的移动函数
def move_up():
player.setheading(90)
player.forward(speed)
def move_down():
player.setheading(270)
player.forward(speed)
def move_left():
player.setheading(180)
player.forward(speed)
def move_right():
player.setheading(0)
player.forward(speed)
# 绑定键盘事件
turtle.onkey(move_up, 'Up')
turtle.onkey(move_down, 'Down')
turtle.onkey(move_left, 'Left')
turtle.onkey(move_right, 'Right')
turtle.listen()
# 定义检测碰撞函数
def is_collision(t1, t2):
x1, y1 = t1.pos()
x2, y2 = t2.pos()
if abs(x1 - x2) < 20 and abs(y1 - y2) < 20:
return True
else:
return False
# 循环检测碰撞
while True:
if is_collision(player, food):
food.goto(random.randint(-200, 200), random.randint(-200, 200))
turtle.update()
这个小乌龟游戏中,玩家控制乌龟移动,吃掉食物。当乌龟碰到食物时,食物会随机移动到一个新的位置。