所以我一直在创建这个简单的寻宝游戏,你可以在棋盘上寻找三件宝藏。但经过 6 次猜测,我陷入了一个循环! X 代表您搜索过的区域,$ 符号代表您发现的宝藏。请帮忙!!!
import random
def hide_treasure(board):
treasures=0
while treasures<=3:
random_row=random.randrange(0,5)
random_col=random.randrange(0,5)
if(0<=random_row<5) and(0<=random_col<5) and (board[random_row] [random_col]==" "):
board[random_row][random_col]="T"
treasures+=1
def display_board(board,show_treasure=False):
for col in range(5):
print " %d " %col,
print
for row in range(5):
print " %d:" %(row)," | ".join(board[row]).replace("T"," ")
print " ---+---+---+---+---"
if show_treasure==True:
" ".replace(" ","T")
def make_user_move(board):
valid_move=False
while not valid_move:
try:
ask_row=input("What row would you like to search (0-4): ")
ask_col=input("What col would you like to search (0-4): ")
if board[ask_row][ask_col]=="T":
board[ask_row][ask_col]="$"
print
print"YES! You found a treasure."
return True
elif board[ask_row][ask_col]=="$" or board[ask_row][ask_col]=="X":
print
print"You already tried there, please pick again."
else:
board[ask_row][ask_col]="X"
print
print"Nothing there."
break
except ValueError:
print"Integers only for row and column values. Please try again!"
continue
except IndexError:
print
print"Sorry invalid location. Please try again!"
def main():
board=[[" "," "," "," "," "],[" "," "," "," "," "],[" ", " "," "," "," ",],[" "," "," "," "," "],[" "," "," "," "," "]]
print"WELCOME TO TREASURE HUNT!"
guess=10
treasures=0
while guess!=0 and treasures!=3:
print
print"You have",guess,"guesses left and have found",treasures,"/3 treasures"
hide_treasure(board)
display_board(board)
guess-=1
if make_user_move(board):
treasures+=1
if guess==0 and treasures!=3:
display_board(show_treasure=True)
print"OH NO! You only found %d"%treasures,"/3 treasures."
print
print"*** GAME OVER ***"
elif treasures==3:
display_board(board)
print"CONGRATULATIONS! You found ALL of the hidden treasure."
print
print"*** GAME OVER ***"
main()
您遇到的问题是您没有足够的空间来隐藏宝藏。您当前的代码不仅仅隐藏三个宝藏,它在开始时隐藏三个宝藏,然后在每次猜测后再隐藏三个宝藏。六次猜测后,所有的空间要么已经被猜出,要么藏有宝藏。
您可能希望将对 hide_treasure
的调用移出 main
中的 while
循环。只需在开始时调用一次,就可以了:
def main():
board=[[" "," "," "," "," "],[" "," "," "," "," "],[" ", " "," "," "," ",],[" "," "," "," "," "],[" "," "," "," "," "]]
print"WELCOME TO TREASURE HUNT!"
guess=10
treasures=0
hide_treasure(board) ### call this here, instead of in the loop below
while guess!=0 and treasures!=3:
print
print"You have",guess,"guesses left and have found",treasures,"/3 treasures"
# hide_treasure(board) ### remove this!
display_board(board)
guess-=1
if make_user_move(board):
treasures+=1
#....
我是一名优秀的程序员,十分优秀!