这是一个要求用户在3乘3网格上输入位置然后另一个用户尝试猜测位置的游戏 . 调试错误时出现问题 .
这条线有什么问题? Col=int(guess[1:])-1
在以下代码中?
当我尝试在repl.it中运行它时,它返回以下错误 .
Traceback(最近一次调用最后一次):文件“python”,第84行,在文件“python”中,第71行,在init中ValueError:对于带有基数为10的int()的无效文字:''
#Creation of the grid and the user interface list
grid = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
turns=0
guess="x"
#Function to clear screen
def cls():
print ("\n" * 100)
#Function to validate coordinate
def validate_entry():
valid=False
while valid==False:
guess=input("Enter a location from A1 to C3: ")
loc = guess.upper() #Use upper case
row = guess[0:1]
col = guess[1:2]
if(row!="A" and row!="B" and row!="C") or (col!="1" and col!="2" and col!="3"):
print("Your location is invalid.")
print("")
return False #not actually needed, but helps see what is happening
else:
valid=True
return True
#Function to set the location of the treasure
def settingTreasure(grid):
treasureSet=input("Set location by entering a location from A1 to C3: ")
#Converting the letter into a coordinate in the list
treasure_letter=str(treasureSet[:1])
if treasure_letter in ["a", "A"]:
locRow=0
elif treasure_letter in ["b", "B"]:
locRow=1
elif treasure_letter in ["c", "C"]:
locRow=2
#Converting the number into a list coordinate
locCol=int(treasureSet[1:])-1
grid[locRow][locCol]=1
settingTreasure(grid)
cls()
#Displaying the user interface in a clean manner
def gameBoard():
UI = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
for i in range(0,len(UI)):
print(UI[i])
gameBoard()
#The main loop that contains the game
def _init_(turns, guess):
turns=turns+1
#If the player exceeds three turns they lose
if turns>3:
print("Too many turns! You lose!")
quit()
#Prints number of turns
print(" ")
print("Turn " + str(turns))
validate_entry()
#Converting the letter into a coordinate in the list
guess_letter=str(guess[:1])
if guess_letter in ["a", "A"]:
Row=0
elif guess_letter in ["b", "B"]:
Row=1
elif guess_letter in ["c", "C"]:
Row=2
#Converting the number into a list coordinate
Col=int(guess[1:])-1
#Test to see if they guessed treasure location
if grid[Row][Col]==1:
print(" ")
print("found treasure!")
quit()
else:
print(" ")
print("Treasure not here!")
#Loop for the main game
while True:
_init_(turns, guess)
1 回答
验证用户的输入后,您没有返回稍后要使用的值,因此猜测值保持为“x”,就像代码初始化时一样
尝试更改validate_entry函数和init函数
validate_entry函数现在返回猜测值,然后将其传递给函数调用内的init函数
附注:您可以在["a","A"]中使用
guess_letter.upper() == "A"
而不是guess_letter .upper()
有助于将字母转换为大写 . 但是你可能想在此之前检查guess_letter.isalpha()
. 我认为这种方式可能更容易,因为您只需要在此之后更改一个字符 . 另一种方法是在测试它是alpha之后获取string.ascii_uppercase中字母的索引