为了一个学校的项目,我必须做一个战舰游戏。在游戏中,一个玩家有4艘船,如果一个玩家的所有船只都被摧毁,游戏结束。我想让这个功能发挥作用。
这是代码:

board = []
for x in range(10):
    board.append(["O"] * 10)
def print_board(board):
    for row in board:
        print " ".join(row)
print "Let's play Battleship!"
print_board(board)
def Input_row1(board):
    return int(raw_input("In what row do you want to place your first ship?"))
def Input_col1(board):
    return int(raw_input("In what col do you want to place your first ship?"))
def Input_row2(board):
    return int(raw_input("In what row do you want to place your second ship?"))
def Input_col2(board):
    return int(raw_input("In what col do you want to place your second ship?"))
def Input_row3(board):
    return int(raw_input("In what row do you want to place your third ship?"))
def Input_col3(board):
    return int(raw_input("In what col do you want to place your third ship?"))
def Input_row4(board):
    return int(raw_input("In what row do you want to place your fourth ship?"))
def Input_col4(board):
    return int(raw_input("In what col do you want to place your fourth ship?"))
ship_row1 = Input_row1(board)
ship_col1 = Input_col1(board)
ship_row2 = Input_row2(board)
ship_col2 = Input_col2(board)
ship_row3 = Input_row3(board)
ship_col3 = Input_col3(board)
ship_row4 = Input_row4(board)
ship_col4 = Input_col4(board)
for turn in range(9):
    guess_row = int(raw_input("Guess Row:"))
    guess_col = int(raw_input("Guess Col:"))
    if guess_row == ship_row1 and guess_col == ship_col1 or guess_row == ship_row2 and guess_col == ship_col2 or guess_row == ship_row3 and guess_col == ship_col3 or guess_row == ship_row4 and guess_col == ship_col4:
        print "Congratulations! You sunk my battleship!"
        if True:
            total_ships = 4
            total_ships = total_ships - 1
            print total_ships
            if total_ships == 0:
                print "You destroyed all hostile ships!"
    else:
        if (guess_row < 0 or guess_row > 9) or (guess_col < 0 or guess_col > 9):
            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!"
            if turn == 9:
                print "GAME OVER"
                if turn == 9:
                    print "Game Over"
        board[guess_row][guess_col] = "X"
    print "Turn", turn + 1
    print_board(board)

问题是,在第二艘飞船被击中后,飞船总数保持在3艘,而不是变成2艘。为什么这个功能不正常?

最佳答案

这是你的问题:

total_ships = 4
total_ships = total_ships - 1

你每次都要重置。以上相当于:
total_ships = 3

你应该让total_ships的初始化在轮到你的循环之外。就这一点而言,最好的方法是创建一个函数,它是游戏循环,并且是一个处理特定回合的函数,这样就不需要一个长的代码文件了。

关于python - Python战舰,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33310958/

10-11 18:02