我刚开始学习 python,在尝试编写一个简单的 1-D 版单人战舰时遇到了一些麻烦。
2 件我似乎无法解决的事情:
我创建了一个一维列表(这是游戏面板),但需要显示/打印列表重复元素的索引。换句话说,我怎样才能打印一个只显示板中元素索引的列表?
如果猜错了,我想用“*”替换那个元素。例如,如果我在 5 个元素的棋盘中错误地猜测位置为 4,我想显示:
1 2 3 * 5
此外,我想将获胜的命中显示为“X”:
1 2 X * 5
这是我当前的代码:
from random import randint
ship=randint(0, 5)
board = ["O","O","O","O","O"]
print ("Let's play Battleship!")
attempts = 1
while attempts < 4:
print (board)
guess = int(input("Guess Where My Ship Is: "))
if guess == ship:
print ("Congratulations Captain, you sunk my battleship!")
break
else:
print ("You missed my battleship!")
if attempts<3:
print("Try again!")
elif attempts==3:
print("Better luck next time, Captain!")
attempts+=1
谢谢你,并对这个蹩脚的问题表示歉意。
最佳答案
好的做法:将电路板尺寸设置为一个变量,以便您可以定期引用它。放在最上面
size = 5 # Can be changed later if you want to make the board bigger
接下来,根据那个选择你的船位
ship = randint(0, size)
不是制作一个充满 0 的板,而是动态生成板,以便它已经预先填充了可能的值。
board = [] # Creating an empty board
for i in range(1, size):
position = str(i) # Converting integers to strings
board.append(position) # Adding those items to the board
然后,在游戏逻辑内部,在“You missed my battleship”这一行之后,更改棋盘上的相关方 block
...
print("You missed my battleship!")
number_guess = int(guess) - 1 # Because lists are zero-indexed
board[number_guess] = "*" # Assign "*" to the spot that was guessed
if attempts < 3:
...
关于python - 列出 1 Dimensional Python Battleship 中的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37643441/