def OnNewGame(self, e): # handicaps not yet implemented HANDICAP = 0 vals = self.MakeNewGameDialog() if not vals: return 0 try: self.ValidateNewGameValues(vals) except: self.log.write("error validating new game values") self.log.write(sys.exc_info()[0]) return 0 try: if vals['human1']: player1 = HumanGoPlayer(self.boardPanel) elif vals['comp1']: player1 = ComputerGoPlayer(self.log, "B", vals['comp1']) elif vals['pygo1']: player1 = PyGoPlayer("B") if vals['human2']: player2 = HumanGoPlayer(self.boardPanel) elif vals['comp2']: player2 = ComputerGoPlayer(self.log, "W", vals['comp2']) elif vals['pygo2']: player2 = PyGoPlayer("W") self.ref = GoReferee(player1, player2, self.boardPanel) self.ref.init_game(vals['size'], float(vals['ko']), HANDICAP) except GoError: self.log.write("error in new game creation\n") self.log.write(sys.exc_info()[0]) self.log.write(sys.exc_info()[1]) return 1
def administrate_game(self): if not self.network_player: return ['player1'] board = empty_board() referee = GoReferee([self.default_player, self.network_player]) out = referee.play_game() self.close_server() return out
def run_game(self): #Set Player 2 client_socket = self.create_server(self.IP, self.port) self.remote_player = RemoteContractProxy(connection=client_socket) player2_name = self.remote_player.register() self.remote_player.receive_stone(StoneEnum.WHITE) #Set Player 1 player1_name = self.local_player.register() self.local_player.receive_stone(StoneEnum.BLACK) # Pass to Referee to start game go_ref = GoReferee(player1=self.local_player, player2=self.remote_player) connected = True valid_response = True # Play game while not go_ref.game_over and connected and valid_response: try: go_ref.referee_game() except socket_error: go_ref.game_over = True print("{} disconnected.".format( go_ref.players[go_ref.current_player].name)) connected = False go_ref.winner = get_other_type(go_ref.current_player) break except PointException: go_ref.game_over = True valid_response = False print("{} played an invalid move.".format( go_ref.players[go_ref.current_player].name)) go_ref.winner = get_other_type(go_ref.current_player) break if go_ref.broke_rules: print("{} broke the rules.".format( go_ref.players[go_ref.broke_rules].name)) if connected: winner = go_ref.get_winners() elif not connected: winner = [self.local_player.name] else: raise Exception("GO ADMIN: Game ended unexpectedly.") return winner
def init_ref(): player1 = GoPlayer() player1.register("name1") player1.receive_stone(StoneEnum.BLACK) player2 = GoPlayer() player2.register("name2") player2.receive_stone(StoneEnum.WHITE) board = Board([[make_stone(None) for i in range(5)] for j in range(5)], 5) return GoReferee([board], [player1, player2])
def play_game(self, a, b): player1 = self.players[a] try: player1.receive_stone(StoneEnum.BLACK) except CloseConnectionException: self.update_score(b, a) return player2 = self.players[b] try: player2.receive_stone(StoneEnum.WHITE) except CloseConnectionException: self.update_score(a, b) return ref = GoReferee([player1, player2]) winners, _ = ref.play_game() winner = get_winner(winners) print("-- {} advances".format(winner)) if winner == self.names[a]: self.update_score(a, b) else: self.update_score(b, a)
def play_game(self, a, b): player1 = self.players[a] try: player1.receive_stone(StoneEnum.BLACK) except CloseConnectionException: self._update_score(b, a) self._update_score_cheater(a) self.cheaters.append(self.names[a]) self._replace_cheater(a) return player2 = self.players[b] try: player2.receive_stone(StoneEnum.WHITE) except CloseConnectionException: self._update_score(a, b) self._update_score_cheater(b) self.cheaters.append(self.names[b]) self._replace_cheater(b) self.players[a].end_game() return ref = GoReferee([player1, player2]) winners, was_cheater = ref.play_game() winner_name = get_winner(winners) winner_index = self._get_player_index(winner_name) loser_name = self._get_loser(winner_name, [player1, player2]) loser_index = self._get_player_index(loser_name) # update score first self._update_score(winner_index, loser_index) # check if cheater, edit points_arr and replace player if there was a cheater if was_cheater != None: self._update_score_cheater(loser_index) self.cheaters.append(loser_name) self._replace_cheater(loser_index)
class GoFrame(wxFrame): """ Main window for a go game""" def __init__(self, parent, id, title): self.dirname = "." wxFrame.__init__(self,parent,-4, title, \ pos=wxPoint(0,50), \ style=wxDEFAULT_FRAME_STYLE|wxNO_FULL_REPAINT_ON_RESIZE) self.log = MyLog(self, "PyGo Messages") self.log.Show(true) self.conf = Configuration(".pygo_conf", self.log) self.CreateStatusBar() self.MakeMenu() self.boardPanel = \ BoardPanel(self, -1, self.conf, self.log) self.SetClientSize(self.boardPanel.GetClientSize()) self.Show(true) def MakeMenu(self): gamemenu = wxMenu() gamemenu.Append(ID_NEW_GAME, "&New Game", "Start a new game") gamemenu.Append(ID_OPEN_SGF, "&Open SGF File", \ "Opens an SGF file for viewing/editing") gamemenu.Append(ID_VIEW_DEBUG, "&View Debug Info", \ "Open a window containing debugging information about the program") gamemenu.Append(ID_EXIT, "E&xit", "Terminate this program") helpmenu = wxMenu() helpmenu.Append(ID_ABOUT, "&About", "Information about this program") menuBar = wxMenuBar() menuBar.Append(gamemenu, "&File") menuBar.Append(helpmenu, "&Help") self.SetMenuBar(menuBar) EVT_MENU(self, ID_NEW_GAME, self.OnNewGame) EVT_MENU(self, ID_OPEN_SGF, self.OnOpen) EVT_MENU(self, ID_VIEW_DEBUG, self.OnViewDebug) EVT_MENU(self, ID_ABOUT, self.OnAbout) EVT_MENU(self, ID_EXIT, self.OnFileExit) EVT_CLOSE(self, self.OnExit) def OnViewDebug(self, e): if self.log.IsShown(): self.log.Show(false) else: self.log.Show(true) return 1 def MakeNewGameDialog(self): win = wxDialog(frame, -1, "New Game", size=wxSize(350, 200), style=wxCAPTION | wxSYSTEM_MENU | wxTHICK_FRAME) mainbox = wxBoxSizer(wxVERTICAL) playerbox = wxBoxSizer(wxHORIZONTAL) box_title = wxStaticBox(win, -1, "Black Player") box = wxStaticBoxSizer(box_title, wxVERTICAL) grid = wxFlexGridSizer(0, 1, 0, 0) human1 = wxRadioButton(win, ID_HUMAN1, "Human", style=wxRB_GROUP) pygo1 = wxRadioButton(win, ID_PYGO1, "PyGo Computer Opponent") comp1 = wxRadioButton(win, ID_COMP1, "Other Computer Opponent") comp1_cmd = wxTextCtrl(win, -1, "", size=(200, -1)) grid.AddWindow(human1, 0, wxALIGN_LEFT | wxLEFT | wxRIGHT | wxTOP, 5) grid.AddWindow(pygo1, 0, wxALIGN_LEFT | wxLEFT | wxRIGHT | wxTOP, 5) grid.AddWindow(comp1, 0, wxALIGN_LEFT | wxLEFT | wxRIGHT | wxTOP, 5) grid.AddWindow(comp1_cmd, 0, wxALIGN_LEFT | wxLEFT | wxRIGHT | wxTOP, 5) box.AddSizer(grid, 0, wxALIGN_LEFT | wxALL, 5) box2_title = wxStaticBox(win, -1, "White Player") box2 = wxStaticBoxSizer(box2_title, wxVERTICAL) grid2 = wxFlexGridSizer(0, 1, 0, 0) human2 = wxRadioButton(win, ID_HUMAN2, "Human", style=wxRB_GROUP) pygo2 = wxRadioButton(win, ID_PYGO2, "PyGo Computer Opponent") comp2 = wxRadioButton(win, ID_COMP2, "Other Computer Opponent") comp2_cmd = wxTextCtrl(win, -1, "", size=(200, -1)) grid2.AddWindow(human2, 0, wxALIGN_LEFT | wxLEFT | wxRIGHT | wxTOP, 5) grid2.AddWindow(pygo2, 0, wxALIGN_LEFT | wxLEFT | wxRIGHT | wxTOP, 5) grid2.AddWindow(comp2, 0, wxALIGN_LEFT | wxLEFT | wxRIGHT | wxTOP, 5) grid2.AddWindow(comp2_cmd, 0, wxALIGN_LEFT | wxLEFT | wxRIGHT | wxTOP, 5) box2.AddSizer(grid2, 0, wxALIGN_LEFT | wxALL, 5) playerbox.Add(box) playerbox.Add(box2) mainbox.Add(playerbox) grid3 = wxFlexGridSizer(1, 0, 0, 0) ko_label = wxStaticText(win, -1, "Ko: ") ko = wxTextCtrl(win, -1, "5.5", size=(30, -1)) bs_label = wxStaticText(win, -1, "Board Size: ") bsizes = ['19'] bs = wxChoice(win, 40, (80, 50), choices=bsizes) bs.SetStringSelection('19') handicap_label = wxStaticText(win, -1, "Handicap: ") handicap = wxTextCtrl(win, -1, "0", size=(30, -1)) grid3.AddWindow(ko_label, 0, wxALL, 5) grid3.AddWindow(ko, 0, wxALIGN_LEFT | wxALL, 5) grid3.AddWindow(handicap_label, 0, wxALL, 5) grid3.AddWindow(handicap, 0, wxALIGN_LEFT | wxALL, 5) grid3.AddWindow(bs_label, 0, wxALIGN_LEFT | wxALL, 5) grid3.AddWindow(bs, 0, wxALIGN_LEFT | wxALL, 5) grid4 = wxGridSizer(1, 0, 0, 0) ok = wxButton(win, wxID_OK, " OK ") cancel = wxButton(win, wxID_CANCEL, " Cancel ") grid4.AddWindow(ok, 0, wxALIGN_RIGHT | wxALL, 5) grid4.AddWindow(cancel, 0, wxALIGN_RIGHT | wxALL, 5) mainbox.Add(grid3) mainbox.Add(grid4) win.SetSizer(mainbox) win.SetAutoLayout(true) mainbox.Fit(win) response = win.ShowModal() if response == wxID_OK: values = { 'size': int(bs.GetStringSelection()), 'pygo1': pygo1.GetValue(), 'pygo2': pygo2.GetValue(), 'human1': human1.GetValue(), 'human2': human2.GetValue(), 'comp1': comp1.GetValue(), 'comp2': comp2.GetValue(), 'ko': ko.GetValue() } win.Destroy() return values else: win.Destroy() return 0 def ValidateNewGameValues(self, vals): bsize = vals['size'] if bsize != 19: msg = 'Sorry, board sizes other than 19 are not yet allowed' self.boardPanel.MakeDialog('sorry', msg) raise InvalidValueError, "invalid board size" valid_lets = '01234567890.' for digit in vals['ko']: if digit not in valid_lets: self.boardPanel.MakeDialog('sorry', "Invalid ko value") raise InvalidValueError, "invalid ko value" def OnNewGame(self, e): # handicaps not yet implemented HANDICAP = 0 vals = self.MakeNewGameDialog() if not vals: return 0 try: self.ValidateNewGameValues(vals) except: self.log.write("error validating new game values") self.log.write(sys.exc_info()[0]) return 0 try: if vals['human1']: player1 = HumanGoPlayer(self.boardPanel) elif vals['comp1']: player1 = ComputerGoPlayer(self.log, "B", vals['comp1']) elif vals['pygo1']: player1 = PyGoPlayer("B") if vals['human2']: player2 = HumanGoPlayer(self.boardPanel) elif vals['comp2']: player2 = ComputerGoPlayer(self.log, "W", vals['comp2']) elif vals['pygo2']: player2 = PyGoPlayer("W") self.ref = GoReferee(player1, player2, self.boardPanel) self.ref.init_game(vals['size'], float(vals['ko']), HANDICAP) except GoError: self.log.write("error in new game creation\n") self.log.write(sys.exc_info()[0]) self.log.write(sys.exc_info()[1]) return 1 def OnAbout(self, e): msg = "PyGo version .001\nBill Mill\nllimllib.f2o.org\[email protected]" d = wxMessageDialog(self, msg, "wxPyGo", wxOK) d.ShowModal() d.Destroy() def OnExit(self, e): sys.exit(1) def OnFileExit(self, e): self.Close() def OnOpen(self, e): pass """still not implemented
def init_referee(): go_ref = GoReferee(player1=GoPlayerBase("player1"), player2=GoPlayerBase("player2")) return go_ref
from constants import BLACK_STONE, WHITE_STONE from referee_formatter import format_pretty_json from go_referee import GoReferee from play_parser import format_input from go_player_base import GoPlayerBase def execute_input(play, referee): input_play = format_input(play) return referee.execute_move(input_play) if __name__ == "__main__": objs = json_parse_stdin() output = [] referee = GoReferee(player1=GoPlayerBase(objs[0]), player2=GoPlayerBase(objs[1])) output.append(BLACK_STONE) output.append(WHITE_STONE) for obj in objs[2:]: raw_out = execute_input(obj, referee) output.append(raw_out) if referee.game_over: if (not referee.winner_declared): output.append(referee.get_winners()) referee.winner_declared = True else: break
from stone import StoneEnum, make_stone from go_player_file import GoPlayerFile from go_player import GoPlayerContract from go_referee import GoReferee from go_ref_formatter import format_obj from referee_formatter import format_pretty_json if __name__ == "__main__": objs = json_parse_stdin() ## Initialize Stones, Points names, points = objs[:2], [parse_move(x) for x in objs[2:]] board = Board([[make_stone(None) for i in range(BOARD_DIM)] for j in range(BOARD_DIM)]) ## Initialize Players inner_player1 = GoPlayerFile(points[::2]) player1 = GoPlayerContract(inner_player1) player1.register(names[0]) player1.receive_stone(StoneEnum.BLACK) inner_player2 = GoPlayerFile(points[1::2]) player2 = GoPlayerContract(inner_player2) player2.register(names[1]) player2.receive_stone(StoneEnum.WHITE) ## Initialize Go Ref go_referee = GoReferee([player1, player2]) output = go_referee.play_game() raw_output = list(map(format_obj, output)) print(format_pretty_json(raw_output))
class GoFrame(wxFrame): """ Main window for a go game""" def __init__(self,parent,id,title): self.dirname="." wxFrame.__init__(self,parent,-4, title, \ pos=wxPoint(0,50), \ style=wxDEFAULT_FRAME_STYLE|wxNO_FULL_REPAINT_ON_RESIZE) self.log = MyLog(self, "PyGo Messages") self.log.Show(true) self.conf = Configuration(".pitch_conf", self.log) #self.CreateStatusBar() self.MakeMenu() self.boardPanel = \ BoardPanel(self, -1, self.conf, self.log) self.SetClientSize(self.boardPanel.GetClientSize()) self.Show(true) def MakeMenu(self): gamemenu=wxMenu() gamemenu.Append(ID_NEW_GAME, "&New Game", "Start a new game") gamemenu.Append(ID_VIEW_DEBUG, "&View Debug Info", \ "Open a window containing debugging information about the program") gamemenu.Append(ID_EXIT, "E&xit", "Terminate this program") helpmenu = wxMenu() helpmenu.Append(ID_ABOUT, "&About", "Information about this program") menuBar = wxMenuBar() menuBar.Append(gamemenu, "&File") menuBar.Append(helpmenu, "&Help") self.SetMenuBar(menuBar) EVT_MENU(self, ID_NEW_GAME, self.OnNewGame) EVT_MENU(self, ID_VIEW_DEBUG, self.OnViewDebug) EVT_MENU(self, ID_ABOUT, self.OnAbout) EVT_MENU(self, ID_EXIT, self.OnExit) def OnViewDebug(self, e): if self.log.IsShown(): self.log.Show(false) else: self.log.Show(true) return 1 def MakeNewGameDialog(self): win = wxDialog(frame, -1, "New Game", size=wxSize(350, 200), style = wxCAPTION | wxSYSTEM_MENU | wxTHICK_FRAME ) mainbox = wxBoxSizer(wxVERTICAL) playerbox = wxBoxSizer(wxHORIZONTAL) box_title = wxStaticBox(win, -1, "Black Player") box = wxStaticBoxSizer(box_title, wxVERTICAL) grid = wxFlexGridSizer(0, 1, 0, 0) human1 = wxRadioButton(win, ID_HUMAN1, "Human", style=wxRB_GROUP) pygo1 = wxRadioButton(win, ID_PYGO1, "PyGo Computer Opponent") comp1 = wxRadioButton(win, ID_COMP1, "Other Computer Opponent") comp1_cmd = wxTextCtrl(win, -1, "", size=(200,-1)) grid.AddWindow(human1, 0, wxALIGN_LEFT|wxLEFT|wxRIGHT|wxTOP, 5) grid.AddWindow(pygo1, 0, wxALIGN_LEFT|wxLEFT|wxRIGHT|wxTOP, 5) grid.AddWindow(comp1, 0, wxALIGN_LEFT|wxLEFT|wxRIGHT|wxTOP, 5) grid.AddWindow(comp1_cmd, 0, wxALIGN_LEFT|wxLEFT|wxRIGHT|wxTOP, 5) box.AddSizer(grid, 0, wxALIGN_LEFT|wxALL, 5) box2_title = wxStaticBox(win, -1, "White Player") box2 = wxStaticBoxSizer(box2_title, wxVERTICAL) grid2 = wxFlexGridSizer(0, 1, 0, 0) human2 = wxRadioButton(win, ID_HUMAN2, "Human", style=wxRB_GROUP) pygo2 = wxRadioButton(win, ID_PYGO2, "PyGo Computer Opponent") comp2 = wxRadioButton(win, ID_COMP2, "Other Computer Opponent") comp2_cmd = wxTextCtrl(win, -1, "", size=(200,-1)) grid2.AddWindow(human2, 0, wxALIGN_LEFT|wxLEFT|wxRIGHT|wxTOP, 5) grid2.AddWindow(pygo2, 0, wxALIGN_LEFT|wxLEFT|wxRIGHT|wxTOP, 5) grid2.AddWindow(comp2, 0, wxALIGN_LEFT|wxLEFT|wxRIGHT|wxTOP, 5) grid2.AddWindow(comp2_cmd, 0, wxALIGN_LEFT|wxLEFT|wxRIGHT|wxTOP, 5) box2.AddSizer(grid2, 0, wxALIGN_LEFT|wxALL, 5) playerbox.Add(box) playerbox.Add(box2) mainbox.Add(playerbox) grid3 = wxFlexGridSizer(1, 0, 0, 0) ko_label = wxStaticText(win, -1, "Ko: ") ko = wxTextCtrl(win, -1, "5.5", size=(30, -1)) bs_label = wxStaticText(win, -1, "Board Size: ") bsizes = ['19'] bs = wxChoice(win, 40, (80, 50), choices = bsizes) bs.SetStringSelection('19') handicap_label = wxStaticText(win, -1, "Handicap: ") handicap = wxTextCtrl(win, -1, "0", size=(30, -1)) grid3.AddWindow(ko_label, 0, wxALL, 5) grid3.AddWindow(ko, 0, wxALIGN_LEFT|wxALL, 5) grid3.AddWindow(handicap_label, 0, wxALL, 5) grid3.AddWindow(handicap, 0, wxALIGN_LEFT|wxALL, 5) grid3.AddWindow(bs_label, 0, wxALIGN_LEFT|wxALL, 5) grid3.AddWindow(bs, 0, wxALIGN_LEFT|wxALL, 5) grid4 = wxGridSizer(1, 0, 0, 0) ok = wxButton(win, wxID_OK, " OK ") cancel = wxButton(win, wxID_CANCEL, " Cancel ") grid4.AddWindow(ok, 0, wxALIGN_RIGHT|wxALL, 5) grid4.AddWindow(cancel, 0, wxALIGN_RIGHT|wxALL, 5) mainbox.Add(grid3) mainbox.Add(grid4) win.SetSizer(mainbox) win.SetAutoLayout(true) mainbox.Fit(win) response = win.ShowModal() if response == wxID_OK: values = { 'size': int(bs.GetStringSelection()), 'pygo1': pygo1.GetValue(), 'pygo2': pygo2.GetValue(), 'human1': human1.GetValue(), 'human2': human2.GetValue(), 'comp1': comp1.GetValue(), 'comp2': comp2.GetValue(), 'ko': ko.GetValue() } win.Destroy() return values else: win.Destroy() return 0 def ValidateNewGameValues(self, vals): bsize = vals['size'] if bsize != 19: msg = 'Sorry, board sizes other than 19 are not yet allowed' self.boardPanel.MakeDialog('sorry', msg) raise InvalidValueError, "invalid board size" valid_lets = '01234567890.' for digit in vals['ko']: if digit not in valid_lets: self.boardPanel.MakeDialog('sorry', "Invalid ko value") raise InvalidValueError, "invalid ko value" def OnNewGame(self, e): # handicaps not yet implemented HANDICAP = 0 vals = self.MakeNewGameDialog() if not vals: return 0 try: self.ValidateNewGameValues(vals) except: self.log.write("error validating new game values") self.log.write(sys.exc_info()[0]) return 0 try: if vals['human1']: player1 = HumanGoPlayer(self.boardPanel) elif vals['comp1']: player1 = ComputerGoPlayer(self.log, "B", vals['comp1']) elif vals['pygo1']: player1 = PyGoPlayer("B") if vals['human2']: player2 = HumanGoPlayer(self.boardPanel) elif vals['comp2']: player2 = ComputerGoPlayer(self.log, "W", vals['comp2']) elif vals['pygo2']: player2 = PyGoPlayer("W") self.ref = GoReferee(player1, player2, self.boardPanel) self.ref.init_game(vals['size'], float(vals['ko']), HANDICAP) except GoError: self.log.write("error in new game creation\n") self.log.write(sys.exc_info()[0]) self.log.write(sys.exc_info()[1]) return 1 def OnAbout(self, e): msg = "PyGo version .001\nBill Mill\nllimllib.f2o.org\[email protected]" d = wxMessageDialog(self, msg, "wxPyGo", wxOK) d.ShowModal() d.Destroy() def OnExit(self, e): self.Close(true)
def run_game(self, player1, player2): go_ref = GoReferee(player1=player1, player2=player2) connected = True valid_response = True cheater = None # Distribute Stones Before Game player1_received = False try: player1.receive_stone(StoneEnum.BLACK) player1_received = True except: go_ref.winner = StoneEnum.WHITE cheater = player1.name connected = False cheater = player1.name print("Unsuccessful receive stone for {}.".format(cheater)) go_ref.winner = StoneEnum.WHITE if player1_received: try: player2.receive_stone(StoneEnum.WHITE) except: go_ref.winner = StoneEnum.BLACK cheater = player2.name connected = False cheater = player2.name print("Unsuccessful receive stone for {}.".format(cheater)) go_ref.winner = StoneEnum.BLACK # Referee game and check for cheating condition # - Game over via breaking the rules. # - Invalid responses during game. # - Disconnecting during game. while not go_ref.game_over and connected and valid_response: try: go_ref.referee_game() except OSError: go_ref.game_over = True connected = False cheater = go_ref.players[go_ref.current_player].name print("Player {} disconnected.".format(cheater)) go_ref.winner = get_other_type(go_ref.current_player) break except PointException: go_ref.game_over = True valid_response = False cheater = go_ref.players[go_ref.current_player].name print("Invalid response from player {}.".format(cheater)) go_ref.winner = get_other_type(go_ref.current_player) break if go_ref.broke_rules: cheater = go_ref.players[go_ref.broke_rules].name print("Player {} broke the rules.".format(cheater)) # Validate Game Over for both players if connected: #(go_ref.game_over and connected and valid_response) or not valid_response: if not player1.game_over([GAME_OVER]): cheater = player1.name print("Did not receive game_over from Player {}".format( player1.name)) go_ref.winner = StoneEnum.WHITE elif not player2.game_over([GAME_OVER]): cheater = player2.name print("Did not receive game_over from Player {}".format( player2.name)) go_ref.winner = StoneEnum.BLACK winner = go_ref.get_winners() # Randomly break ties if two winners if len(winner) == 1: return winner[0], cheater else: rand_idx = random.randint(0, 1) return winner[rand_idx], cheater