Python Code Connect-N Game.
Hi there, I need help with detecting the winner for the 8 directions in Connect N. The game is like Connect 4, but the user inputs N to whatever they want it to be. So could be Connect 5, or 6, etc. However, at the moment, my code is not detecting the 8 directions. I really am struggling with this function. Can someone show me how some code that would work to apply into my def have_winner function.
Thank you!
Instructions for the game
# GLOBAL VARIABLES
N = 5
num_row = N + 3
num_col = N + 2
disk = ['\u2B1C', '\u26AA', '\u26AB']
board = []
def init_board(n):
'''initialise the board'''
global N, num_row, num_col
N = n
num_row = n + 3
num_col = n + 2
for c in range(num_col):
board.append([0]*num_row)
def display():
'''print the board'''
to_print = " "
for i in range(num_col):
to_print = to_print + f'[{i}]'
print(to_print)
for i in range(num_row):
to_print = f'[{i:2}]'
for j in range(num_col):
to_print = f'{to_print}{disk[board[j][i]]:2}'
print(to_print)
def game():
'''play the game'''
n = input('Please input N:')
init_board(int(n))
p = 0
while True:
c = input(f'Player {p} select colomn:')
if c == 'q': # quit the game
print(f'Player {p} resigned')
break
# drop disk
f = drop_disk(int(c), p+1)
if f == 0: # illegal move
print(f'Column {c} is an illegal move')
continue
display()
# check winner and switch side
w = have_winner()
if w == 1:
print(f'Player {p} won')
break
elif w == 2:
print('draw')
break
else:
p = (p + 1)%2
def drop_disk(c, player):
"""player drop a disk at ch colomn. Return 1 if successfully drop the disk, return 0 if this is a illegal move, e.g. the colomn is full."""
if board[c][0] != 0:
return 0
for r in range(num_row -1, -1, -1):
if board[c][r] == 0:
board[c][r] = player
return 1
return 0
def have_winner():
"""return 1 if there is a winner, return 2 if the board is full, return 0 otherwise"""
for c in range(num_col):
for r in range(num_row):
if board[c][r] == 0:
return 0
return 2
# MAIN CODE
game()
Related
I am trying to use minimax algo to find a best move for a game.
The game is 2 players take turns to pick a number from a pile [0,1,2,,,8]
Winning Condition: player wins the game if the player contains three numbers and their sum is 14.
The initial game state is given by the argument like:
4 1 2 3 4
The first number indicate the total length and the following numbers are the numbers taken by player each turn. In this example the player A has [1,3] and player B has [2,4]
My problem is the algo can't give the correct answer:
Like when the input is 4 4 1 7 8 my program cannot gives the correct move: it takes 0 not 3 for next move.
import sys
import math
totalMoves = int(sys.argv[1])
pile = [0, 1, 2, 3, 4, 5, 6, 7, 8]
# who are u
you = []
opponent = []
# cards in hand
playerA = []
playerB = []
# get all the cards into hand
for i in range(totalMoves):
# save card into playerB
if i % 2 != 0:
playerB.append(int(sys.argv[i+2]))
# save card into playerA
if i % 2 == 0:
playerA.append(int(sys.argv[i+2]))
# remove sent card in list
pile.remove(int(sys.argv[i+2]))
# identify which player you are
if totalMoves % 2 == 0:
you = playerA
opponent = playerB
else:
you = playerB
opponent = playerA
def find3Numbers(player): # calcluate the card in hand is equal to 14
arr_size = len(player)
if (len(player) >= 3):
for i in range(0, arr_size-2):
for j in range(i + 1, arr_size-1):
for k in range(j + 1, arr_size):
if (player[i] + player[j] + player[k] == 14):
return True
else:
return False
def isNumberLeft(board):
if (len(board) == 0):
return False
else:
return True
def evaluate(player, oppo):
if (find3Numbers(player) == True):
return 10
elif (find3Numbers(oppo) == True):
return -10
else:
return 0
def minimax(board, player, oppo, depth, isMax):
score = evaluate(player, oppo)
if (score == 10):
return score
if (score == -10):
return score
if (isNumberLeft(board) == False):
return 0
if (isMax):
best = -math.inf
for card in board:
player.append(card)
board.remove(card)
best = max(best, minimax(board, player, oppo, depth+1, not isMax))
board.append(card)
player.remove(card)
return best
else:
best = +math.inf
for card in board:
oppo.append(card)
board.remove(card)
best = min(best, minimax(board, player, oppo, depth+1, not isMax))
board.append(card)
oppo.remove(card)
return best
def bestMove():
bestScore = -math. inf
bestNum = -math.inf
for card in pile:
you.append(card)
pile.remove(card)
score = minimax(pile, you, opponent, 0, False)
pile.append(card)
you.remove(card)
if (bestScore < score):
bestNum = card
bestScore = score
return bestNum
you.append(bestMove())
I am currently trying to make a Tic Tac Toe game with minimax implemented in Python. Another feature that I'm trying to implement is different board sizes. But overall, unfortunately, the algorithm is not working.
As a beginner, this is not a surprise for me, but this case seems hopeless. I tried tweaking quite a lot of things (may seem like a lot just to me) just to end up with the same result - the computer filling up the fields from top left to bottom right.
#Sprawdzenie czy ktos wygral w poziomie lub pionie / straight line check
def winLine(line, letter):
return all(n == letter for n in line)
#Utworzenie nowej listy z elementow przekatnych / diagonal check
def winDiagonal(board, letter):
arr = []
tArr = []
for n in range(boardSize):
arr.append(board[n][n])
tArr.append(board[n][boardSize-n-1])
if winLine(arr, letter):
return True
elif winLine(tArr, letter):
return True
else:
return False
def checkWinner (board):
#Liczenie wolnych pol / checking the available fields
openSpots = 9
for n in range(boardSize):
for m in range(boardSize):
if board[n][m] == '0':
openSpots += 1
#Transpozycja planszy, by mozna bylo latwo zastosowac winLine na kolumach / transposition of the board
for letter in (person, ai):
transPos = list(zip(*board))
#Sprawdzanie w poziomie / horizontal check
if any(winLine(row, letter) for row in board):
#print('winline horizontal')
return letter
#Sprawdzanie w pionie / vertical check
elif any (winLine(col, letter) for col in transPos):
#print('winline vertical')
return letter
#Sprawdzanie po przekatnych / diagonal check
elif winDiagonal(board, letter):
return letter
elif openSpots == 0: return 'tie'
else: return 'none'
#Funkcja sprawdzajaca czy dane pole jest wolne / checks whether the field is available
def available (row, col):
global board
#Sprawdzenie czy pole jest wolne
if board[row][col] == '0':
return True
else:
return False
#Stale dla algorytmu minimax / minimax initial scores to compare against
minTarget = float('inf')
maxTarget = float('-inf')
#Slownik z wartosciami liczbowi dla wynikow, komputer maksymalizuje / a dictionary with scores for particular results
scores = {
'X': 10,
'O': -10,
'tie': 0
}
#Algorytm minimax
def minimax(myBoard, depth, maximizes):
#Sprawdzenie czy zaszla wygrana lub remis / Checking whether there is a win or tie
res = checkWinner(myBoard)
if (res != 'none'):
return scores[res]
#Gracz maksymalizujacy/ Maximizing player
elif maximizes == True:
bestScoreMax = maxTarget
for n in range(boardSize):
for m in range(boardSize):
if board[n][m] == '0':
board[n][m] = person
score = minimax(board, depth + 1, False)
board[n][m] = '0'
bestScoreMax = max([score, bestScoreMax])
return bestScoreMax
#Gracz minimalizujacy / minimizing player
elif maximizes == False:
bestScoreMin = minTarget
for n in range(boardSize):
for m in range(boardSize):
if board[n][m] == '0':
board[n][m] = ai
score = minimax(board, depth + 1, True)
board[n][m] = '0'
bestScoreMin = min([score, bestScoreMin])
return bestScoreMin
def makeMove(row, col):
global board
board[row][col] = ai
def computedMove():
global board
myBoard = board
computedTarget = maxTarget
moveX = 2
moveY = 2
for n in range(boardSize):
for m in range(boardSize):
if myBoard[n][m] == '0':
score = minimax(myBoard, 0, True)
if score > computedTarget:
computedTarget = score
moveX = n
moveY = m
makeMove(moveX, moveY)
#print(str(move.x) + ' ' + str(move.y))
# Funkcja pobierajaca ruch uzytkownika / player input for the move
def getPlayerMove():
global board
res = input('Please type in your move on the form \"x y\", x being the number of the row and y the number of the column of your choosing.\n')
col, row = res.split(" ")
row = int(row)
col = int(col)
if available(row-1, col-1):
board[row-1][col-1] = person
else:
print('You cannot make that move')
getPlayerMove()
def drawBoard():
global board
for n in range(boardSize):
for m in range(boardSize):
if board[n][m] == '0':
print(' - ', end='')
else:
print(' '+board[n][m]+' ', end='')
print('\n')
#Zmienna powiadamiajaca o stanie rozgrywki / variable indicating the state of the game
playing = False
# initializing the variable
boardSize = 0
# initializing the players
person = 'X'
ai = 'O'
#Gracz posiadajacy ruch (a takze rozpoczynajacy) / player who is playing at the moment
currentPlayer = ''
while True:
currentPlayer = person
boardSize = int(input("Please enter the size of the board. (one side)\n"))
global board
board = [['0' for i in range(boardSize)] for i in range(boardSize)]
print("You go first.")
playing = True
while playing:
if currentPlayer == person:
drawBoard()
getPlayerMove()
if checkWinner(board) == person:
drawBoard()
print("Yaay, you won!")
playing = False
else:
if checkWinner(board) == 'tie':
drawBoard()
print('It\'s a tie!')
break
else:
currentPlayer = ai
elif currentPlayer == ai:
computedMove()
if checkWinner(board) == ai:
drawBoard()
print('You lose!')
playing = False
else:
if checkWinner(board) == 'tie':
drawBoard()
print('It\'s a tie!')
break
else:
currentPlayer = person
if not input('Do you want to play again?').lower().startswith('y'):
break
In computedMove, you should first play the ai move then check the scores.
def computedMove():
global board
myBoard = board
computedTarget = maxTarget
moveX = 2
moveY = 2
for n in range(boardSize):
for m in range(boardSize):
if myBoard[n][m] == '0':
myBoard[n][m] = ai #This is added
score = minimax(myBoard, 0, True)
if score > computedTarget:
computedTarget = score
moveX = n
moveY = m
makeMove(moveX, moveY)
Also in minimax function, you should use same variable for myBoard and board.
I'm currently working on making a Game of Life program (UNI related, beginner course), by using nested lists.
However I can't seem to get the update() method to work properly, I've no clue what's wrong. The generation of the first board is okay, but the update leaves only the cornercells alive, and the rest dead.
All methodcalls in this class originates from other .py files, which works well.
from random import randint
from cell import *
class Spillebrett:
def __init__(self, rows, columns):
self.genNumber = 0
self._rows = rows
self._columns = columns
self._grid = []
for i in range(self._rows):
self._grid.append([])
for j in range(self._columns):
self._grid[i].append(cell())
self.generate()
def drawBoard(self):
for i in self._grid:
print(" ".join(map(str, i)))
print()
#Method updates genNumber, checks if cells are alive or dead and updates the board accordingly
#Currently only yield board with corner-cells alive
def updateBoard(self):
self.genNumber += 1
toLive = []
toDie = []
for x, row in enumerate(self._grid):
for y, cell in enumerate(rad):
if cell.areAlive() is True:
counter = len(self.findNeighbour(x, y))
if counter < 2 or counter > 3:
toDie.append(cell)
elif counter == 2 or counter == 3:
toLive.append(cell)
elif cell.areAlive() is False:
counter = len(self.findNeighbour(x, y))
if counter == 3:
toLive.append(cell)
for i in toDie:
i.setDead()
for i in toLive:
i.setAlive()
return self.genNumber
#Code given by Uni
def generate(self):
for i in range(self._rows):
for j in range(self._columns):
rand = randint(0, 3)
if rand == 3:
self._grid[i][j].setAlive()
#Code given by Uni
def findNeighbour(self, row, column):
neighbourList = []
for i in range(-1, 2):
for j in range(-1, 2):
neighbourRow = rad + i
neighbourcolumn = column + j
if(neighbourRow == rad and neighbourcolumn == column) is not True:
if(neighbourRow < 0 or neighbourcolumn < 0 or neighbourRow >
self._rows - 1 or neighbourcolumn > self._columns - 1) is not True:
neighbourList.append(self._grid[neighbourRow][neighbourcolumn])
return neighbourList
def findAllAlive(self):
self._alive = 0
for i in range(self._rows):
for j in range(self._columns):
if self._grid[i][j].areAlive() is True:
self._alive += 1
return self._alive
Ok I have a feeling that this is a simple simple issue but I have been staring at this code for about 10 hours now.
The issue I am having is in mastermind is that once I get it to recognize that I have the correct colors in the right spot I can get it to display the right spots with X and the wrong spots with O. I need to be able to convert that so instead of X and O I need it to tell the user that he/she has 2 blacks and one white
For example: The secret code is RGYB The user enters RGOY so then Python relays "You have 2 blacks(The R and G spots) and one 1 White (The Y because it's the right color just in the wrong index) As of right now I got it to display X for the right color in the right spot and anything else it is an O
I will post what I have been working with now but today I am at my wit's end
https://pastebin.com/HKK0T7bQ
if correctColor != "XXXX":
for i in range(4):
if guess[i] == tempCode[i]:
correctColor += "X"
if guess[i] != tempCode[i] in tempCode:
correctColor += "O"
print (correctColor + "\n")
if correctColor == "XXXX":
if attempts == 1:
print ("You think you are sweet because you got it right on the first try? Play me again!")
else:
print ("Well done... You needed " + str(attempts) + " attempts to guess.")
game = False
A few comments
X and O
you use X and 0 to denote the success, it will be easier and faster to use a list or tuple or booleans for this, that way you can use sum() to count how many colors and locations were correct. Then whether you represent that with X and O or red and white pins is a matter for later
compartmentalization
Your game logic (guess input, input validation, do you want to continue, etc) is mixed with the comparison logic, so it would be best to separate the different functions of your program into different methods.
This is an fineexample to introduce object oriented programming, but is so simple it doesn't need OO, but it can help. What you need is a method which takes a series of colours and compares it to another series of colours
Standard library
Python has a very extended standard library, so a lot of stuff you want to do probably already exists
Correct colours
to count the number of letters which occur in 2 strings, you can use collections.Counter
guess = "RGOY "
solution = "RGYB"
a = collections.Counter(guess)
b = collections.Counter(solution)
a & b
Counter({'G': 1, 'R': 1, 'Y': 1})
correct_colours = sum((a & b).values())
3
So the user guessed 3 colours correctly
Correct locations
can be solved with an easy list comprehension
[g == s for g, s in zip(guess, solution)]
[True, True, False, False]
sum(g == s for g, s in zip(guess, solution))
2
so the used put 2 colours on the correct location
This is a MasterMind I made in Python. Hope you like it and it helped you! :)
import random
import time
from tkinter import *
def select_level():
global level
level = level_selector.get()
root.destroy()
root = Tk()
level_selector = Scale(root, from_=1, to=3, tickinterval=1)
level_selector.set(0)
level_selector.pack()
Button(root, text="Select a difficulty level", command=select_level).pack()
mainloop()
cpc_1_digit = 0
cpc_2_digit = 0
cpc_3_digit = 0
cpc_4_digit = 0
p_1_digit = 0
p_2_digit = 0
p_3_digit = 0
p_4_digit = 0
correct_correct = 0
correct_wrong = 0
chances = 0
if level == 1:
chances = 15
elif level == 2:
chances = 10
else:
chances = 7
cpc_1_digit = random.randint(0, 9)
while cpc_2_digit == cpc_1_digit or cpc_2_digit == cpc_3_digit or cpc_2_digit ==
cpc_4_digit:
cpc_2_digit = random.randint(0, 9)
while cpc_3_digit == cpc_1_digit or cpc_3_digit == cpc_2_digit or cpc_3_digit ==
cpc_4_digit:
cpc_3_digit = random.randint(0, 9)
while cpc_4_digit == cpc_1_digit or cpc_4_digit == cpc_2_digit or cpc_4_digit ==
cpc_3_digit:
cpc_4_digit = random.randint(0, 9)
while chances > 0:
correct_correct = 0
correct_wrong = 0
answer = input("Enter a four-digit number with different digits (e.g 1476): ")
p_1_digit = int(answer[0])
p_2_digit = int(answer[1])
p_3_digit = int(answer[2])
p_4_digit = int(answer[3])
if p_1_digit == cpc_1_digit:
correct_correct = int(correct_correct) + 1
elif p_1_digit == cpc_2_digit or p_1_digit == cpc_3_digit or p_1_digit ==
cpc_4_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
if p_2_digit == cpc_2_digit:
correct_correct = correct_correct + 1
elif p_2_digit == cpc_1_digit or p_2_digit == cpc_3_digit or p_2_digit ==
cpc_4_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
if p_3_digit == cpc_3_digit:
correct_correct = int(correct_correct) + 1
elif p_3_digit == cpc_1_digit or p_3_digit == cpc_2_digit or p_3_digit ==
cpc_4_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
if p_4_digit == cpc_4_digit:
correct_correct = int(correct_correct) + 1
elif p_4_digit == cpc_1_digit or p_4_digit == cpc_3_digit or p_4_digit ==
cpc_2_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
print("")
if int(correct_correct) == 4:
print("Congratsulations! You found the computer's number!")
break
elif int(correct_wrong) > 0 or int(correct_correct) >= 1 and int(correct_correct)
< 4:
print("You got " + str(correct_correct) + " correct digit(s) in the correct
place, and " + str(correct_wrong) + " correct digit(s) but in wrong place.")
elif int(correct_correct) == 0 and int(correct_wrong) == 0:
print("You didn't guess any number, try again!")
else:
raise Exception("CheckError: line 69, something went wrong with the
comparings.")
exit()
print("")
chances = chances - 1
if chances == 0:
print("You lost... The secret number was " + str(cpc_1_digit) + str(cpc_2_digit)
+ str(cpc_3_digit) + str(cpc_4_digit) + ". Try again by rerunning the program.")
time.sleep(4)
I am currently working on a connect 4 game in python and I was hoping to allow the player to customise the board (be able to choose the size of the board. However when I try to add this in it breaks my code. Is there any way around this? Or will I just have to hard code the board size in?
def CreateBoard(r, c, b, n):
for i in range(1,(r+1)):
n.append(str(i))
b.append(n)
for i in range(c):
b.append(['*']*(r))
return(b)
def printBoard(b):
for lst in b:
print(" ".join(lst))
return b
def check(board, n):
n = []
for i in range(1,len(board[1])+1):
if board[1][i-1] == '*':
n.append(i)
print(n)
user = (input('Enter column: '))
if(user.isdigit() == True):
user = int(user)
if (user in n):
return(user)
print('Invalid input')
return check(board, n)
def WinningCon(b, r, u, c):
'row'
loop1 = True
rowCon = ""
colCon = ""
for i in range(0,len(b[1])):
rowCon += b[r][i]
if('X'*4 in rowCon) or('O'*4 in rowCon):
return(True)
for i in range(1,c+1):
colCon += b[i][u-1]
if('X'*4 in colCon) or('O'*4 in colCon):
return(True)
def Diag2(u, r, b, row, column):
utemp1 = u-1
utemp2 = u-1
rtemp1 = r
rtemp2 = r
end = ""
beg = ""
while(True):
beg += b[rtemp1][utemp1]
if(rtemp1 == 1):
break
elif(utemp1 == column):
break
rtemp1 -= 1
utemp1 += 1
while(True):
if(rtemp2 == row-1):
break
elif(utemp2 == 0):
break
rtemp2 +=1
utemp2 -=1
end += b[rtemp2][utemp2]
beg = beg[::-1]
fullstring = beg+end
if('X'*4 in fullstring) or('O'*4 in fullstring):
return(True)
def Diag1(u, r, b, row, column):
utemp1 = u-1
utemp2 = u-1
rtemp1 = r
rtemp2 = r
end = ""
beg = ""
while(True):
beg += b[rtemp1][utemp1]
if(rtemp1 == 1):
break
elif(utemp1 == 0):
break
rtemp1 -= 1
utemp1 -= 1
while(True):
if(rtemp2 == row-1):
break
elif(utemp2 == column):
break
rtemp2 +=1
utemp2 +=1
end += b[rtemp2][utemp2]
beg = beg[::-1]
fullstring = beg+end
if('X'*4 in fullstring) or('O'*4 in fullstring):
return(True)
def ProcessInput(u, s, b, r):
rowNum = r-1
u = u-1
while(not b[rowNum][u] == '*'):
rowNum -= 1
b[rowNum][u] = s
return(rowNum)
def EndGame(g, b, p):
printBoard(b)
print("Congrats %s, you've won!" %p)
replayGame = input('Would you like to play again? Yes or No?\n').lower()
if replayGame == 'yes':
MainGame()
else:
g = False
return(g)
def MainGame():
row = 7 #input('Enter number of rows')
column = 6 #input('Enter number of columns')
board = []
nums = []
board = CreateBoard(row, column, board, nums)
player1 = 'K'#input('Enter name: ')
player2 = 'A'#input('Enter name: ')
turn = 1
GameOn = True
while(GameOn):
board = printBoard(board)
if(not turn%2 == 0):
print("It's %s's turn" %player1)
user = check(board, nums)
rc = ProcessInput(user, "X", board, row)
if(WinningCon(board, rc , user, column) == True):
GameOn = EndGame(GameOn, board, player1)
elif(Diag1(user, rc, board, row, column) == True):
GameOn = EndGame(GameOn, board, player1)
elif(Diag2(user, rc, board, row, column) == True):
GameOn = EndGame(GameOn, board, player1)
else:
print("It's %s's turn" %player2)
user = check(board, nums)
rc = ProcessInput(user, "O", board, row)
if(WinningCon(board, rc , user, column) == True):
GameOn = EndGame(GameOn, board, player2)
elif(Diag1(user, rc, board, row, column) == True):
GameOn = EndGame(GameOn, board, player2)
elif(Diag2(user, rc, board, row, column) == True):
GameOn = EndGame(GameOn, board, player2)
turn +=1
MainGame()
An example of an error message it throws up:
Enter number of columns4
Enter number of rows5
1 2 3 4
* * * *
* * * *
* * * *
* * * *
* * * *
It's K's turn
[1, 2, 3, 4]
Enter column: 4
Traceback (most recent call last):
File "C:\Users\609380145\Python\Code Dojo\Connect 4\Connect 4 v3.py", line 169, in <module>
MainGame()
File "C:\Users\609380145\Python\Code Dojo\Connect 4\Connect 4 v3.py", line 150, in MainGame
GameOn = EndGame(GameOn, board, player1)
File "C:\Users\609380145\Python\Code Dojo\Connect 4\Connect 4 v3.py", line 127, in EndGame
MainGame()
File "C:\Users\609380145\Python\Code Dojo\Connect 4\Connect 4 v3.py", line 153, in MainGame
elif(Diag2(user, rc, board, row, column) == True):
File "C:\Users\609380145\Python\Code Dojo\Connect 4\Connect 4 v3.py", line 66, in Diag2
beg += b[rtemp1][utemp1]
IndexError: list index out of range
def CreateBoard(r, c, b, n):
for i in range(1,(r+1)):
n.append(str(i))
b.append(n)
for i in range(c):
b.append(['*']*(r))
return(b)
def printBoard(b):
for lst in b:
print(" ".join(lst))
return b
def check(board, n):
n = []
for i in range(1,len(board[1])+1):
if board[1][i-1] == '*':
n.append(i)
print(n)
user = (input('Enter column: '))
if(user.isdigit() == True):
user = int(user)
if (user in n):
return(user)
print('Invalid input')
return check(board, n)
def WinningCon(b, r, u, c):
loop1 = True
rowCon = ""
colCon = ""
for i in range(0,len(b[1])):
rowCon += b[r][i]
if('X'*4 in rowCon) or('O'*4 in rowCon):
return(True)
for i in range(1,c+1):
colCon += b[i][u-1]
if('X'*4 in colCon) or('O'*4 in colCon):
return(True)
def Diag2(u, r, b, column, row):
utemp1 = u-1
utemp2 = u-1
rtemp1 = r
rtemp2 = r
end = ""
beg = ""
while(True):
beg += b[rtemp1][utemp1]
rtemp1 -= 1
utemp1 += 1
if(rtemp1 == 1):
break
elif(utemp1 >= column - 1):
break
while(True):
end += b[rtemp2][utemp2]
rtemp2 +=1
utemp2 -=1
if(rtemp2 >= row):
break
elif(utemp2 == 0):
break
beg = beg[::-1]
fullstring = beg+end
if('X'*4 in fullstring) or('O'*4 in fullstring):
return(True)
def Diag1(u, r, b, column, row):
utemp1 = u-1
utemp2 = u-1
rtemp1 = r
rtemp2 = r
end = ""
beg = ""
while(True):
beg += b[rtemp1][utemp1]
rtemp1 -= 1
utemp1 -= 1
if(rtemp1 == 1):
break
elif(utemp1 == 0):
break
while(True):
print('Row ' + str(rtemp2))
print('Colum ' +str(utemp2))
end += b[rtemp2][utemp2]
rtemp2 +=1
utemp2 +=1
if(rtemp2 >= row):
break
elif(utemp2 >= column-1):
break
beg = beg[::-1]
fullstring = beg+end
if('X'*4 in fullstring) or('O'*4 in fullstring):
return(True)
def ProcessInput(u, s, b, r):
rowNum = r
u = u-1
print('Row: ' + str(rowNum))
print('Col: ' + str(u))
while(not b[rowNum][u] == '*'):
rowNum -= 1
print('New Row Num: ' + str(rowNum))
b[rowNum][u] = s
printBoard(b)
return(rowNum)
def EndGame(g, b, p):
printBoard(b)
print("Congrats %s, you've won!" %p)
replayGame = input('Would you like to play again? Yes or No?\n').lower()
if replayGame == 'yes':
MainGame()
else:
g = False
return(g)
def MainGame():
column = int(input('Enter number of columns'))
row = int(input('Enter number of rows'))
board = []
nums = []
board = CreateBoard(column, row, board, nums)
player1 = 'K'#input('Enter name: ')
player2 = 'A'#input('Enter name: ')
turn = 1
GameOn = True
while(GameOn):
board = printBoard(board)
user = check(board, nums)
if(turn%2 != 0):
print("It's %s's turn" %player1)
rc = ProcessInput(user, "X", board, row)
else:
print("It's %s's turn" %player2)
rc = ProcessInput(user, "O", board, row)
if(WinningCon(board, rc , user, row) == True):
GameOn = EndGame(GameOn, board, player1)
elif(Diag1(user, rc, board, column, row) == True):
GameOn = EndGame(GameOn, board, player1)
elif(Diag2(user, rc, board, column, row) == True):
GameOn = EndGame(GameOn, board, player1)
turn +=1
MainGame()