Oct-27-2018, 03:53 PM
Hello, I was wondering if it's possible to refactor this piece of code to make a connect 4 game? I understand that it can be done way more efficiently, but I'm stuck.. Could somebody help me out?
grid1 = [0, 0, 0, 0] grid2 = [0, 0, 0, 0] grid3 = [0, 0, 0, 0] grid4 = [0, 0, 0, 0] grids = [grid1, grid2, grid3, grid4] check = [] user = 1 class FullCapacity_error(Exception): pass def playerWins(): print("player " + str(user) + " has won") def grid_def(): print("", grid4, "\n", grid3, "\n", grid2, "\n", grid1) def user_def(): global user if user < 2: user = 2 else: user = 1 return user def FullCapacity(): while True: try: if grid4[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("\ninput a slot player " + str(user) + "(1,4)\n")) if userInput < 5 and 0 < userInput: PlayTheGame = False else: print("invalid int") except ValueError: print("invalid input") def placement_def(): for i in range(0, 4): counter = 0 FullCapacity() if grids[i][userInput - 1] == 0: grids[i][userInput - 1] = int(user) grid_def() 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]: playerWins() 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]: playerWins() 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(): check_def() checkEmpty_def() 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]: playerWins() 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]: playerWins() loop = False return loop loop = True while loop: check_def() confirmed() placement_def() checks_def() if not loop: break user_def()