当玩家圈数=6时,程序退出。Python战舰

2024-05-15 13:34:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我在用python做一个2人的战舰游戏。我已经这样做了,使每个'游戏'允许总共6个回合(3从每个球员),然后会出现一条消息说'的数量已结束'。你知道吗

一旦发生这种情况,他们将被要求再次发挥。如果他们回答“是”或“是”,游戏应该重新加载。然而,它没有。板加载,但程序然后退出。我相信问题出在play\u again()函数上,但我不太确定它是什么。你知道吗

我想让玩家们可以玩任意多的游戏,直到他们决定回答“不”或“不”。我该如何实施这一点?你知道吗

from random import randint


game_board = []

player_one = {
    "name": "Player 1",
    "wins": 0,
}

player_two = {
    "name": "Player 2",
    "wins": 0,
}

colors = {"reset":"\033[00m",
          "red":"\033[91m",
          "blue":"\033[94m",
          "cyan":"\033[96m"
              }


# Building our 5 x 5 board
def build_game_board(board):
    for item in range(5):
        board.append(["O"] * 5)

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

# Defining ships locations
def load_game(board):
    print("WELCOME TO BATTLESHIP!")
    print("Find and sink the ship!")
    del board[:]
    build_game_board(board)
    print(colors['blue'])
    show_board(board)
    print(colors['reset'])
    ship_col = randint(1, len(board))
    ship_row = randint(1, len(board[0]))
    return {
        'ship_col': ship_col,
        'ship_row': ship_row,
    }

ship_points = load_game(game_board)


# Players will alternate turns.
def player_turns(total_turns):

    if total_turns % 2 == 0:
        total_turns += 1
        return player_one

    return player_two

# Allows new game to start
def play_again():

    positive = ["yes", "y"] 
    negative = ["no", "n"]

    global ship_points

    while True:
        answer = input("Play again? [Y(es) / N(o)]: ").lower().strip()
        if answer in positive:
            ship_points = load_game(game_board)
            break

        elif answer in negative:   
            print("Thanks for playing!")
            exit()

# What will be done with players guesses
def input_check(ship_row, ship_col, player, board):
    guess_col = 0
    guess_row = 0
    while True:
        try:
            guess_row = int(input("Guess Row:")) - 1
            guess_col = int(input("Guess Col:")) - 1
        except ValueError:
            print("Enter a number only: ")
            continue
        else:
            break
    match = guess_row == ship_row - 1 and guess_col == ship_col - 1
    not_on_game_board = (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4)

    if match:
        player["wins"] += 1
        print("Congratulations! You sunk my battleship!")
        print('The current match score is %d : %d (Player1 : Player2)' % (player_one["wins"], player_two["wins"]))
        print("Thanks for playing!")
        play_again()

    elif not match:
        if not_on_game_board:
            print("Oops, that's not even in the ocean.")

        elif board[guess_row][guess_col] == "X" or board[guess_row][guess_col] == "Y":
            print("You guessed that one already.")

        else:
            print("You missed my battleship!")
            if player == player_one:
                board[guess_row][guess_col] = "X"
            else:
                board[guess_row][guess_col] = "Y"

        print(colors['cyan'])
        show_board(game_board)
        print(colors['reset'])

    else:
        return 0


def main():
    begin = input('Type \'start\' to begin: ')
    while (begin != str('start')):
        begin = input('Type \'start\' to begin: ')

    for turns in range(6):

        if player_turns(turns) == player_one:
            print(ship_points)
            print("Player One")
            input_check(
                ship_points['ship_row'],
                ship_points['ship_col'],
                player_one, game_board
            )

        elif player_turns(turns) == player_two:
            print("Player Two")
            input_check(
                ship_points['ship_row'],
                ship_points['ship_col'],
                player_two, game_board
            )

        if turns == 5:
            print("The number of turns has ended.")
            print(colors['red'])
            show_board(game_board)
            print(colors['reset'])
            print('The current match score is %d : %d (Player1 : Player2)' % (player_one["wins"], player_two["wins"]))
            play_again()

if __name__ == "__main__":
    main()

Tags: boardgameinputifcolonepointsrow
3条回答

问题是您的play_again()调用在接收到“Y”作为答案时,会加载电路板,但随后简单地返回。哪里?好吧,它是从main()中的for循环调用的。不幸的是,这是for循环的最后一次迭代,因此循环结束,程序退出。你知道吗

你应该在for循环上加一个循环:

while True:
    for turns in range(6):
       ...

尝试修改main

turns = 0
while turns < 6:
    # Process turn...
    if turns == 5:
        # Show endgame board
        if play_again():
            turns = -1
    turns += 1

在正输入上返回{},否则返回{}。你知道吗

当我在play\u again()函数中向main添加一个调用时,它也对我起了作用:

# Allows new game to start
def play_again():

    positive = ["yes", "y"] 
    negative = ["no", "n"]

    global ship_points

    while True:
        answer = input("Play again? [Y(es) / N(o)]: ").lower().strip()
        if answer in positive:
            ship_points = load_game(game_board)
            main()
            break

        elif answer in negative:   
            print("Thanks for playing!")
            exit()

相关问题 更多 >