能写一些python turtle小游戏的代码吗
时间: 2023-09-04 19:09:25 浏览: 108
当然可以,以下是一个简单的Python Turtle小游戏的代码示例:
```
import turtle
import random
# 设置背景颜色
turtle.bgcolor("lightblue")
# 创建一个乌龟对象
player = turtle.Turtle()
player.color("black")
player.shape("turtle")
player.penup()
player.speed(0)
# 创建随机食物
food = turtle.Turtle()
food.color("red")
food.shape("circle")
food.penup()
food.speed(0)
food.goto(random.randint(-200, 200), random.randint(-200, 200))
# 设置键盘事件函数
def move_up():
player.setheading(90)
player.forward(10)
def move_down():
player.setheading(270)
player.forward(10)
def move_left():
player.setheading(180)
player.forward(10)
def move_right():
player.setheading(0)
player.forward(10)
# 绑定键盘事件
turtle.onkeypress(move_up, "Up")
turtle.onkeypress(move_down, "Down")
turtle.onkeypress(move_left, "Left")
turtle.onkeypress(move_right, "Right")
turtle.listen()
# 循环检测碰撞
while True:
if player.distance(food) < 20:
food.goto(random.randint(-200, 200), random.randint(-200, 200))
if player.xcor() > 300 or player.xcor() < -300 or player.ycor() > 300 or player.ycor() < -300:
player.goto(0,0)
if player.distance(food) < 20:
food.goto(random.randint(-200, 200), random.randint(-200, 200))
if player.xcor() > 300 or player.xcor() < -300 or player.ycor() > 300 or player.ycor() < -300:
player.goto(0,0)
```
这是一个基于Python Turtle的简单小游戏,你可以通过上下左右键控制乌龟移动,吃掉食物即可得分。当乌龟撞到边界时,会自动回到初始位置,吃掉食物后食物会随机移动到一个新的位置。
阅读全文