风火轮编程的考试题目:被困牢笼(turtle按键检测与预判)

风火轮编程的考试题目:被困牢笼(turtle按键检测与预判)

3. 被困牢笼
如下图是8X8的格子图,每个正方形格子的边长是50,小蓝点的初始坐标是(25,25)。编写程序,用turtle模块中的海龟画出8×8格子,然后可以用上下左右方向箭头操作小蓝点移动,每次移动50个单位,但无论如何操作,它都到达不了格子外面。

python 8x8方格图

python 8×8方格图

以下是参考代码:

import turtle

def moveup():
    if queen.ycor()<=125:
       queen.sety(queen.ycor()+50)

def movedown():
    if queen.ycor()>= -125:
        queen.sety(queen.ycor()-50)

def moveleft():
    if queen.xcor()>= -125:
       queen.setx(queen.xcor()-50)

def moveright():
    if queen.xcor()<=125:
       queen.setx(queen.xcor()+50)
    
def draw_grid(n,length):
    """n: 行列数,length:格子边长"""
    turtle.penup()
    top = length * n/2
    left = -length * n/2
    turtle.goto(left,top)
    turtle.pendown()
    for _ in range(n):
        turtle.fd(n*length)
        turtle.bk(n*length)
        turtle.right(90)
        turtle.fd(length)
        turtle.left(90)
    turtle.fd(n*length)
    turtle.left(90)    
    for _ in range(n):
        turtle.fd(n*length)
        turtle.bk(n*length)
        turtle.left(90)
        turtle.fd(length)
        turtle.right(90)
    turtle.update()

turtle.dot(10,'red')
turtle.speed(0)
turtle.delay(0)
draw_grid(8,50)
turtle.ht()

queen = turtle.Turtle('circle')
queen.color('blue')
queen.penup()
queen.goto(25,25)

screen = turtle.getscreen()
screen.onkeypress(moveup,'Up')
screen.onkeypress(movedown,'Down')
screen.onkeypress(moveleft,'Left')
screen.onkeypress(moveright,'Right')
screen.listen()   
screen.mainloop()

李兴球

李兴球的博客是Python创意编程原创博客