抓狐狸游戏python代码
时间: 2023-10-09 20:08:11 浏览: 247
抓狐狸游戏是一个比较经典的Python游戏例子,主要是用Python的turtle模块进行绘图,下面是一个简单的抓狐狸游戏Python代码示例:
```
import turtle
import random
import math
# 初始化
turtle.setup(600, 600)
turtle.bgcolor("lightgreen")
turtle.title("Catch the Fox")
# 创建画笔
pen = turtle.Turtle()
pen.color("blue")
pen.penup()
pen.hideturtle()
# 创建猎人
hunter = turtle.Turtle()
hunter.color("red")
hunter.shape("triangle")
hunter.penup()
hunter.speed(0)
# 创建狐狸
fox = turtle.Turtle()
fox.color("brown")
fox.shape("circle")
fox.penup()
fox.speed(0)
fox.setpos(random.randint(-200, 200), random.randint(-200, 200))
# 创建目标点
target = turtle.Turtle()
target.color("green")
target.shape("circle")
target.penup()
target.speed(0)
target.setpos(random.randint(-200, 200), random.randint(-200, 200))
# 定义距离函数
def distance(t1, t2):
x1, y1 = t1.pos()
x2, y2 = t2.pos()
return math.sqrt((x1-x2)**2 + (y1-y2)**2)
# 定义狩猎函数
def hunt():
global score
if distance(hunter, fox) < 20:
score += 1
pen.clear()
pen.write("Score: {}".format(score), align="center", font=("Courier", 24, "normal"))
fox.setpos(random.randint(-200, 200), random.randint(-200, 200))
if distance(hunter, target) < 20:
target.setpos(random.randint(-200, 200), random.randint(-200, 200))
angle = hunter.towards(fox.pos())
hunter.setheading(angle)
hunter.forward(5)
turtle.ontimer(hunt, 100)
# 初始化得分
score = 0
pen.write("Score: {}".format(score), align="center", font=("Courier", 24, "normal"))
# 事件处理
turtle.onkey(lambda: hunter.left(30), "Left")
turtle.onkey(lambda: hunter.right(30), "Right")
turtle.onkey(lambda: hunter.forward(30), "Up")
turtle.onkey(lambda: hunter.backward(30), "Down")
turtle.listen()
# 开始游戏
hunt()
turtle.mainloop()
```
通过这个简单的Python代码,你可以创建一个抓狐狸的游戏,同时还可以练习Python语言的turtle模块基础。当然,你也可以根据自己的需求和兴趣进行更多的修改和拓展。
阅读全文