列出一维Python战舰的问题

时间:2016-06-05 15:12:59

标签: python arrays

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

我似乎无法做出两件事:

  1. 我创建了一个一维列表(这是游戏玩法板),但需要显示/打印列表中重复元素的索引。换句话说,我如何打印一个仅显示我板上元素索引的列表?

  2. 我想用" *"替换该元素如果这是一个错误的猜测。例如,如果我错误地将位置猜测为5个元素的板中的4,我想显示:

    1 2 3 * 5

  3. 此外,我想将获胜的热门歌曲显示为" 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
    

    感谢并为这个蹩脚的问题道歉。

2 个答案:

答案 0 :(得分: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 

然后,在游戏逻辑内部,&#34;你错过了我的战舰&#34;线,改变板上的相关方块

...
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:
    ...

答案 1 :(得分:1)

为了实现您的两种显示功能,我建议您只让board列表保留显示值,因为您还没有在其他任何地方使用它。

from random import randint

ship=randint(1, 5)
board = ['1', '2', '3', '4', '5']

print ("Let's play Battleship!")

attempts = 1
while attempts < 4:
    print(' '.join(board))
    guess = int(input("Guess Where My Ship Is: "))
    if guess == ship:
        print ("Congratulations Captain, you sunk my battleship!")
        board[guess - 1] = 'X'
        break
    else:
        print ("You missed my battleship!")
        board[guess - 1] = '*'
        if attempts<3:
            print("Try again!")
        elif attempts==3:
            print("Better luck next time, Captain!")
    attempts+=1

print(' '.join(board))

还有一件事:当您选择船舶的索引(应该在范围[1,5]中)时,您有一个错误,我也已经纠正过了。

如果你正在扩展你的战舰计划,你必须有一个打印出列表索引的功能(除非值是'*''X'),一种方法是简单地做:

def display(b):
    print(' '.join(y if y in 'X*' else str(x + 1) for x, y in enumerate(b)))