def test_get_variable(self):
     notactoe = NoTacToe()
     comp = ComputerPlayer(notactoe)
     notactoe.board_list[0] = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
     self.assertEqual('c', comp.get_monoid(0))
     notactoe.board_list[0] = ['X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X']
     self.assertEqual('1', comp.get_monoid(0))
Exemple #2
0
    def __init__(self, main):
        self.cp = ComputerPlayer()
        self.main = main
        self.analpan = None
        self.CurrentMoveDepth = 0
        self.ActiveBoard = None
        self.ActiveEvalPar = None
        self.ActiveEvalGame = None
        self.SearchDepth = 0

        return
Exemple #3
0
    def __init__(self, main, panel):
        self.play_process_state = StringVar(
        )  # proces-state to share information between the various events
        self.main = main
        self.panel = panel
        self.root = self.panel.root
        self.mg = MoveGenerator()
        self.cp = ComputerPlayer()
        self.get_move_from_book = False
        self.EvalReceivedProc = None
        self.EvalReceivedContinueProc = None
        self.ContinuationMessage = ''
        self.ProcesFixedDepth = None
        self.ContinuePlaying = None
        self.RescueProcess = None
        self.EngineID = None
        self.AnalyzeGameMoveReceived = None
        self.EndOfGameContinue = None
        self.ClockIsTicking = False
        self.CurrentTimeToGo = 0.0
        self.RemainingMinutes = 0
        self.RemainingSeconds = 0
        self.MiliSecondsRemaining = 1000
        self.NumberOfMovesToGo = 0
        self.RemainingEnigineTimeAvailable = self.main.TotalEngineTime
        file = open('/home/feike/Horizon/Opening Books/OpeningBook.pickle',
                    'r')
        self.OpeningBook = pickle.load(file)
        file.close()

        return
Exemple #4
0
 def __init__(self):
     # Creates a new instance of NoTacToe (the game logic class)
     self.notactoe = NoTacToe()
     self.comp_player = ComputerPlayer(self.notactoe)
     self.notactoe.reset_game()
     # root is the base window that holds the frames
     self.root = Tk()
     # widgets is a dict used to store all the member variable widgets in the program
     self.widgets = {}
     # widgets['canvas'] is the dict within a dict that store all the Canvas member variables
     self.canvases = {}
     self.canvas_labels = {}
     self.game_in_progress = True
     self.notactoe.set_num_active_boards(3)
     title_frame = Frame(self.root)
     title_frame.grid(row=0, columnspan=2)
     Label(title_frame, text='Time to play NoTacToe!').grid(row=0)
     Label(title_frame, text='Rules:\n(1) Both players play X.\n(2) Once a board has three-in-a-row it dies.\n'
           '(3) The player who kills the last board loses.').grid(row=1, pady=10)
     self.widgets['player_label'] = Label(title_frame, text='Player 1\'s turn', font='bold')
     self.widgets['player_label'].grid(row=2)
     self.canvas_window()
     self.control_window()
     self.bottom_window()
     for i in range(self.MAX_CANVAS):
         self.update_monoid_labels(i)
         self.canvases[i].config(bg="LIGHT GRAY")
Exemple #5
0
 def __init__(self, main, panel):
     self.play_process_state=StringVar()                         # proces-state to share information between the various events
     self.main = main
     self.panel = panel
     self.root = self.panel.root
     self.mg = MoveGenerator()
     self.cp = ComputerPlayer()
     return
Exemple #6
0
    def runLocalGame(self, user):
        self.setGame(CheckersBoard())

        aiDifficulty = self.view.displayAIDifficultyForm()

        computerPlayer = ComputerPlayer(playerID=2, diff=aiDifficulty)
        computerPlayer.setHeuristic(self.getGame())
        computerPlayer.initializeAIStrategy()

        self.game.initializeGameBoard(HumanPlayer(1), computerPlayer)
        self.game.notifyObservers()

        self.view.displayBoard(self.game.getReadOnlyState())

        while (self.game.getWinner() is None):
            for player in self.game.observers:
                pieceID, moveType = self.view.getPlayerMove(
                    player.__class__.__name__)
                player.makeMove(self.game, pieceID, moveType)

                self.view.displayBoard(self.game.getReadOnlyState())

        if (type(self.game.getWinner()) == HumanPlayer):
            self.dbProxy.executeUpdateQuery('wins', user, 1)
        else:
            self.dbProxy.executeUpdateQuery('losses', user, 1)

        self.dbProxy.executeUpdateQuery('playtime', user,
                                        self.game.getTimerTotal())
Exemple #7
0
 def __init__(self, main, panel):
     self.play_process_state=StringVar()                         # proces-state to share information between the various events
     self.main = main
     self.panel = panel
     self.root = self.panel.root
     self.mg = MoveGenerator()
     self.cp = ComputerPlayer()
     self.get_move_from_book = False
     self.EvalReceivedProc = None
     self.EvalReceivedContinueProc = None
     self.ContinuationMessage = ''
     self.ProcesFixedDepth = None
     return
