我相信以下展示了您描述的行为。它设置棋盘,将海龟移动到一个白色方块,然后将它随机移动到它尚未访问过的方块(避免黑色方块),直到它用完有效的移动:
from turtle import Turtle, Screen
from random import choice
WIDTH = 40
BOARD_SIZE = 8
COLOR_EMPTY, COLOR_BLOCKED, COLOR_VISITED, COLOR_FAILED = 'white', 'black', 'green', 'red'
blocked_squares = [(5, 7), (5, 6), (3, 5), (7, 5), (2, 4), (4, 4), (5, 4), (6, 4)] # should generate randomly
def mysquare(turtle, i, j, color, size):
turtle.penup()
turtle.goto((i - BOARD_SIZE//2) * size, (j - BOARD_SIZE//2) * size)
turtle.pendown()
turtle.fillcolor(color)
turtle.setheading(0)
turtle.begin_fill()
for _ in range(4):
turtle.forward(size)
turtle.left(90)
turtle.end_fill()
def board_to_screen(position):
y, x = position
return ((x - BOARD_SIZE//2) * WIDTH + WIDTH / 2, (y - BOARD_SIZE//2) * WIDTH + WIDTH / 2)
def move():
global position
positions = []
for j_delta in (-1, 0, 1):
if 0 <= position[0] + j_delta < BOARD_SIZE:
for i_delta in (-1, 0, 1):
if 0 <= position[1] + i_delta < BOARD_SIZE:
if board[position[0] + j_delta][position[1] + i_delta]:
new_position = (position[0] + j_delta, position[1] + i_delta)
if new_position != position:
positions.append(new_position)
j, i = position
if positions:
board[j][i] = False
mysquare(tess, i, j, COLOR_VISITED, WIDTH)
position = choice(positions)
screen.ontimer(move, 1000)
else:
mysquare(tess, i, j, COLOR_FAILED, WIDTH)
tess.penup()
tess.goto(board_to_screen(position))
screen.update()
tess = Turtle(shape='turtle')
tess.speed('fastest')
screen = Screen()
screen.tracer(0)
board = []
for j in range(BOARD_SIZE):
board.append(list())
for i in range(BOARD_SIZE):
board[j].append(True)
square_color = COLOR_EMPTY
if (i, j) in blocked_squares:
square_color = COLOR_BLOCKED
board[j][-1] = False
mysquare(tess, i, j, square_color, WIDTH)
screen.update()
position = (3, 3)
tess.penup()
tess.goto(board_to_screen(position))
screen.ontimer(move, 1000)
screen.exitonclick()
这可能最好使用多个海龟来避免一些移动,并且板上的海龟可以是 GIF 图像而不是内置的海龟形状。黑色方块可能应该是随机生成的(但要小心),乌龟板上的初始起始位置也应该如此。
