我正在尝试使用 Python 和海龟制作寻宝类型游戏
目标是在屏幕上写入一个随机步骤,然后用户将使用箭头键按照指示进行操作,完成后按 Enter,然后再执行另一个步骤显示
我正在使用 trinket.io 对其进行编码
我知道我必须有一些方法来停止程序,但仍然允许用户在每一步之后用箭头移动海龟,但到目前为止我尝试过的还没有工作。
这是到目前为止的程序:
################################################
## This program simulates following a series ##
## of directions in a random order to see if ##
## You will end up at the same place ##
################################################
import turtle
import random
#############################
### Variable declareation ###
#############################
unit = 10 # this is the distance the turtle will move each time a key is pressed
hunt1 = turtle.Turtle() # turtle used in the first hunt
hunt2 = turtle.Turtle()# turtle used in the sedond hunt
hunt3 = turtle.Turtle()#turtle used in the third hunt
directions = turtle.Turtle()#used to print the steps
screen = turtle.Screen()# creates a Screen
koopa = [hunt1,hunt2,hunt3] # a collection of 'hunt' turtles
color = ['black','green','red']
map = ['Step 1', 'step 2', 'step3'] #this holds all the steps in the treasure hunt
x = random.randint(-50,0)
y = random.randint(-50,0)
next_step = False
#################
## Functions ##
#################
def set_koopa():
c=0
for i in koopa:
i.penup()
i.goto(x,y)
i.color(color[c])
i.pendown()
c=c+1
def east():
k.setheading(180)
k.forward(unit)
def west():
k.setheading(0)
k.forward(unit)
def north():
k.setheading(90)
k.forward(unit)
def south():
k.setheading(270)
k.forward(unit)
def enter():
next_step = True
##################
## key bindings ##
##################
screen.onkey(east, 'left')
screen.onkey(west, 'right')
screen.onkey(north, 'up')
screen.onkey(south, 'down')
screen.onkey(enter, 'enter')
screen.listen()# tells the compouter to listen for keystrokes
z=0 #debug
############
## Main ##
############
directions.goto(0,0)
directions.ht()
set_koopa()
for k in koopa:
while len(map)!=0: # checks if there are items left in the list
l = len(map) # returns the number if items
directions.write(map.pop(random.randint(0,l-1))) #randomly takes an item and removes it and writes in on the screen
while not next_step: #gives time for user to move
z=z+1#debug
print z #debug
print next_step #debug
directions.clear()
有问题的代码在底部。
我尝试的第一件事没有循环:
while not next_step: #gives time for user to move
z=z+1#debug
print z #debug
print next_step #debug
相反,我有代码要求输入,但这不允许用户移动海龟。