I'm having some trouble improving the Connect 4 game that is made in Python. I was wondering if I could get rid of the global
statements and pass the variables between parameters and return its values. Also to put all of this in a class. I was wondering if this is possible.
And any more improvements that I could use would be appreciated a lot. Be gentle since I'm a newbie with Python.
grids = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
check = []
user = 1
# THIS WAS VERSION ONE
# def GridBuilder(x,y):
# Colum_Count_Str = x
# Colum_Count = int(Colum_Count_Str)
# Row_Count_Str = y
# Row_Count = int(Row_Count_Str)
#
# Grids = [] * Colum_Count
#
# for Current_Grid_Insert in range (Colum_Count):
# Grids.insert(Current_Grid_Insert,[0]*Row_Count)
#
# return Grids
class FullCapacity_error(Exception):
pass
def user_def():
#Change the global vartiables into local variables
#Define them in the parameters of the functions.
global user
if user < 2:
user = 2
else:
user = 1
return user
def FullCapacity():
global FullCapacity_error
while True:
try:
if grids[3][userInput - 1] != 0:
raise FullCapacity_error
else:
break
except FullCapacity_error:
print("This row is full, try another one!")
confirmed()
def confirmed():
PlayTheGame = True
while PlayTheGame:
try:
global userInput
userInput = int(input("\n Input a coin, player " + str(user) + "(1,4)\n"))
if 5 > userInput > 0:
PlayTheGame = False
else:
print("This number exceeds the board value.")
except ValueError:
print("This number exceeds the board value.")
def placement_def():
for i in range(0, 4):
counter = 0
FullCapacity()
if grids[i][userInput - 1] == 0:
grids[i][userInput - 1] = int(user)
print("\n Current Board\n", grids[3], "\n", grids[2], "\n", grids[1], "\n", grids[0])
break
def check_def():
global loop
global check
for i in range(0, 4):
for a in range(0, 4):
check.append(grids[i][a])
if check == [1, 1, 1, 1] or check == [2, 2, 2, 2]:
print("player " + str(user) + " has won")
loop = False
return loop
else:
check = []
for i in range(0, 4):
for a in range(0, 4):
check.append(grids[a][i])
if check == [1, 1, 1, 1] or check == [2, 2, 2, 2]:
print("player " + str(user) + " has won")
loop = False
return loop
else:
check = []
def checkEmpty_def():
global check
for i in range(0, 4):
for a in range(0, 4):
check.append(grids[i][a])
if 0 not in check:
print("full")
def checks_def():
return check_def() and checkEmpty_def() and diagcheck_def()
def diagcheck_def():
global loop
global check
check = []
diag = 0
for i in range(0, 4):
check.append(grids[diag][diag])
diag = diag + 1
if check == [1, 1, 1, 1] or check == [2, 2, 2, 2]:
print("player " + str(user) + " has won")
loop = False
return loop
check = []
diag = 3
diag2 = 0
for i in range(0, 4):
check.append(grids[diag][diag2])
if check == [1, 1, 1, 1] or check == [2, 2, 2, 2]:
print("player " + str(user) + " has won")
loop = False
return loop
loop = True
while loop:
check_def()
confirmed()
placement_def()
checks_def()
if not loop:
break
user_def()