为什么我的player_turns()不会增加1?

时间:2017-05-29 14:52:54

标签: python

我正在研究用python编写的2人战舰游戏。我的player_turns()使它在玩家1和玩家2之间交替。但是当你玩它只停留在玩家1上时,为什么会这样呢?

此外,我注意到如果您找到了该船的位置并开始新游戏,则该船找不到新位置并保持与上次游戏相同的坐标。我怎样才能让坐标改变每场比赛?

from random import randint

game_board = []
player_one = {
    "name": "Player 1",
    "wins": 0,
    "lose": 0
}
player_two = {
    "name": "Player 2",
    "wins": 0,
    "lose": 0
}

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

def show_board(board):
    print("Find and sink the ship!")
    for row in board:
        print(" ".join(row))

# Defining ships locations
def load_game(board):
    print("WELCOME TO BATTLESHIP!")
    print("START")
    del board[:]
    build_game_board(board)
    show_board(board)
    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 = 0
    if total_turns % 2 == 0:
        return player_one
        total_turns += 1

    else:
        return player_two

# Allows new game to start
def play_again():
    answer = input("Would you like to play again? ")
    if answer == "yes" or answer == "y":
        total_turns = 0
        ship_points = load_game(game_board)

    else:
        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("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":
            print("You guessed that one already.")

        else:
            print("You missed my battleship!")
            board[guess_row][guess_col] = "X"
        show_board(game_board)

    else:
        return 0


def main():
    begin = input('Type \'start\' to begin: ')
    while (begin != str('start')):
        begin = input('Type \'start\' to begin: ')
    for games in range(3):
        for turns in range(6):

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

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

            if turns == 6:
                print("The game is a draw")
                play_again()

if __name__ == "__main__":
    main()

1 个答案:

答案 0 :(得分:0)

在递增 Public Class Form1 Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load ' Configuring for Background Workers Control.CheckForIllegalCrossThreadCalls = False Dim MyList As New List(Of String) For a As Integer = 0 To 100 MyList.Add(CStr(a)) Next End Sub Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click Dim bgw As New System.ComponentModel.BackgroundWorker bgw.WorkerReportsProgress = True bgw.WorkerSupportsCancellation = True AddHandler bgw.DoWork, AddressOf bgw_DoWork ' I create a BackgroundWorker here rather than add one in the toolbox so that I can specify the Handler and use different Handler routines for different part of a large program. Button1.Enabled = False Dim progress As New Progress(bgw) progress.ShowDialog() Button1.Enabled = True End Sub Private Sub bgw_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) For i = 0 To MyList.Count -1 Label1.Text = MyList(i) sender.ReportProgress(i) System.Threading.Thread.Sleep(200) Label1.Refresh() Next End Sub End Class Public Class Progress Private WithEvents _BGW As System.ComponentModel.BackgroundWorker Public Sub New(ByVal BGW As System.ComponentModel.BackgroundWorker) _BGW = BGW InitializeComponent() End Sub Private Sub frmProgress_Shown(sender As Object, e As System.EventArgs) Handles Me.Shown If Not IsNothing(_BGW) Then _BGW.RunWorkerAsync() End If End Sub Private Sub _BGW_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles _BGW.ProgressChanged ProgressBar1.Value = e.ProgressPercentage Label1.Text = e.ProgressPercentage End Sub Private Sub _BGW_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles _BGW.RunWorkerCompleted Me.Close() End Sub End Class 后,您需要使用return语句。

执行return语句后,退出该函数。