Python一日一练18----用turtle写猫和老鼠小游戏

要求

用turtle写一个猫和老鼠的小游戏,要求通过鼠标控制老鼠的移动,逃出电脑控制的猫的追捕。

源码如下

import time
import turtle

boxsize=200
caught=False
score=0
#老鼠前进
def up():
    mouse.forward(10)
    checkbound()
#老鼠左转
def left():
    mouse.left(45)
#老鼠右转
def right():
    mouse.right(45)
#老鼠后退
def back():
    mouse.backward(10)
    checkbound()
#结束游戏
def quitTurtle():
    window.bye()

#检测老鼠是否跑过界
def checkbound():
    global boxsize
    if mouse.xcor()>boxsize:
        mouse.goto(boxsize,mouse.ycor())  
    if mouse.xcor()<-boxsize:
        mouse.goto(-boxsize,mouse.ycor())
    if mouse.ycor()>boxsize:
        mouse.goto(mouse.xcor(),boxsize)
    if mouse.ycor()<-boxsize:
        mouse.goto(mouse.xcor(),-boxsize)

#
window=turtle.Screen()
mouse=turtle.Turtle()
cat=turtle.Turtle()
mouse.penup()                   #将老鼠的画笔提起,使不会出现轨迹
mouse.goto(100,100)             #老鼠的初始地址放置在坐标(100,100)

window.onkeypress(up,"Up")      #按动方向键Up则执行函数up
window.onkeypress(left,"Left")
window.onkeypress(right,"Right")
window.onkeypress(back,"Down")
window.onkeypress(quitTurtle,"Escape")

#产生一个输入难度的对话框
difficulty=window.numinput("难度","请输入游戏的难度(1~5)",minval=1,maxval=5)
#窗体监听按键
window.listen()

while not caught:
    cat.setheading(cat.towards(mouse))   #猫调整自己方向,使自己正对老鼠
    cat.forward(8+difficulty)
    score+=1
    if cat.distance(mouse)<5:            #老鼠与猫的距离少于5个像素就输了
        caught=True
    time.sleep(0.2-(0.01*difficulty))    #难度越高,运行速度越快
window.textinput("GAME OVER","游戏得分:"+str(score*difficulty))
window.bye()    

源码下载:http://download.csdn.net/detail/a359680405/9501893
本文地址:http://blog.csdn.net/a359680405/article/details/51242212

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值