Exemple #8
0
def rungame():
    """
    Random AF
    :return:
    """
    maxturns = 300

    playme = g.Game(4)
    playme.loadtiles()
    plyrz = []
    for plnum in range(4):
        plyrz.append(cp.ComputerPlayer(playme, playme.playerboard[plnum]))
    playme.show()
    cont = True
    firstplayer = 0
    turnz = 0
    retval = 0
    # while cont:
    while cont and turnz < maxturns:  # real games rarely go past 5
        for idxnum in range(4):
            plnum = (firstplayer + idxnum) % 4
            if playme.turnover(): #   dispnum == 9:
                # cont = False
                for plnum in range(4):
                    playme.playerboard[plnum].movescore(playme.box)
                    if playme.playerboard[plnum].firstplayer:
                        firstplayer = plnum
                        playme.playerboard[plnum].firstplayer = False
                    if playme.playerboard[plnum].finalboard.horizrowcomplete():
                        cont = False
                if cont:
                    print("    next turn")
                    if not playme.loadtiles():
                        cont = False
                        retval = 1
                        break
                    playme.show()
                break
            print("Player " + str(plnum+1) + " turn:")
            plyrz[plnum].taketurn()
            playme.show()
            turnz += 1
    print("Final scoring here")
    for idxnum in range(4):
        playme.playerboard[idxnum].finalscore()
    playme.show()
    if turnz == maxturns:
        retval = 1
    return (retval)
