From de0ad5a005c18c9b303a5fd5bb6d65795e6a678a Mon Sep 17 00:00:00 2001 From: Vincent Rodley Date: Tue, 12 Aug 2025 10:59:25 +1200 Subject: [PATCH] basic algorithm CPU - plays a random move but takes free wins and blocks instant wins --- main.py | 29 ++++++++++++++++++++--------- 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/main.py b/main.py index 1178237..5117271 100644 --- a/main.py +++ b/main.py @@ -1,6 +1,8 @@ import os import sys +from copy import deepcopy from colours import Colours as C +import random # =========================== # | Helper functions | @@ -77,15 +79,23 @@ def local_move_provider(player, board): return col def cpu_move_provider(player, board): - - i = 0 - while i < len(board): - if any([t == 'O' for t in board[i]]): + col = random.randint(0, 6) + while 'O' not in board[col]: + col += 1 + + # prevent immediate wins + other_p = 'Y' if player == 'R' else 'R' + for other_p_col in range(len(board)): + if 'O' not in board[other_p_col]: + continue + + new_board = deepcopy(board) + new_board[other_p_col][new_board[other_p_col].index('O')] = other_p + if checkWin(new_board, other_p) != None: + col = other_p_col break - else: - i += 1 - print(i) - return i + + return col # =========================== # | Main game loop | @@ -140,7 +150,8 @@ def play_lan_client(): return def play_vs_computer(): - play_game(cpu_move_provider, local_move_provider) + # play_game(cpu_move_provider, local_move_provider) + play_game(local_move_provider, cpu_move_provider) # =========================== # | Menu |