Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

AI #8

Merged
merged 14 commits into from
Mar 12, 2024
Merged

AI #8

Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file added AI/__init__.py
Empty file.
2 changes: 1 addition & 1 deletion AI/ai_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ def set_strategy(self, strategy: ai_strategy.AIStrategy):

# Runs the strategy as a new thread and returns the thread
def run_strategy(self):
thread = Thread(target=self._strategy.thread_entry)
thread = Thread(target=self._strategy.thread_entry, daemon=True)
thread.start()
return thread

Expand Down
41 changes: 21 additions & 20 deletions AI/ai_strategy.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,20 @@

class AIStrategy(ABC, GameClient):

def __init__(self, second_player: bool):
def __init__(self):

self._strength = "Placeholder"
self._good_luck_message = "Good luck!"
self._good_game_message_lost = "Good game! You played well."
self._good_game_message_won = "Good game! I'll have better luck next time."
self._good_game_message_draw = "Good game! We are evenly matched."
self._current_uuid = None
self._rulebase = ai_rulebase.AIRulebase()
self._ip = "127.0.0.1"
self._port = 8765

def post_init(self):
#needs to be called by inheriting classes at the end of their __init__ function
super().__init__(self._ip, self._port, self._player)

def thread_entry(self):
Expand Down Expand Up @@ -54,10 +58,10 @@ async def _message_handler(self, message_type: str):
# AI does not need this
pass
case "game/start":
logger.info("start")
if self._current_player == self._player:
logger.info(f"start {self._starting_player.uuid}")
if self._starting_player == self._player:
await self.do_turn()
#await self.wish_good_luck()
await self.wish_good_luck()

case "game/end":
await self.say_good_game()
Expand All @@ -83,7 +87,7 @@ async def wish_good_luck(self):
await self.chat_message(self._good_luck_message)

async def say_good_game(self):
if self._winner.uuid == self._ai_uuid:
if self._winner.uuid == self._current_uuid:
await self.chat_message(self._good_game_message_won)
elif self._winner.uuid == None:
await self.chat_message(self._good_game_message_draw)
Expand All @@ -105,39 +109,36 @@ def get_empty_cells(self, game_status: list):
async def do_turn(self):
pass



class WeakAIStrategy(AIStrategy):

def __init__(self, second_player: bool = False):
self._ai_uuid = "108eaa05-2b0e-4e00-a190-8856edcd56a5"
self._ai_uuid2 = "108eaa05-2b0e-4e00-a190-8856edcd56a6"
def __init__(self, uuid: str = '108eaa05-2b0e-4e00-a190-8856edcd56a5'):
super().__init__()
self._current_uuid = uuid
self._strength = "Weak"
self._good_luck_message = "Good luck! I'm still learning so please have mercy on me."
self._good_game_message_lost = "Good game! I will try to do better next time."
self._good_game_message_won = "Good game! I can't believe I won!"
self._good_game_message_draw = "Good game! I' happy I didn't lose."
self._player = Player(f"{self._strength} AI", random.randint(0, 0xFFFFFF), uuid=(self._ai_uuid if not second_player else self._ai_uuid2))
super().__init__(second_player)
self._player = Player(f"{self._strength} AI", random.randint(0, 0xFFFFFF), uuid=self._current_uuid)
self.post_init()

async def do_turn(self):

empty_cells = self.get_empty_cells(self._playfield)
move = random.randint(0, len(empty_cells) - 1)
await self.game_make_move(empty_cells[move][0], empty_cells[move][1])

class AdvancedAIStrategy(AIStrategy):

def __init__(self, second_player: bool = False):
self._ai_uuid = "108eaa05-2b0e-4e00-a190-8856edcd56a5"
self._ai_uuid2 = "108eaa05-2b0e-4e00-a190-8856edcd56a6"
def __init__(self, uuid: str = 'd90397a5-a255-4101-9864-694b43ce8a6c'):
super().__init__()
self._current_uuid = uuid
self._strength = "Advanced"
self._good_luck_message = "Good luck! I hope you are ready for a challenge."
self._good_game_message_lost = "Good game! I admire your skills."
self._good_game_message_won = "Good game! I hope you learned something from me."
self._good_game_message_draw = "Good game! I hope you are ready for a rematch."
self._player = Player(f"{self._strength} AI", random.randint(0, 0xFFFFFF), uuid=(self._ai_uuid if not second_player else self._ai_uuid2))
super().__init__(second_player)
self._player = Player(f"{self._strength} AI", random.randint(0, 0xFFFFFF), uuid=self._current_uuid)
self.post_init()

