greatdonut - 1 year ago 87
Python Question

# Edit: Python - Going from 1 Player to Two Player Game Using Functions

I posted something similar earlier, but I did a horrible job of asking the right question.
I'm trying to code a two player connect four game, but can only manage a 1 player game, with the user playing against the computer. Can anyone help me with trying to write a 2 player approach to the game? I'm still quite a beginner and am still learning the ropes, so apologies if this is still not a good question and/or is too vague.

Here's my current code:

``````import random

def winner(board):

# Check rows
for row in range(6):
for col in range(3):
if (board[row][col] == board[row][col + 1] == board[row][col + 2] == board[row][col + 3]) and (board[row][col] != " "):
return board[row][col]

# Check columns
for col in range(6):
for row in range(3):
if (board[row][col] == board[row + 1][col] == board[row + 2][col] == board[row + 3][col]) and (board[row][col] != " "):
return board[row][col]

# Check diagonal A

for row in range(3):
for col in range(4):
if (board[row][col] == board[row + 1][col + 1] == board[row + 2][col + 2] == board[row + 3][col + 3]) and (board[row][col] != " "):
return board[row][col]

# Check diagonal B

for row in range(5, 2, -1):
for col in range(3):
if (board[row][col] == board[row - 1][col + 1] == board[row - 2][col + 2] == board[row - 3][col + 3]) and (board[row][col] != " "):
return board[row][col]

# Tie (just returns an empty string)
return ""

def printBoard(board):
# there are probably better ways to print a board, but I didn"t want to bother with another function, especially since the number of columns and rows are fixed in this game.

print ("   1   2   3   4    5   6   7")
print ("1: " + board[0][0] + " | " + board[0][1] + " | " + board[0][2] + " | " + board[0][3] + " | " + board[0][4] + " | " + board[0][5] + " | " + board[0][6] + " | " + board[0][7])
print ("  ---+---+---+---+---+---+---")
print ("2: " + board[1][0] + " | " + board[1][1] + " | " + board[1][2] + " | " + board[1][3] + " | " + board[1][4] + " | " + board[1][5] + " | " + board [1][6] + " | " + board [1][7])
print ("  ---+---+---+---+---+---+---+")
print ("3: " + board[2][0] + " | " + board[2][1] + " | " + board[2][2] + " | " + board[2][3] + " | " + board [2][4] + " | " + board [2][5] + " | " + board [2][6] + " | " + board [2][7])
print ("  ---+---+---+---+---+---+---+")
print ("4: " + board[3][0] + " | " + board[3][1] + " | " + board[3][2] + " | " + board[3][3] + " | " + board [3][4] + " | " + board [3][5] + " | " + board [3][6] + " | " + board [3][7])
print ("  ---+---+---+---+---+---+---+")
print ("5: " + board[4][0] + " | " + board[4][1] + " | " + board[4][2] + " | " + board[4][3] + " | " + board [4][4] + " | " + board [4][5] + " | " + board [4][6] + " | " + board [4][7])
print ("  ---+---+---+---+---+---+---+")
print ("6: " + board[5][0] + " | " + board[5][1] + " | " + board[5][2] + " | " + board[5][3] + " | " + board [5][4] + " | " + board [5][5] + " | " + board [5][6] + " | " + board [5][7])
print

def playerMove(board):

validMove = False
while not validMove:
col = input("What column would you like to play? :")
for row in range (6,0,-1):
if (1 <= int(row) <= 6) and (1 <= int(col) <= 7) and (board[int(row)-1][int(col)-1] == " "):
board[int(row)-1][int(col)-1] = "X"
validMove = True
break
else:
print ("Invalid input. Please try again!\n")

def computerTurn(board):

validMove = False
while not validMove:
row = random.randint(0,5)
col = random.randint(0,6)
for row in range (5,0,-1):
if board[row][col] == " ":
board[row][col] = "O"
validMove = True
break

def game():
openCells = 42
playerTurn = True
count = 1
newBoard = [ [ " ", " ", " ", " ", " ", " "," ", " "], [ " ", " ", " ", " ", " "," ", " ", " "], [ " ", " ", " ", " ", " ", " ", " ", " "], [ " ", " ", " ", " ", " ", " ", " ", " "], [ " ", " ", " ", " ", " ", " ", " ", " "], [ " ", " ", " ", " ", " ", " ", " ", " "] ]

while not winner(newBoard) and (openCells > 0):
printBoard(newBoard)
if playerTurn:
playerMove(newBoard)
playerTurn = not playerTurn
else:
computerTurn(newBoard)
playerTurn = not playerTurn
openCells -= 1

printBoard(newBoard)
if (winner(newBoard) == "X"):
print ("You Won!")