Exemple #9
0
class DraughtAnalyze:
    def __init__(self, main):
        self.cp = ComputerPlayer()
        self.main = main
        self.analpan = None
        self.CurrentMoveDepth = 0
        self.ActiveBoard = None
        self.ActiveEvalPar = None
        self.ActiveEvalGame = None
        self.SearchDepth = 0

        return

    def anal_pos_mode_clicked(self, wanted_depth):
        self.Game_1 = GameRecord(self.main, None, None)
        self.Game_2 = GameRecord(self.main, None, None)
        self.Game_3 = GameRecord(self.main, None, None)
        game = self.main.ActiveGame
        self.main.play.startup_engine()
        game.CurrentPosition.ColorOnMove = self.main.panel.current_color_on_move.get(
        )
        self.analpan = DraughtAnalyzePanel(self)
        self.analpan.top.title("Analyze (depth = " +
                               str(wanted_depth).zfill(2) + ' )')
        self.CurrentMoveDepth = wanted_depth
        self.SearchDepth = self.CurrentMoveDepth
        self.analpan.board3.display(game.CurrentPosition)
        self.main.play.ProcesFixedDepth = self.proces_fixed_depth_move

        self.main.play.engine.send_analyse_position(game, wanted_depth)
        # obtained moves in "receive all moves"
        return

    def receive_all_moves(self, msg):
        #receive all moves (with move-value) in the given configuration
        #print "python: ", msg
        cnt = (len(msg) - 1) / 14
        #print cnt, len(msg)
        self.all_moves = []
        for j in range(0, cnt):
            k = j * 14 + 1
            next_move = HalfPlyRecord()
            next_move.Start = int(msg[k:k + 2])
            next_move.op = msg[k + 2:k + 3]
            next_move.Stop = int(msg[k + 3:k + 5])
            next_move.MoveValue = int(msg[k + 7:k + 13])
            #print next_move
            self.all_moves.append(next_move)

        self.all_moves.sort(reverse=True)
        # moves are sorted in decreasing order by MoveValue
        self.analpan.all_moves.delete(first=0,
                                      last=self.analpan.all_moves.size() - 1)
        for j in range(0, cnt):
            self.analpan.all_moves.insert(END, str(self.all_moves[j].Start).zfill(2) + self.all_moves[j].op + str(self.all_moves[j].Stop).zfill(2) +\
            ' (' + str(self.all_moves[j].MoveValue).rjust(6) + ')')
        return

    def show1_pressed(self):
        self.ActiveBoard = self.analpan.board1
        self.ActiveEvalPar = self.analpan.eval1_par
        self.ActiveEvalGame = self.Game_1
        self.Show_continue()
        return

    def show2_pressed(self):
        self.ActiveBoard = self.analpan.board2
        self.ActiveEvalPar = self.analpan.eval2_par
        self.ActiveEvalGame = self.Game_1
        self.Show_continue()
        return

    def Show_continue(self):
        selection = self.analpan.all_moves.curselection()
        if selection == ():
            self.analpan.main_variant.delete(1.0, END)
            self.analpan.main_variant.insert(END, "please select a move first")
            return
        self.CurrentMoveDepth = self.SearchDepth
        self.MaxColor = self.analpan.board3.board_position.ColorOnMove
        self.ActiveEvalGame.clear()
        self.ActiveEvalGame.set_begin_position_ext(
            self.analpan.board3.board_position)
        move = self.all_moves[int(selection[0])]
        self.ActiveEvalGame.do_move(move)
        self.ActiveBoard.display(self.ActiveEvalGame.CurrentPosition)
        self.analpan.main_variant.delete(1.0, END)
        if self.MaxColor == dc.WHITE_ON_MOVE:
            self.analpan.main_variant.insert(END, \
                    str(move.Start).zfill(2) + move.op + str(move.Stop).zfill(2) + '(' + str(move.MoveValue).rjust(6) + ') ')
        else:
            self.analpan.main_variant.insert(END, '              ' + \
                    str(move.Start).zfill(2) + move.op + str(move.Stop).zfill(2) + '(' + str(move.MoveValue).rjust(6) + ')\n')
        if self.all_moves[int(selection[0])].op == '-':
            self.CurrentMoveDepth = self.CurrentMoveDepth - 1
        value = self.all_moves[int(selection[0])].MoveValue
        if self.CurrentMoveDepth > 0:
            self.main.play.engine.send_get_fixed_depth_move(self.ActiveEvalGame , self.CurrentMoveDepth, \
                                                                                          value, self.analpan.get_orig_color(), False,True)
        return

    def proces_fixed_depth_move(self, s):
        game = self.ActiveEvalGame
        if s[1] == 'x': return
        start = int(s[1:3])
        stop = int(s[3:5])
        value = int(s[5:11])
        print "python(1): ", start, stop, value
        valid, move = game.start_stop_to_move_record(start, stop)
        if valid == False: return
        print "python(2)", move.Start, move.Stop
        #we have to decide whether we should stop, is different for MAX side and MIN side
        if self.MaxColor == self.ActiveBoard.board_position.ColorOnMove:
            # MAX node
            if self.CurrentMoveDepth < 0 and move.op == '-':
                #we have collected the main variant, now get the evaluation
                self.main.play.engine.send_evaluate_position_2(game, False)
                return  # the end of the row
        else:
            if self.CurrentMoveDepth <= 0 and move.op == '-':
                #we have collected the main variant, now get the evaluation
                self.main.play.engine.send_evaluate_position_2(game, False)
                return  # the end of the row

        game.do_move(move, True)
        game.write_moves()
        #        self.analpan.main_variant.insert(END, str(move.Start).zfill(2) + move.op + str(move.Stop).zfill(2) + '(' + str(value).rjust(6) + ')')
        #        if self.ActiveBoard.board_position.ColorOnMove == dc.WHITE_ON_MOVE:
        #            self.analpan.main_variant.insert(END, ' ')
        #        else:
        #            self.analpan.main_variant.insert(END, '\n')
        #        self.ActiveBoard.display(self.ActiveEvalGame.CurrentPosition)
        #        if move.op == '-':
        #            self.CurrentMoveDepth = self.CurrentMoveDepth - 1
        #        self.main.play.engine.send_get_fixed_depth_move(self.ActiveEvalGame , self.CurrentMoveDepth, \
        #                                                                                          value, self.analpan.get_orig_color(), False)

        return

    def eval_par_received(self, msg):
        eval = self.ActiveEvalPar.display(msg)
        return

    def anal_pos_mode_clicked_old(self, wanted_depth):
        game = self.main.ActiveGame
        self.main.play.startup_engine()
        game.CurrentPosition.ColorOnMove = self.main.panel.current_color_on_move.get(
        )
        move = None  #game.is_valid_move(game.get_half_ply_pointer_record())
        if move == None:
            self.main.play.engine.send_analyse_position(game, wanted_depth)
        else:
            self.main.play.engine.send_analyse_move(game, move, wanted_depth)
        return

    def anal_time_mode_clicked(self):
        self.main.read.get_pdn_file(True)  #open the time test pdn file
        self.main.play.startup_engine()
        game = self.main.ActiveGame
        self.main.play.engine.send_init_game(game)
        game.HalfPlyPointer = 14  # was 80
        self.send_next_move_for_timing()
        return

    def send_next_move_for_timing(self):
        game = self.main.ActiveGame
        game.HalfPlyPointer += 6
        if game.HalfPlyPointer <= 21:  #game.get_half_ply_length():
            game.build_till_pointer()
            game.refresh_display()
            #print "python -- start next move"
            self.main.play.engine.send_analyse_timing(game)
        else:
            #print "python -- start final report"
            self.main.play.engine.send_final_report()
        return

    def final_report_ready(self):
        #print "python -- final report ready"
        self.main.panel.setup_mode()
        self.main.play.end_proc()
        return

    def eval_mode_clicked(self, game, display=True):
        self.main.play.startup_engine()
        game.CurrentPosition.ColorOnMove = self.main.panel.current_color_on_move.get(
        )
        self.main.play.engine.send_evaluate_position(game, display)
        self.main.panel.setup_mode()
        return

    def init_board(self):
        self.setup.setup_board()
        self.bord.ColorOnMove = dc.WHITE_ON_MOVE
        self.cp.c_init_tree()
        return

    def get_next_move(self, game, pnt):
        if self.bord.is_color_white():
            start = game.Moves[pnt].White_start
            stop = game.Moves[pnt].White_stop
            token = game.Moves[pnt].White_op
        else:
            start = game.Moves[pnt].Black_start
            stop = game.Moves[pnt].Black_stop
            token = game.Moves[pnt].Black_op
        ply = game.Moves[pnt].Ply_nr
        if start == '' or stop == '': return "empty start of stop"
        ml = self.mg.valid_move(
            self.bord)  # get all valid moves, maybe we have a capture.
        if ml == []: return "empty list"
        for move in ml:
            if move.start == start and move.stop == stop:
                break
        if not (move.start == start and move.stop == stop):
            return "mismatch"
        # no invalid neither impossible moves
        # print  start, stop, chr(ord('(')+start) + chr(ord('(')+stop)
        return chr(ord('(') + start) + chr(ord('(') + stop)

    def get_Incremental_board_position(
            self, game, ply):  # for testing only, must be called incremental
        ok = self.setup.exec_one_half_ply(game, ply)  # white move
        if not ok: return
        ok = self.setup.exec_one_half_ply(game, ply)  # black move
        if not ok: return
        return
Exemple #10
0
class DraughtAnalyze:
    def __init__(self, main):
        self.cp = ComputerPlayer()
        self.main = main
        self.analpan = None
        self.CurrentMoveDepth = 0
        self.ActiveBoard = None
        self.ActiveEvalPar = None
        self.ActiveEvalGame = None
        self.SearchDepth = 0

        return

    def anal_pos_mode_clicked(self, wanted_depth):
        game = self.main.ActiveGame
        self.main.play.startup_engine()
        game.CurrentPosition.ColorOnMove = self.main.panel.current_color_on_move.get()
        self.analpan = DraughtAnalyzePanel(self)
        self.analpan.top.title("Analyze (depth = " + str(wanted_depth).zfill(2) + ' )' )
        self.Game_1 = GameRecord(self.main,  self.analpan.board1, self.analpan.board1)
        self.Game_2 = GameRecord(self.main,  self.analpan.board2, self.analpan.board2)
        self.Game_3 = GameRecord(self.main,  self.analpan.board3, self.analpan.board3)
        self.CurrentMoveDepth = wanted_depth
        self.SearchDepth = self.CurrentMoveDepth
        self.analpan.board3.display(game.CurrentPosition)
        #self.main.play.ProcesFixedDepth = self.proces_fixed_depth_move
        self.all_moves = self.main.mg.valid_move(game)
        self.main.play.engine.send_analyse_position(game, wanted_depth)
        # obtained moves in "receive all moves"
        return

    def receive_all_moves(self, msg):
        #receive all moves (with move-value) in the given configuration
        #print "python: ", msg
        cnt = (len(msg) - 1)/(14 + 51)
        #print cnt, len(msg)
        #self.all_moves = []
        for j in range(0, cnt):
            k=j*65+1
            Start = int(msg[k:k+2])
            Stop = int(msg[k+3:k+5])
            MoveValue = int( msg[k+7:k+13])
            stand = msg[k+14:k+65]
            #print msg[k+14:k+65]
            self.InsertValue(Start,  Stop,  MoveValue, stand)
        self.all_moves.sort(reverse=True)
        # moves are sorted in decreasing order by MoveValue
        self.analpan.all_moves.delete(first=0, last=self.analpan.all_moves.size()-1)
        for j in range(0, cnt):
            self.analpan.all_moves.insert(END, str(self.all_moves[j].Start).zfill(2) + self.all_moves[j].op + str(self.all_moves[j].Stop).zfill(2) +\
            ' (' + str(self.all_moves[j].MoveValue).rjust(6) + ')')
        return

    def InsertValue(self,  start,  stop,  value, stand):
        for move in self.all_moves:
            if move.Start == start and move.Stop == stop:
                move.MoveValue = value
                move.stand = stand
        return

    def show1_pressed(self):
        self.ActiveBoard = self.analpan.board1
        self.ActiveEvalPar = self.analpan.eval1_par
        self.ActiveEvalGame = self.Game_1
        self.Show_continue()
        return

    def show2_pressed(self):
        self.ActiveBoard = self.analpan.board2
        self.ActiveEvalPar = self.analpan.eval2_par
        self.ActiveEvalGame = self.Game_2
        self.Show_continue()
        return

    def Show_continue(self):
        #print "Show_continue"
        selection = self.analpan.all_moves.curselection()
        if selection==():
            self.analpan.main_variant.delete(1.0, END)
            self.analpan.main_variant.insert(END, "please select a move first")
            return
        stand = self.all_moves[int(selection[0])].stand
        #print "stand is: ", stand
        self.ActiveEvalGame.set_50_square_position(stand)
        self.ActiveEvalGame.refresh_display()
        self.main.play.engine.send_evaluate_position_2(self.ActiveEvalGame, False)
        return


##    def proces_fixed_depth_move(self, s):
##        game = self.ActiveEvalGame
##        if s[1] == 'x': return
##        start = int(s[1:3])
##        stop = int(s[3:5])
##        value = int(s[5:11])
##        print "python(1): ", start, stop, value
##        valid, move = game.start_stop_to_move_record(start, stop)
##        if valid == False: return
##        print "python(2)", move.Start, move.Stop
##        #we have to decide whether we should stop, is different for MAX side and MIN side
##        if self.MaxColor == self.ActiveBoard.board_position.ColorOnMove:
##            # MAX node
##            if self.CurrentMoveDepth <= 0 and move.op == '-':
##                #we have collected the main variant, now get the evaluation
##                self.main.play.engine.send_evaluate_position_2(game, False)
##                return # the end of the row
##        else:
##            if self.CurrentMoveDepth <= 0 and move.op == '-':
##                #we have collected the main variant, now get the evaluation
##                self.main.play.engine.send_evaluate_position_2(game, False)
##                return # the end of the row
##
##        game.do_move(move,True)
##        self.analpan.main_variant.insert(END, str(move.Start).zfill(2) + move.op + str(move.Stop).zfill(2) + '(' + str(value).rjust(6) + ')')
##        if self.ActiveBoard.board_position.ColorOnMove == dc.WHITE_ON_MOVE:
##            self.analpan.main_variant.insert(END, ' ')
##        else:
##            self.analpan.main_variant.insert(END, '\n')
##        self.ActiveBoard.display(self.ActiveEvalGame.CurrentPosition)
##        if move.op == '-':
##            self.CurrentMoveDepth = self.CurrentMoveDepth - 1
##        self.main.play.engine.send_get_fixed_depth_move(self.ActiveEvalGame , self.CurrentMoveDepth, \
##                                                                                          value, self.analpan.get_orig_color(), False)
##
##        return

    def eval_par_received(self, msg):
        eval = self.ActiveEvalPar.display(msg)
        return



    def anal_pos_mode_clicked_old(self, wanted_depth):
        game = self.main.ActiveGame
        self.main.play.startup_engine()
        game.CurrentPosition.ColorOnMove = self.main.panel.current_color_on_move.get()
        move = None #game.is_valid_move(game.get_half_ply_pointer_record())
        if move == None:
            self.main.play.engine.send_analyse_position(game, wanted_depth)
        else:
            self.main.play.engine.send_analyse_move(game, move, wanted_depth)
        return

    def anal_time_mode_clicked(self):
        self.main.read.get_pdn_file(True) #open the time test pdn file
        self.main.play.startup_engine()
        game = self.main.ActiveGame
        self.main.play.engine.send_init_game(game)
        self.NextHalfPly = 56
        self.ShowTimingOfThisPostion(14)
        return

    def ShowTimingOfThisPostion(self,  half_ply):
        game = self.main.ActiveGame
        game.HalfPlyPointer = half_ply
        game.build_till_pointer()
        game.refresh_display()
        self.main.play.engine.send_analyse_timing(game)
        return

    def send_next_move_for_timing(self):
        self.main.play.engine.send_final_report()
        if self.NextHalfPly == 56:
            self.NextHalfPly = 76
        elif self.NextHalfPly == 76:
            self.NextHalfPly = 96
        else:
            return
        self.ShowTimingOfThisPostion(self.NextHalfPly)
        return

    def final_report_ready(self):
        #print "python -- final report ready"
        self.main.play.engine.send_final_report()
        return

    def eval_mode_clicked(self, game, display=True):
        self.main.play.startup_engine()
        game.CurrentPosition.ColorOnMove = self.main.panel.current_color_on_move.get()
        #self.main.play.engine.send_get_fixed_depth_move(game , 10, 0,  'W', False,True)
        self.main.play.engine.send_evaluate_position(game, display)
        self.main.panel.setup_mode()
        return

    def init_board(self):
        self.setup.setup_board()
        self.bord.ColorOnMove = dc.WHITE_ON_MOVE
        self.cp.c_init_tree()
        return

    def get_next_move(self, game, pnt):
        if self.bord.is_color_white():
            start = game.Moves[pnt].White_start
            stop = game.Moves[pnt].White_stop
            token = game.Moves[pnt].White_op
        else:
            start = game.Moves[pnt].Black_start
            stop = game.Moves[pnt].Black_stop
            token = game.Moves[pnt].Black_op
        ply = game.Moves[pnt].Ply_nr
        if start == '' or stop == '': return "empty start of stop"
        ml = self.mg.valid_move(self.bord)                                     # get all valid moves, maybe we have a capture.
        if ml == []: return "empty list"
        for move in ml:
            if move.start == start and move.stop == stop:
                break
        if not (move.start == start and move.stop == stop):
            return "mismatch"
        # no invalid neither impossible moves
        # print  start, stop, chr(ord('(')+start) + chr(ord('(')+stop)
        return chr(ord('(')+start) + chr(ord('(')+stop)

    def get_Incremental_board_position(self, game, ply):                  # for testing only, must be called incremental
        ok = self.setup.exec_one_half_ply(game, ply)                          # white move
        if not ok: return
        ok = self.setup.exec_one_half_ply(game, ply)                          # black move
        if not ok: return
        return

    def analyze_game(self):    # called from LiveDraughts
      game = self.main.ActiveGame
      game.HalfPlyPointer = 0
      while True:
        move = game.get_half_ply_pointer_record()
        if not move:
          if game.file_name_chart and game.url_chart:
            #self.main.root.after(500, self.main.live.process_analyze_queue) #blind
            self.main.root.after(500, self.main.live.next_polling) #tournament
          else:
            self.main.chart.create_chart("chart.png")
          return # we are done
        #print move.Start, move.Stop
        if move.Comment == '':
          break
        game.HalfPlyPointer += 1
      # first not analysed move
      while True:
        if game.HalfPlyPointer >= 6: break # get calculated best move value
        move.Comment = '0: None '
        game.HalfPlyPointer += 1
        move = game.get_half_ply_pointer_record()
        if not move:
          if game.file_name_pdn:
            self.main.save.file_save_game_clicked(game.file_name_pdn)
          if game.file_name_chart:
            self.main.chart.create_chart(game.file_name_chart)
          else:
            self.main.chart.create_chart("chart.png")
          if game.file_name_chart and game.url_chart:
            self.main.play.beam_up_chart(game.file_name_chart, game.url_chart)
            #self.main.root.after(500, self.main.live.process_analyze_queue) #blind
            self.main.root.after(500, self.main.live.next_polling) #tournament
          return # we are done

      #self.main.play.beam_up_chart('/home/feike/Horizon/LiveDraughts/wait.png')
      game.HalfPlyPointer += 1 # has to point to the next move
      print "start analysing with half ply =", game.HalfPlyPointer
      if game.build_till_pointer()== False:
        print "build till pointer is False"
        if game.file_name_pdn:
          self.main.save.file_save_game_clicked(game.file_name_pdn)
        if game.file_name_chart:
          self.main.chart.create_chart_with_illegal_move(game.file_name_chart)
        #self.main.root.after(500, self.main.live.process_analyze_queue) #blind
        self.main.root.after(500, self.main.live.next_polling) #tournament
        return
      game.refresh_display()
      self.main.play.startup_engine()
      self.main.play.engine.send_get_next_move(game)
      return
    def display(self):
        """ """
        screen, background, clock = self._facade.initialise_screen("battleships", "BATTLESHIPS.png", self._screen_size)

        board = Board.Board(screen, self._dal)

        p1_allocation = Allocation.Allocation(1)
        p2_allocation = Allocation.Allocation(2)

        Tracker = StopWatch.TrackTime()
        

        player1 = Player.Player(board, p2_allocation, self._dal, screen)
        if self._dal.is_player2_cpu() == False:
            player2 = Player.Player(board, p1_allocation, self._dal, screen)
        else: 
            player2 = CPU.ComputerPlayer(board, p1_allocation, self._dal, screen)


        current_player = player1

        Tracker.start_timer_1()   ## Start tracking the time taken by player 

        ################################################
        # This is the main gaming loop for this screen
        ################################################
        while True:

            #cap the framerate to 30 frames per second
            clock.tick(30)

            # this loop will walk through a list of captured events
            # and react according to the specific ones we are interested in.
            events = pygame.event.get()

            for event in events:
                if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
                    return Navigate.SPLASHSCREEN
                
                ## Get the current mouse positional information
                pos = pygame.mouse.get_pos()
            
            screen.blit(background, (0, 0))


            if p1_allocation.are_all_ships_destroyed() == False and p2_allocation.are_all_ships_destroyed() == False and self.checked_out == False:
                current_player.take_turn(pos, event)
                if current_player.swap_player == True:
                    current_player.swap_player = False
                    current_player.reset_shot_taken()
                    if current_player.is_player_1 == True:
                        Tracker.stop_timer_1()
                        Tracker.start_timer_2()
                        current_player = player2
                    else:
                        Tracker.stop_timer_2()
                        Tracker.start_timer_1()
                        current_player = player1
            else:
                self.checked_out == True
                t1 = Tracker.get_overall_time_for_timer_1()
                t2 = Tracker.get_overall_time_for_timer_2()
                shots1 = p1_allocation.get_number_of_shots_taken
                shots2 = p2_allocation.get_number_of_shots_taken

                if p1_allocation.are_all_ships_destroyed() == True:  ### then player 2 won
                    self._facade.DrawStringArchivoNarrow(screen,"GAME OVER PLAYER 2 WINS", 400, 438,self.GREEN, False, 77 )
                    self._dal.add_stat_to_player(2,t2, str(shots2), "true")
                    self._dal.add_stat_to_player(1,t1, str(shots1), "false")
                else: ## player 1 won
                    self._facade.DrawStringArchivoNarrow(screen,"GAME OVER PLAYER 1 WINS", 400, 438,self.GREEN, False, 77 )
                    self._dal.add_stat_to_player(1,t1, str(shots1), "true")
                    self._dal.add_stat_to_player(2,t2, str(shots2), "false")

         

            
            # the next statement is important otherwise carriage returns will remain and continue to be processed in the processForm           

            pygame.display.update()
         
            
            pygame.display.flip()
Exemple #12
0
                 bord: Board):
        self.game_logic = game_logic
        self.players = players
        self.bord = bord
        # itertools has a nice way to implement next player:
        # import itertools
        # self.players = itertools.cycle(players)

    def next_player(self) -> PlayerBase:
        # return next(self.players)
        the_game.step_counter += 1
        return self.players[the_game.step_counter % 2]

    def start_game(self):
        while not self.game_logic.is_win():
            current_player = self.next_player()
            print(f"{current_player.name} playing ... ")
            self.bord.print_board()
            step = current_player.next_step()
            self.bord.set_step(current_player.symbol, step)


game_logic = GameLogic()
board = Board(3)
hp = HumanPlayer("Amiel", 'X', board)
cp = ComputerPlayer("My Computer", '0', board)
players = [hp, cp]

the_game = TheGame(game_logic, players, board)
the_game.start_game()
Exemple #13
0
class NoTacToeUI:

    # Constants for set values hard coded in the program
    MAX_CANVAS = 3
    TAG_TUPLE = ('one', 'two', 'three')
    TAG_DICT = {'one': 1, 'two': 2, 'three': 3}
    BOARD_NUMBER_TUPLE = (3, 1, 2, 3)
    PLAYER_MODE = 0
    COMPUTER_MODE = 1

    def __init__(self):
        # Creates a new instance of NoTacToe (the game logic class)
        self.notactoe = NoTacToe()
        self.comp_player = ComputerPlayer(self.notactoe)
        self.notactoe.reset_game()
        # root is the base window that holds the frames
        self.root = Tk()
        # widgets is a dict used to store all the member variable widgets in the program
        self.widgets = {}
        # widgets['canvas'] is the dict within a dict that store all the Canvas member variables
        self.canvases = {}
        self.canvas_labels = {}
        self.game_in_progress = True
        self.notactoe.set_num_active_boards(3)
        title_frame = Frame(self.root)
        title_frame.grid(row=0, columnspan=2)
        Label(title_frame, text='Time to play NoTacToe!').grid(row=0)
        Label(title_frame, text='Rules:\n(1) Both players play X.\n(2) Once a board has three-in-a-row it dies.\n'
              '(3) The player who kills the last board loses.').grid(row=1, pady=10)
        self.widgets['player_label'] = Label(title_frame, text='Player 1\'s turn', font='bold')
        self.widgets['player_label'].grid(row=2)
        self.canvas_window()
        self.control_window()
        self.bottom_window()
        for i in range(self.MAX_CANVAS):
            self.update_monoid_labels(i)
            self.canvases[i].config(bg="LIGHT GRAY")

    # Creates and displays the canvas objects in a frame
    def canvas_window(self):
        self.widgets['canvas_frame'] = Frame(self.root)
        self.widgets['canvas_frame'].grid(row=1, padx=15)
        for i in range(self.MAX_CANVAS):
            self.canvases[i] = Canvas(self.widgets['canvas_frame'], width=150, height=150)
            self.canvases[i].grid(row=(i/3), column=(i % 3), padx=10, pady=10)
            self.canvas_labels[i] = Label(self.widgets['canvas_frame'], text='1', width=2)
            self.canvas_labels[i].grid(row=(i / 3 + 1), column=(i % 3), padx=10, pady=(0, 10))
        self.paint_canvas()

    # Creates and displays the control options frame
    def control_window(self):
        self.widgets['control_frame'] = Frame(self.root)
        self.widgets['control_frame'].grid(row=0, column=1, rowspan=2)
        Label(self.widgets['control_frame'], text='Number of Boards:').grid(row=0)
        self.widgets['board_variable'] = IntVar()
        self.widgets['board_variable'].set(self.notactoe.get_num_active_boards())
        self.widgets['combined_monoid'] = Label(self.widgets['control_frame'], text='1')
        self.widgets['combined_monoid'].grid(row=5, padx=20, pady=5)
        self.widgets['board_option'] = OptionMenu(self.widgets['control_frame'], self.widgets['board_variable'],
                                                  *self.BOARD_NUMBER_TUPLE, command=self.board_option_callback)
        self.widgets['board_option'].grid(row=1, padx=20, pady=15)
        self.widgets['radio_variable'] = IntVar()
        self.widgets['radio_variable'].set(1)
        self.widgets['radiobutton_player'] = Radiobutton(self.widgets['control_frame'], text="Versus Player",
                                                         variable=self.widgets['radio_variable'],
                                                         value=self.PLAYER_MODE, command=self.reset_callback)
        self.widgets['radiobutton_player'].grid(row=2, sticky='W', padx=20)
        self.widgets['radiobutton_computer'] = Radiobutton(self.widgets['control_frame'], text="Versus Computer",
                                                           variable=self.widgets['radio_variable'],
                                                           value=self.COMPUTER_MODE, command=self.reset_callback)
        self.widgets['radiobutton_computer'].grid(row=3, sticky='W', padx=20)
        Label(self.widgets['control_frame'], text='Composite:').grid(row=4, padx=20, pady=(120, 5))

    def bottom_window(self):
        self.widgets['bottom_frame'] = Frame(self.root)
        self.widgets['bottom_frame'].grid(row=2, columnspan=2)
        self.widgets['reset_button'] = Button(self.widgets['bottom_frame'], text='Reset Game',
                                              command=self.reset_callback)
        self.widgets['reset_button'].grid(row=0, pady=(0, 15))

    # Paints the number of canvas objects based on active boards
    def paint_canvas(self):
        for i in range(self.MAX_CANVAS):
            self.canvases[i].delete("all")
            self.canvases[i].unbind('<Button-1>')
            self.canvas_labels[i].config(text=' ')
        for i in range(self.notactoe.get_num_active_boards()):
            self.canvases[i].bind('<Button-1>', lambda e, j=i: self.click(e, j))
            self.canvases[i].create_line(0, 50, 150, 50)
            self.canvases[i].create_line(0, 100, 150, 100)
            self.canvases[i].create_line(50, 0, 50, 150)
            self.canvases[i].create_line(100, 0, 100, 150)
            self.canvas_labels[i].config(text=BoardCalculations.translate_to_monoid(
                BoardCalculations.get_monoid_index(i, self.notactoe.board_list)))

    def paint_loser(self, board_number):
        self.canvases[board_number].config(bg='LIGHT BLUE')
        # box1, box2, box3 = BoardCalculations.get_loser_boxes(self.notactoe.board_list, board_number)
        # if box1 == 0 and box2 == 1 and box3 == 2:
        #     self.canvases[board_number].create_line(0, 25, 150, 25)
        # elif box1 == 0 and box2 == 3 and box3 == 6:
        #     self.canvases[board_number].create_line(25, 0, 25, 150)
        # elif box1 == 0 and box2 == 4 and box3 == 8:
        #     self.canvases[board_number].create_line(0, 0, 150, 150)
        # elif box1 == 1 and box2 == 4 and box3 == 7:
        #     self.canvases[board_number].create_line(75, 0, 75, 150)
        # elif box1 == 2 and box2 == 5 and box3 == 8:
        #     self.canvases[board_number].create_line(125, 0, 125, 150)
        # elif box1 == 3 and box2 == 4 and box3 == 5:
        #     self.canvases[board_number].create_line(0, 75, 150, 75)
        # elif box1 == 6 and box2 == 7 and box3 == 8:
        #     self.canvases[board_number].create_line(0, 125, 150, 125)

    # Callback to respond when mouse click occurs in a canvas that the click is bound to.  event returns where the
    # click occurred and what canvas was clicked.  index tells the method mark_box which canvas was clicked for the
    # NoTacToe method

    def click(self, event, board_num):
        box = box_number(event.x, event.y)
        if box >= 0:
            if BoardCalculations.mark_box(board_num, box, self.notactoe.board_list, self.notactoe.dead_boards, 'X'):
                draw_x(box, event.widget)
                logging.debug("Human move Board number: %d Box: %d", board_num, box)
                self.change_player()
                self.update_monoid_labels(board_num)
                if BoardCalculations.check_loser(self.notactoe.board_list, self.notactoe.dead_boards, board_num):
                    self.paint_loser(board_num)
                if self.widgets['radio_variable'].get() == self.COMPUTER_MODE and self.game_in_progress:
                    board, box = self.comp_player.make_move()
                    draw_x(box, self.canvases[board])
                    self.change_player()
                    self.update_monoid_labels(board)
                    if BoardCalculations.check_loser(self.notactoe.board_list, self.notactoe.dead_boards, board):
                        self.paint_loser(board)

    def update_monoid_labels(self, board_num):
        self.canvas_labels[board_num].config(text=BoardCalculations.translate_to_monoid(
            BoardCalculations.get_monoid_index(board_num, self.notactoe.board_list)))
        if BoardCalculations.translate_to_monoid(BoardCalculations.find_composite(self.notactoe.board_list)) in \
                BoardCalculations.COLORED_MONOIDS:
            self.widgets['combined_monoid'].config(text=BoardCalculations.translate_to_monoid(
                BoardCalculations.find_composite(self.notactoe.board_list)), foreground='red')
        else:
            self.widgets['combined_monoid'].config(text=BoardCalculations.translate_to_monoid(
                BoardCalculations.find_composite(self.notactoe.board_list)), foreground='black')

    # Modifies widgets['player_label'] based on a method to find out current player and react accordingly
    def change_player(self):
        if self.notactoe.get_player() == 1 and len(self.notactoe.dead_boards) == self.notactoe.get_num_active_boards():
            self.widgets['player_label'].config(text='Player 2 wins!')
            self.notactoe.set_player(2)
            self.game_in_progress = False
            # self.results_callback()
        elif self.notactoe.get_player() == 2 and len(self.notactoe.dead_boards) == \
                self.notactoe.get_num_active_boards():
            self.widgets['player_label'].config(text='Player 1 wins!')
            self.notactoe.set_player(1)
            self.game_in_progress = False
            # self.results_callback()
        elif self.notactoe.get_player() == 1:
            self.widgets['player_label'].config(text='Player 2\'s turn')
            self.notactoe.set_player(2)
        elif self.notactoe.get_player() == 2:
            self.widgets['player_label'].config(text='Player 1\'s turn')
            self.notactoe.set_player(1)
        else:
            return False

    def board_option_callback(self, unused_var):
        self.notactoe.set_num_active_boards(self.widgets['board_variable'].get())
        self.notactoe.reset_game()
        self.paint_canvas()
        self.widgets['player_label'].config(text='Player 1\'s turn')
        self.notactoe.set_player(1)
        self.game_in_progress = True
        for i in range(self.notactoe.get_num_active_boards()):
            self.update_monoid_labels(i)
            self.canvases[i].config(bg="LIGHT GRAY")

    def reset_callback(self):
        self.notactoe.set_num_active_boards(self.widgets['board_variable'].get())
        self.notactoe.reset_game()
        self.paint_canvas()
        self.widgets['player_label'].config(text='Player 1\'s turn')
        self.notactoe.set_player(1)
        self.game_in_progress = True
        for i in range(self.notactoe.get_num_active_boards()):
            self.update_monoid_labels(i)
            self.canvases[i].config(bg="LIGHT GRAY")
Exemple #14
0
def computerGame():
    cPlayer = ComputerPlayer.Player(game)
    cPlayer.runGame()