import random
locationX = random.randint(1,3) #随机生成宝藏的横坐标
locationY = random.randint(1,3) #随机生成宝藏的纵坐标
isOver = False #判断游戏是否结束
row1 = ["□","□","□"]
row2 = ["□","□","□"]
row3 = ["□","□","□"]
map = [row1, row2, row3] #用来打印3×3地图
for ele in map: #遍历并打印地图
print(ele)
while not isOver:
userInput = input("输入横纵坐标,比如23,退出请按q\n")
if userInput == "q": #输入q则退出游戏
isOver = True
print("game over")
elif userInput[0] == str(locationX) and userInput[1] == str(locationY): #如果用户输入的二位数字跟随机生成的横纵坐标都相等
isOver = True
print("你猜对啦,恭喜!")
elif int(userInput[0]) < 1 or int(userInput[1]) < 1 or int(userInput[0]) > 3 or int(userInput[1]) > 3: #如果用户输入的数字小于1或大于3,则需重新输入
print("你输入的坐标不正确")
else:
map[int(userInput[0])-1][int(userInput[1])-1] = "X" #用户猜错时,错误的坐标替换成"X",并打印地图
for ele in map:
print(ele)
下图为游戏开始时
下图为用户输入13和22后,打印变化的地图