print ("\nGAME OVER")
elif (winner(newBoard) == "O"):
print ("The Computer Won!")
print ("\nGAME OVER")
else:
print ("Tie!")
print ("\nGAME OVER \n")
``````

EDIT:I modified my code so that I got rid of the computerTurn function and incorporated 2 user inputs in my playerMove function, however my game keeps looping back to player name inputs instead of alternating between turns.
Here's the new code (note that only the last couple functions were changed):

``````def playerMove(board):
turn = 0
players = []
numPlayers = 2
checkers = ['X','O']
for i in range(numPlayers):

validMove = False
while not validMove:
col = input(players[turn]+" what column would you like to play? :")
for row in range (6,0,-1):
if (1 <= int(row) <= 6) and (1 <= int(col) <= 7) and (board[int(row)-1][int(col)-1] == " "):
board[int(row)-1][int(col)-1] = "X"
validMove = True
break
else:
print ("Invalid input. Please try again!\n")

def game():
openCells = 42
playerTurn = True
turn = 0
players = []
numPlayers = 2
count = 1
newBoard = [ [ " ", " ", " ", " ", " ", " "," ", " "], [ " ", " ", " ", " ", " "," ", " ", " "], [ " ", " ", " ", " ", " ", " ", " ", " "], [ " ", " ", " ", " ", " ", " ", " ", " "], [ " ", " ", " ", " ", " ", " ", " ", " "], [ " ", " ", " ", " ", " ", " ", " ", " "] ]

while not winner(newBoard) and (openCells > 0):
printBoard(newBoard)
playerMove(newBoard)
playerTurn = not playerTurn
openCells -= 1

printBoard(newBoard)
if (winner(newBoard) == "X"):
print ("You Won!")

print ("GAME OVER")
elif (winner(newBoard) == "O"):
print ("The Computer Won!")
print ("GAME OVER")
else:
print ("Tie!")
print ("GAME OVER")

game()
``````

I found a simpler way: I made a new function, `playerMoveO`, and renamed your old one `playerMoveX`. I made playerMoveO look like this:

``````def playerMoveO(board):

validMove = False
while not validMove:
col = input("You are the O player. What column would you like to play? :")
for row in range (6,0,-1):
if (1 <= int(row) <= 6) and (1 <= int(col) <= 7) and (board[int(row)-1][int(col)-1] == " "):
board[int(row)-1][int(col)-1] = "O"
validMove = True
break
else:
print ("Invalid input. Please try again!\n")
``````

I also changed playerMoveX to look like this:

``````def playerMoveX(board):

validMove = False
while not validMove:
col = input("You are the X player. What column would you like to play? :")
for row in range (6,0,-1):
if (1 <= int(row) <= 6) and (1 <= int(col) <= 7) and (board[int(row)-1][int(col)-1] == " "):
board[int(row)-1][int(col)-1] = "X"
validMove = True
break
else:
print ("Invalid input. Please try again!\n")
``````

Then, I changed the main loop, but I replaced the `computerTurn` function with `playerMoveO`. It works fine :D

EDIT Obviously, there is a cleaner way. In this one, the `playerMove` function is passed the current symbol. So:

``````def playerMove(board, symbol):

validMove = False
while not validMove:
col = input("You are the {} player. What column would you like to play? :".format(symbol))
for row in range (6,0,-1):
if (1 <= int(row) <= 6) and (1 <= int(col) <= 7) and (board[int(row)-1][int(col)-1] == " "):
board[int(row)-1][int(col)-1] = symbol
validMove = True
break
else:
print ("Invalid input. Please try again!\n")
``````

And in the main loop, there is a variable, `currentSymbol`, which is changed after each turn:

``````def game():
openCells = 42
playerTurn = True
count = 1
newBoard = [ [ " ", " ", " ", " ", " ", " "," ", " "], [ " ", " ", " ", " ", " "," ", " ", " "], [ " ", " ", " ", " ", " ", " ", " ", " "], [ " ", " ", " ", " ", " ", " ", " ", " "], [ " ", " ", " ", " ", " ", " ", " ", " "], [ " ", " ", " ", " ", " ", " ", " ", " "] ]
currentSymbol = "X"

while not winner(newBoard) and (openCells > 0):
printBoard(newBoard)
playerMove(newBoard, currentSymbol)
if currentSymbol == "X": currentSymbol = "O"
elif currentSymbol == "O": currentSymbol = "X"
openCells -= 1

printBoard(newBoard)
if (winner(newBoard) == "X"):
print ("X Won!")

print ("\nGAME OVER")
elif (winner(newBoard) == "O"):
print ("O Won!")
print ("\nGAME OVER")
else:
print ("Tie!")
print ("\nGAME OVER \n")
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download