def check_winning_move(self, empty_cells: list, player: int):
"""
Expand Down Expand Up @@ -168,12 +169,12 @@ async def do_turn(self):
empty_cells = self.get_empty_cells(self._playfield)

# Check for own winning move
if winning_move:= self.check_winning_move(empty_cells, self._player_number) != None:
if (winning_move:= self.check_winning_move(empty_cells, self._player_number)) != None:
await self.game_make_move(winning_move[0], winning_move[1])
return

# Check for opponent winning move
if winning_move:= self.check_winning_move(empty_cells, self._opponent_number):
if (winning_move:= self.check_winning_move(empty_cells, self._opponent_number)) != None:
await self.game_make_move(winning_move[0], winning_move[1])
return

Expand Down
File renamed without changes.
11 changes: 9 additions & 2 deletions Client/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@
from uuid import UUID

# Set up logging
logging.basicConfig(level=logging.INFO)
logging.basicConfig(
format='%(asctime)s %(levelname)-8s %(message)s',
level=logging.INFO,
datefmt='%Y-%m-%d %H:%M:%S')
logger = logging.getLogger(__name__)

class GameClient:
Expand Down Expand Up @@ -170,7 +173,11 @@ async def _preprocess_message(self, message:str) -> str:
logger.error("Game start message received, but lobby does not contain 2 players. This should not happen and should be investigated.")
raise ValidationError("Game start message received, but lobby does not contain 2 players. This should not happen and should be investigated.")

self._opponent = self._lobby_status[0] if self._lobby_status[0].uuid is not str(self._player.uuid) else self._lobby_status[1]

self._opponent = self._lobby_status[0] if self._lobby_status[0] != self._player else self._lobby_status[1]

if self._opponent == self._player:
logger.info("ERROR WTF ALTER")
JM-Lemmi marked this conversation as resolved.
Show resolved Hide resolved

if str(self._player.uuid) == message_json["starting_player_uuid"]:
self._current_player = self._player
Expand Down
11 changes: 7 additions & 4 deletions Server/websocket_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,11 +99,14 @@ async def handler(self, websocket):

# check for winning state
if self._game.state.finished:
websockets.broadcast(self._connections, json.dumps({
finished_dict = {
"message_type": "game/end",
"winner_uuid": self._game.state.winner.uuid,
"final_playfiled": self._game.state.playfield,
}))
"final_playfield": self._game.state.playfield,
}
if self._game.state.winner != 0:
finished_dict["winner_uuid"] = str(self._game.players[self._game.state.winner].uuid)

websockets.broadcast(self._connections, json.dumps(finished_dict))
self._inprogress = False

# announce new game state
Expand Down
11 changes: 5 additions & 6 deletions UI/field_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@

class player_type(Enum):
local = auto()
ai = auto()
ai_weak = auto()
ai_strong = auto()
network = auto()
unknown = auto()

Expand All @@ -36,7 +37,7 @@ def set(self, name, type):
match type:
case player_type.local:
self.symbol.config(text="Lokal")
case player_type.ai:
case player_type.ai_strong, player_type.ai_weak:
self.symbol.config( text="Computer")
case player_type.network:
self.symbol.config(text="Online")
Expand All @@ -60,14 +61,12 @@ def __init__(self, view, players):
def _bind(self):
self.view.close.config(command=self.view.master.show_menu)

def end(self, *args):
def end(self, queue, *args):
root = self.view.master
queue = root.in_queue.get()
root.show(EndScreen, queue['win'])

def error(self, *args):
def error(self, queue, *args):
root = self.view.master
queue = root.in_queue.get()
msg = messages(type='move', message=queue['error_message'])
msg.display()

Expand Down
3 changes: 1 addition & 2 deletions UI/gamefield.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,8 @@ def change_active_player(self, player_id: int):
for i, player in enumerate(self.view.master.player):
player.highlight(i == player_id)

def turn(self, *args):
def turn(self, queue, *args):
root = self.view.master.master
queue = root.in_queue.get()
self.draw_field(matrix=queue['playfield'])
self.change_active_player(queue['next_player'])

Expand Down
6 changes: 4 additions & 2 deletions UI/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ def __init__(self):

self.devOptions = False
self.player = None
self.ai_thread = None
self.network_events = {}
self.out_queue = Queue()
self.in_queue = Queue()
Expand All @@ -34,7 +35,7 @@ def __init__(self):
self.bind("<<game/end>>", lambda *args: self.network_event_handler('game/end'))
self.bind("<<game/error>>", lambda *args: self.network_event_handler('game/error'))
self.bind("<<game/turn>>", lambda *args: self.network_event_handler('game/turn'))
self.bind("<<chat/message>>", lambda *args: self.network_event_handler('chat/message'))
self.bind("<<chat/receive>>", lambda *args: self.network_event_handler('chat/receive'))
self.show(Menu, True)

def show(self, Frame, *args, cache=False, **kwargs):
Expand Down Expand Up @@ -70,7 +71,8 @@ def start_server(self):

def network_event_handler(self, event):
try:
self.network_events[event]()
queue = self.in_queue.get()
self.network_events[event](queue)
except KeyError:
pass

Expand Down
13 changes: 8 additions & 5 deletions UI/multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
from Client.ui_client import client_thread
from .field_frame import player_type
from Server.main import server_thread
from AI.ai_context import AIContext
from AI.ai_strategy import AIStrategy, WeakAIStrategy, AdvancedAIStrategy

class Join(base_frame):
def __init__(self, master, *args, opponent=player_type.unknown, **kwargs):
Expand All @@ -23,9 +25,12 @@ def __init__(self, master, *args, opponent=player_type.unknown, **kwargs):
self.ready = False
if opponent != player_type.unknown:
server_thread(self.master.player)
if opponent in [player_type.ai_strong, player_type.ai_weak]:
ai_context = AIContext(AdvancedAIStrategy() if opponent == player_type.ai_strong else WeakAIStrategy())
self.master.ai = ai_context.run_strategy()

def _create_widgets(self, opponent):
title = 'Waiting for players to join' if opponent in [player_type.network, player_type.unknown] else 'Play local game against AI' if opponent == player_type.ai else 'Play local game against a friend'
title = 'Waiting for players to join' if opponent in [player_type.network, player_type.unknown] else 'Play local game against AI' if opponent in [player_type.ai_weak, player_type.ai_strong] else 'Play local game against a friend'
self.lblTitle = tk.Label(self, text=title, font=self.master.title_font)
self.btnRdy = tk.Button(self, text='Start', command=lambda *args: self.master.out_queue.put({'message_type': 'lobby/ready', 'args' : {'ready': not self.ready}}))
if opponent == player_type.local:
Expand All @@ -48,8 +53,7 @@ def _display_widgets(self,):
self.btnRdy2.grid(sticky=tk.E+tk.W+tk.N+tk.S, column=2, row=10)
self.btnExit.grid(sticky=tk.E+tk.W+tk.N+tk.S, column=5, row=1)

def _update_lobby(self):
queue = self.master.in_queue.get()
def _update_lobby(self, queue):
self.playerlist = []
for player in queue['player']:
self.playerlist.append([tk.Label(self, text=player.display_name),
Expand All @@ -65,8 +69,7 @@ def _update_lobby(self):
player[1].grid(sticky=tk.E+tk.W+tk.N+tk.S, column=4, row=4+i)


def _start_game(self):
queue = self.master.in_queue.get()
def _start_game(self, queue):
print(queue)
self.master.show(Field, **queue)

Expand Down
20 changes: 17 additions & 3 deletions UI/single.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,15 @@
from .base_frame import base_frame
from .multi import Join
from .field_frame import player_type
from Client.ui_client import client_thread
from .profile import Profile

class Singleplayer(base_frame):
def __new__(cls, master, *args, **kwargs):
if(master.player == None):
return Profile(master, *args, return_to=Singleplayer, **kwargs)
return super().__new__(cls, *args, **kwargs)

def __init__(self, master, *args, **kwargs):
super().__init__(master)
self._create_widgets()
Expand All @@ -14,8 +21,8 @@ def __init__(self, master, *args, **kwargs):

def _create_widgets(self):
self.lblTitle = tk.Label(self, text='Choose your opponent', font=self.master.title_font)
self.btnStrong = tk.Button(self, text='Strong AI', command=lambda *args: self.master.show(Join, opponent=player_type.ai))
self.btnWeak = tk.Button(self, text='Weak AI', command=lambda *args: self.master.show(Join, opponent=player_type.ai))
self.btnStrong = tk.Button(self, text='Strong AI', command=lambda *args: self.join_ai(True))
self.btnWeak = tk.Button(self, text='Weak AI', command=lambda *args: self.join_ai(False))
self.btnExit = tk.Button(self, text='Menu', command=lambda *args: self.master.show_menu())

def _display_widgets(self):
Expand All @@ -31,4 +38,11 @@ def _display_widgets(self):
self.lblTitle.grid(sticky=tk.E+tk.W+tk.N+tk.S, column=2, row=2, columnspan=3)
self.btnStrong.grid(sticky=tk.E+tk.W+tk.N+tk.S, column=2, row=4, rowspan=7)
self.btnWeak.grid(sticky=tk.E+tk.W+tk.N+tk.S, column=4, row=4, rowspan=7)
self.btnExit.grid(sticky=tk.E+tk.W+tk.N+tk.S, column=5, row=1)
self.btnExit.grid(sticky=tk.E+tk.W+tk.N+tk.S, column=5, row=1)

def join_ai(self, strong: bool):
self.master.network_thread = client_thread(self.master, in_queue=self.master.out_queue, out_queue=self.master.in_queue, player=self.master.player, ip='localhost')
if strong:
self.master.show(Join, opponent=player_type.ai_strong)
else:
self.master.show(Join, opponent=player_type.ai_weak)
Loading