我刚刚开始学习python,在尝试编写单人战舰的简单一维版本时遇到了一些麻烦。

我似乎无法完成的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


谢谢您对这个me脚的问题表示歉意。

最佳答案

良好做法:将电路板尺寸设置为变量,以便您可以定期引用它。把这个放在顶部

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


然后,在游戏逻辑内,在“您错过了我的战舰”行之后,更改棋盘上的相关方块

...
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 - 列出一维Python战舰中的问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37643441/

10-16 04:18
查看更多