连接4个Python板

时间:2017-05-25 19:55:05

标签: python computer-science

我正在尝试为2名玩家创建一个python Connect 4游戏,并且有一个我似乎无法解决的错误。请帮忙。代码应该随机选择哪个玩家首先在1和2之间,然后通过python shell获取他们的输入。使用列号,代码应该能够将每个玩家的标记放置在连接四板上。这是代码:

import random
import sys

width = 7
height = 6
player1Marker = 'X'
player2Marker = 'O'

def whoGoesFirst():
    # Randomly choose the player who goes first.
    if random.randint(0, 2) == 0:
        return 'Player 1'
    else:
        return 'Player 2'


def drawBoard(board):
    print()
    print(' ', end='')
    for x in range(1, width + 1):
        print(' %s  ' % x, end='')
    print()

    print('+---+' * (width - 1))

    for y in range(height):
        print('|   |' + ('   |' * (width - 1)))

        print('|', end='')
        for x in range(width):
            print(' %s |' % board[x][y], end='')
        print()

        print('|   |' + ('   |' * (width - 1)))

        print('+---+' + ('---+' * (width - 1)))


def getPlayer1Move(game_board):
    while True:
        print('Player 1: which column do you want to move on (1-7)? Type quit if you want to quit: ' % (width))
        move = input()
        if move.lower().startswith('q'):
            sys.exit()
        if move.int():
            continue
        move = int(move) - 1
        if isValidMove(game_board, move):
            return move

def getPlayer2Move(game_board):
    while True:
        print('Player 2: Which column do you want to move on (1-7)? Type quit if you want to quit: ' % (width))
        move = input()
        if move.lower().startswith('q'):
            sys.exit()
        if move.int():
            continue
        move = int(move) - 1
        if isValidMove(game_board, move):
            return move

def getNewBoard():
    game_board = []
    for x in range(width):
        game_board.append([' '] * height)
    return game_board

def p1makeMove(game_board, player, column):
    for y in range(height -1, -1, -1):
        if game_board[column][x] == ' ':
            game_board[column][x] = player1
            return

def p2makeMove(game_board, player, column):
    for y in range(height -1, -1, -1):
        if game_board[column][y] == ' ':
            game_board[column][y] = player2
            return

def isValidMove(game_board, move):
    if move < 0 or move >= (width):
        return False

    if game_board[move][0] != ' ':
        return False
    return True

def isBoardFull(game_board):
    for x in range(width):
        for y in range(height):
            if game_board[x][y] == ' ':
                return False
    return True

def winnerOfGame(game_board, tile):
    # check horizontal spaces
    for y in range(height):
        for x in range(width - 3):
            if game_board[x][y] == tile and game_board[x+1][y] == tile and game_board[x+2][y] == tile and game_board[x+3][y] == tile:
                return True

    # check vertical spaces
    for x in range(width):
        for y in range(height - 3):
            if game_board[x][y] == tile and game_board[x][y+1] == tile and game_board[x][y+2] == tile and game_board[x][y+3] == tile:
                return True

    # check / diagonal spaces
    for x in range(width - 3):
        for y in range(3, height):
            if game_board[x][y] == tile and game_board[x+1][y-1] == tile and game_board[x+2][y-2] == tile and game_board[x+3][y-3] == tile:
                return True

    # check \ diagonal spaces
    for x in range(width - 3):
        for y in range(height - 3):
            if game_board[x][y] == tile and game_board[x+1][y+1] == tile and game_board[x+2][y+2] == tile and game_board[x+3][y+3] == tile:
                return True

    return False

def playAgain():
    # This function returns True if the player wants to play again, otherwise it returns False.
    print('Do you want to play again? (yes or no)')
    return input().lower().startswith('y')

def main():

    print('Four In A Row')
    print()

    while True:

        turn = whoGoesFirst()
        print('The %s player will go first.' % (turn))
        gameBoard = getNewBoard()

        while True:
            if turn == 'Player 1':
                drawBoard(gameBoard)
                move1 = getPlayer1Move(gameBoard)
                p1makeMove(gameBoard, player1Marker, move1)
                if winnerOfGame(gameBoard, player1Marker):
                    winner = 'Player 1'
                    break
                turn = 'Player 2'

            elif turn == 'Player 2':
                drawBoard(gameBoard)
                move2 = getPlayer2Move(gameBoard)
                p2makeMove(gameBoard, player2Marker, move2)
                if winnerOfGame(gameBoard, player2Marker):
                    winner = 'Player 2'
                    break
                turn = 'Player 1'

            elif isBoardFull(game_board):
                winner = 'tie'
                break

        drawBoard(mainBoard)
        print('Winner is: %s' % winner)
        if not playAgain():
            break
main()

这是游戏板后显示的错误:

Traceback (most recent call last):
  File "/Users/EshaS/Documents/Connect4Final.py", line 166, in <module>
    main()
  File "/Users/EshaS/Documents/Connect4Final.py", line 151, in main
    move2 = getPlayer2Move(gameBoard)
  File "/Users/EshaS/Documents/Connect4Final.py", line 53, in getPlayer2Move
    print('Player 2: Which column do you want to move on (1-7)? Type quit if you want to quit: ' % (width))
TypeError: not all arguments converted during string formatting

1 个答案:

答案 0 :(得分:1)

print的最后,您要对% (width)做什么? 您可以使用:

print('Player 2: [...] %d [...]' % (width))

%d表示您将width作为int包含在您正在打印的字符串中的特定位置。 e.g:

print('Player 2: Which column do you want to move on (1-%d)? Type quit if you want to quit:' % (width))

将打印(假设width = 7):Player 2: Which column do you want to move on (1-7)? Type quit if you want to quit:

顺便说一句,(之后的代码),最好解析你的输入。要使用lower函数,您需要输入为字符串。 .int()函数不清楚,最好使用isinstance( <var>, int )。这给出了:

    move = str(input())
    if move.lower().startswith('q'):
        sys.exit()
    if isinstance( move, int ):
        continue

(对于这两个函数都是如此:getPlayer1MovegetPlayer2Move)。