欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

利用Python实现简单猫鼠游戏

程序员文章站 2024-01-09 18:55:58
猫鼠游戏 利用键盘的方向键来控制老鼠的移动 import turtle import time boxsize=200 caught=False score=0...

猫鼠游戏

利用键盘的方向键来控制老鼠的移动

import turtle
import time

boxsize=200
caught=False
score=0

#function that are called on keypresses
def up():
    mouse.forward(10)
    checkbound()

def left():
    mouse.left(45)

def right():
    mouse.right(45)

def back():
    mouse.backward(10)
    checkbound()

def quitTurtles():
    window.bye()

#stop the mouse from leaving the square set by box size
def checkbound():
    global boxsize
    if mouse.xcor()>boxsize:
        mouse.goto(boxsize,mouse.ycor())
    if mouse<-boxsize:
        mouse(-boxsize,mouseycor())
    if mouse.ycor>boxsize:
        mouse.goto(mouse.xcor(),boxsize)
    if mouse.ycor()<-boxsize:
        mouse.goto(mouse.xcor(),-boxsize)

#set up screen
window = turtle.Screen()
mouse = turtle.Turtle()
cat = turtle.Turtle()
mouse.penup()
mouse.penup()
mouse.goto(100,100)

#add key listeners
window.onkeypress(up,"Up")
window.onkeypress(left,"Left")
window.onkeypress(right,"Right")
window.onkeypress(back,"Down")
window.onkeypress(quitTurtles,"Escape")
difficulty = window.numinput("Diffculty",
                             "Enter a difficulty from easy (1) ,for hard (5)",
                             minval=1,maxval=5)

window.listen()
#mian loop
#note how it change with difficulty
while not caught:
    cat.setheading(cat.towards(mouse))
    cat.forward(8+difficulty)
    score=score+1
    if cat.distance(mouse)<5:
        caught=True
    time.sleep(0.2-(0.01*difficulty))
window.textinput("GAME OVER","Well done. You scored:"+str(score*difficulty))
window.bye()