python代码写一个简单的iwanna游戏
时间: 2024-03-20 10:20:12 浏览: 21
好的,下面是一个简单的iwanna游戏代码,主要用到了Python的turtle模块:
```python
import turtle
# 设置游戏窗口
window = turtle.Screen()
window.title("I wanna game")
window.bgcolor("white")
window.setup(width=600, height=600)
# 创建玩家
player = turtle.Turtle()
player.shape("turtle")
player.color("blue")
player.penup()
player.speed(0)
# 移动玩家
def move_up():
y = player.ycor()
player.sety(y + 20)
def move_down():
y = player.ycor()
player.sety(y - 20)
def move_left():
x = player.xcor()
player.setx(x - 20)
def move_right():
x = player.xcor()
player.setx(x + 20)
# 设置键盘响应事件
turtle.listen()
turtle.onkey(move_up, "Up")
turtle.onkey(move_down, "Down")
turtle.onkey(move_left, "Left")
turtle.onkey(move_right, "Right")
# 创建目标
goal = turtle.Turtle()
goal.shape("circle")
goal.color("red")
goal.penup()
goal.speed(0)
goal.goto(0, 100)
# 设置计分板
score = 0
pen = turtle.Turtle()
pen.color("black")
pen.penup()
pen.hideturtle()
pen.goto(0, 260)
pen.write("Score: {}".format(score), align="center", font=("Courier", 24, "normal"))
# 判断碰撞
def is_collision(t1, t2):
distance = t1.distance(t2)
if distance < 20:
return True
else:
return False
# 设置主循环
while True:
window.update()
# 判断是否碰撞
if is_collision(player, goal):
goal.setposition(0, 100)
score += 10
pen.clear()
pen.write("Score: {}".format(score), align="center", font=("Courier", 24, "normal"))
# 移动目标
y = goal.ycor()
y -= 0.2
goal.sety(y)
# 判断是否超出边界
if goal.ycor() < -300:
goal.setposition(0, 300)
# 结束游戏
turtle.done()
```
运行代码后,您将看到一个小海龟作为玩家,用箭头键控制移动,目标是吃到红色的圆圈。每吃到一个目标,得分增加10分,计分板会实时更新。如果目标超出边界,它将回到窗口的顶部。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)