2015-04-13 2 views
0

Я попытался сделать функцию, чтобы проверить, выиграл ли кто-нибудь, выиграл ли он вверх и вниз, а не по диагонали или поперек.Функция win для подключения 4 работает неправильно

Он работает иногда, но иногда он говорит о своем выигрыше с 3 подряд.

Heres код, который у меня есть.

#myBoard is a 2d array storing the board. col is the column a player is                                  
#trying to move, and player is the player to move. If it is a valid move,                                 
#the program will go ahead and change myBoard.                                        
def move2(myBoard, col, player): 
    if player == True: 
     for i in range(len(myBoard) - 1,-1,-1): 
      if myBoard[i][col] == 0: 
       myBoard[i][col] = 1 
       player = False 
       break 
    else: 
     for i in range(len(myBoard) - 1,-1,-1): 
      if myBoard[i][col] == 0: 
       myBoard[i][col] = -1 
       player = True 
       break 
    return myBoard, player 


#Returns 1 if player 1 has won, a -1 if player 2 has won, and 0 otherwise.                                 
#lastColPlayed is the last valid move that was made.                                       
def checkWin(myBoard, lastColPlayed): 
    player1amount = 0 
    player2amount = 0 
    for i in range(len(myBoard) - 1): 
     if myBoard[i][lastColPlayed] == 1: 
       player2amount = 0 
       player1amount += 1 
     if myBoard[i][lastColPlayed] == -1: 
       playet1amount = 0 
       player2amount += 1 
    if player1amount == 3: 
     return 1 
    elif player2amount == 3: 
     return -1 
    else: 
     return 0 

#prints myBoard to the screen                                            
def printBoard(myBoard): 
    for row in myBoard: 
     for item in row: 
      if item == 0: 
       print("_", end="") 
      elif item == -1: 
       print("0", end="") 
      elif item == 1: 
       print("X", end="") 
     print() 

#returns true if it's a draw                                             
def isDraw(myBoard): 
    return False 

def main(): 
    won = 0 
    draw = False 
    player1turn = True 
    print("Welcome to Connect Four!") 
    rows = input("Please enter a number of rows: ") 
check = True 
    while check == True: 
     try: 
      if int(rows) <= 5: 
       while int(rows) <= 5: 
        rows = input("Please enter a Valid choice: ") 
      else: 
       check = False 
     except ValueError: 
      rows = input("Please enter a Valid choice: ") 
    columns = input("Please enter a number of columns: ") 
    check2 = True 
    while check2 == True: 
     try: 
      if int(columns) <= 5: 
       while int(columns) <= 5: 
        columns = input("Please enter a Valid choice: ") 
      else: 
       check2 = False 
     except ValueError: 
      columns = input("Please enter a Valid choice: ") 
    myBoard = [] 
    myBoardTemp = [] 
    for i in range(int(columns)): 
     myBoardTemp.append(0) 
    for i in range(int(rows)): 
     myBoard.append([0] * int(columns)) 
    printBoard(myBoard) 
    check3 = True 
while won == 0 and draw == False: 
     move = input("Please enter a move: ") 
     while check3 == True: 
      try: 
       if int(move) < 0 or int(move) > len(myBoard[0]): 
        while int(move) < 0 or int(move) > len(myBoard[0]): 
         move = input("Please enter a valid choice: ") 
       else: 
        check3 = False 
      except ValueError: 
       move = input("Please enter a valid choice: ") 
     myBoard, player1turn = move2(myBoard,int(move) - 1,player1turn) 
     printBoard(myBoard) 
     won = checkWin(myBoard,int(move) - 1) 
     draw = isDraw(myBoard) 
     if won == 1: 
      print("Player 1 has won!") 
     elif won == -1: 
      print("Player 2 has won!") 
     elif draw == True: 
      print("It is a draw!") 
main() 

На этот раз он работал

____________________ 
____________________ 
X___________________ 
X_0_________________ 
X_0_________________ 
X_0_________________ 
Player 1 has won! 

На этот раз он не

____________________ 
____________________ 
__XX________________ 
_X0X0_______________ 
_0XX0_______________ 
X0X00_______________ 
Player 1 has won! 

Что не так?

ответ

1

Несколько вещей:

1) диапазон (п) возвращает все значения от 0 до п-1 Так, когда в checkWin вы набираете:

for i in range(len(myBoard) - 1): 

Вы на самом деле не принимая во внимание нижнюю строку ,

2) Вы проверяете только 3 подряд. Единственная причина, по которой первый пример дает правильный ответ, заключается в том, что он не учитывает нижнюю строку. В вашем втором примере у вас есть три X подряд (не включая нижнюю строку), поэтому он ошибочно утверждает победу.

Так что ответ:

  • удалить -1 из для цикла
  • чек на player1amount и player2amount для 4 (или лучше:> 3)
Смежные вопросы