Advertisement
vasil_k_k

workshop_connect_four

Aug 18th, 2023 (edited)
221
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.14 KB | None | 0 0
  1. def print_board():
  2.     [print(f"[{', '.join(row)}]") for row in board]
  3.  
  4.  
  5. def place_on_the_board(col_idx: int, player_symbol: str, row_idx=-1):
  6.     while board[row_idx][col_idx] != "0":
  7.         row_idx -= 1
  8.     board[row_idx][col_idx] = player_symbol
  9.  
  10.     return ROWS + row_idx
  11.  
  12.  
  13. def check_for_win(row: int, col: int, ):
  14.     check_list = {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0}
  15.  
  16.     directions = ((1, 0), (0, -1), (0, 1), (-1, -1), (1, 1), (-1, 1), (1, -1))
  17.     # (bottom), (left), (right), (top-left), (bottom-right), (top-right), (bottom-left)
  18.  
  19.     for index, direction in enumerate(directions):
  20.         checked_row = row + direction[0]
  21.         checked_col = col + direction[1]
  22.  
  23.         while 0 <= checked_row < ROWS and 0 <= checked_col < COLS and \
  24.                 board[row][col] == board[checked_row][checked_col]:
  25.             check_list[index] += 1
  26.             checked_row += direction[0]
  27.             checked_col += direction[1]
  28.  
  29.     if counter_for_draw == ROWS * COLS:
  30.         print_board()
  31.         quit(print('\033[92m' + "Draw!"))
  32.  
  33.     if check_list[0] == 3 or check_list[1] + check_list[2] >= 3 or \
  34.             check_list[3] + check_list[4] >= 3 or check_list[5] + check_list[6] >= 3:
  35.         print_board()
  36.         quit(print('\033[92m' + f"Player {current_player} " + '\033[92m' + "wins!"))
  37.  
  38.  
  39. ROWS, COLS = 6, 7
  40.  
  41. counter_for_draw = 0
  42.  
  43. board = [["0"] * COLS for _ in range(ROWS)]
  44.  
  45. current_player, second_player = '\x1b[33m1\x1b[39m', '\x1b[31m2\x1b[39m'
  46.  
  47. while True:
  48.  
  49.     print_board()
  50.  
  51.     try:
  52.         col_index = int(input(f"Player {current_player}, please chose a column: ")) - 1
  53.         if not 0 <= col_index < COLS:
  54.             raise ValueError
  55.         row_index = place_on_the_board(col_index, current_player)
  56.     except ValueError:
  57.         print('\033[91m' + f"Select a valid number in the range (1-{COLS})" + '\033[0m')
  58.         continue
  59.     except IndexError:
  60.         print('\033[91m' + "No empty spaces on that column, choose another one!" + '\033[0m')
  61.         continue
  62.  
  63.     counter_for_draw += 1
  64.     check_for_win(row_index, col_index)
  65.     current_player, second_player = second_player, current_player
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement