在python中显示随机整数的结果

时间:2014-10-16 21:41:41

标签: python random matrix

from random import randint

board = []

for x in range(5):
    board.append(["O"] * 5)

def print_board(board):
    for row in board:
        print " ".join(row)

print "Let's play Battleship!"
print_board(board)

def random_row(board):
    return randint(0, len(board) - 1)

def random_col(board):
    return randint(0, len(board[0]) - 1)

ship_row = random_row(board)
ship_col = random_col(board)

for turn in range(4):
    guess_row = int(raw_input("Guess Row:"))
    guess_col = int(raw_input("Guess Col:"))

    if guess_row == ship_row and guess_col == ship_col:
        print "Congratulations! You sunk my battleship!"
        break
    else:
        if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4):
            print "Oops, that's not even in the ocean."
        elif(board[guess_row][guess_col] == "X"):
            print "You guessed that one already."
        else:
            print "You missed my battleship!"
            board[guess_row][guess_col] = "X"
    if turn == 3:
        print "Game Over"
    print "Turn", turn + 1
    print_board(board)

我通过CodeCademy创建了一个简单的程序,允许用户使用5x5矩阵玩Battleship,在那里你试图在矩阵中找到一个随机整数。无论是否是正确的坐标,您的命中都会标记为“X”。在用户猜测完成的机会4之后,我想弄清楚如何显示每个游戏的随机坐标。 例如:

Game Over
[0,X,0,0,0]
[X,0,0,[X],0]
[0,0,0,0,X]
[0,0,0,0,0]
[O,0,0,0,0]

其中第4列第2行括号中的X坐标是用户猜测的正确随机坐标。如果它与python语法冲突,则X不必在括号中,我只想向用户显示矩阵中正确答案的位置。例如:

Game Over
[0,X,0,0,0]
[X,0,0,X,0]
[0,0,0,0,X]
[0,0,{0},0,0]
[O,0,0,0,0]

这是我第一次使用堆栈溢出问一个问题,所以如果我问错了,请纠正我。

1 个答案:

答案 0 :(得分:1)

使用&#39; S&#39;作为船舶角色

if turn == 3:
    print 'Game Over'
    board[ship_row][ship_col] = 'S'
    print_board(board)