basic algorithm CPU - plays a random move but takes free wins and blocks instant wins

This commit is contained in:
Vincent Rodley 2025-08-12 10:59:25 +12:00
parent 9a47d3fd85
commit de0ad5a005

29
main.py
View File

@ -1,6 +1,8 @@
import os import os
import sys import sys
from copy import deepcopy
from colours import Colours as C from colours import Colours as C
import random
# =========================== # ===========================
# | Helper functions | # | Helper functions |
@ -77,15 +79,23 @@ def local_move_provider(player, board):
return col return col
def cpu_move_provider(player, board): def cpu_move_provider(player, board):
col = random.randint(0, 6)
i = 0 while 'O' not in board[col]:
while i < len(board): col += 1
if any([t == 'O' for t in board[i]]):
# 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 break
else:
i += 1 return col
print(i)
return i
# =========================== # ===========================
# | Main game loop | # | Main game loop |
@ -140,7 +150,8 @@ def play_lan_client():
return return
def play_vs_computer(): 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 | # | Menu |