예제 #1
0
def test_is_in_next_step():
    """Test click the position which is legal place, which means the location
    should be in self.next_step_map"""
    gc = GameController(800, 100)
    assert gc.is_in_next_step(3, 2) is True
    assert gc.is_in_next_step(5, 4) is True
    assert gc.is_in_next_step(7, 7) is False
예제 #2
0
파일: main.py 프로젝트: Mordrog/pyarcanoid
def main():
    os.environ['SDL_VIDEO_CENTERED'] = '1'

    pygame.init()

    pygame.display.set_caption('pyarcanoid')
    pygame.display.set_icon(pygame.image.load('assets/brick.png'))
    screen = pygame.display.set_mode(
        [settings.SCREEN_WIDTH, settings.SCREEN_HEIGHT])
    pygame_clock = pygame.time.Clock()

    background = Background(screen)
    game_controller = GameController(screen)

    running = True
    while running:
        pygame_clock.tick(60)
        screen.fill([0, 0, 0])
        background.update()
        game_controller.update()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    game_controller.pause = not game_controller.pause

        pygame.display.flip()

    pygame.quit()
예제 #3
0
    def __init__(self,
                 delay,
                 collect_cases=False,
                 use_merge_input_nodes=False,
                 *args,
                 **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.title("2048-solver Neural nets")
        self.cell_width = self.cell_height = 100
        self.dim = (4, 4)
        self.delay = delay
        screen_width = self.dim[0] * self.cell_width + 1
        screen_height = self.dim[1] * self.cell_height + 1
        self.canvas = tk.Canvas(self,
                                width=screen_width,
                                height=screen_height,
                                borderwidth=0,
                                highlightthickness=0)
        self.canvas.pack(side="top", fill="both", expand="true")
        self.color_dict = self.fill_color_dict()
        #self.bind_keys()

        self.controller = GameController(
            collect_cases=collect_cases,
            use_merge_input_nodes=use_merge_input_nodes)
        self.do_iteration()
예제 #4
0
def test_score_position():
    gc = GameController(SPACE, filename)
    board = [[-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1],
             [-1, -1, -1, -1, -1, -1, -1], [-1, -1, 1, 0, -1, -1, -1],
             [-1, 1, 1, 0, -1, -1, -1], [-1, 0, 1, 0, -1, -1, -1]]
    assert gc.score_position(board, HUMAN) == -81
    assert gc.score_position(board, AI) == -82
def test_makevalidmove():
    gc = GameController(400, 400)
    bd = Board(4, 4, gc)
    # Actual coordinates on grid
    # If we try to place a disk object in the table
    # index that already has a disk object, will end function
    # and return None
    assert bd.makevalidmove(100, 100) == None
    # If we try to click on a spot that does not have an object
    # but is not valid, will return empty list, because no tiles
    # were flipped
    assert bd.makevalidmove(50, 50) == []

    # If we successfully add a disk in a spot, color flag
    # will change and it will be the other color's turn, in this
    # case, True flag (Black) switches to False (White)
    gc1 = GameController(400, 400)
    bd1 = Board(4, 4, gc1)
    bd1.table[0][0] = Disk(0, 0, 255)
    bd1.table[0][1] = Disk(0, 1, 255)
    bd1.table[0][2] = Disk(0, 2, 255)
    bd1.table[1][0] = Disk(1, 0, 255)
    bd1.table[1][1] = Disk(1, 1, 255)
    bd1.table[1][2] = Disk(1, 2, 0)
    bd1.table[2][0] = Disk(2, 0, 255)
    bd1.table[2][1] = Disk(2, 1, 0)
    bd1.table[2][2] = Disk(2, 2, 0)
    assert bd1.color_flag
    bd1.makevalidmove(350, 350)
    assert not bd1.color_flag
예제 #6
0
def test_start_drop():
    gc = GameController(SPACE, filename)
    cur_x, cur_y = 300, 30
    num_empty_cells_bef = sum(row.count(None) for row in gc.board)
    gc.start_drop(cur_x, cur_y)
    num_empty_cells_aft = sum(row.count(None) for row in gc.board)
    assert num_empty_cells_aft == num_empty_cells_bef - 1
예제 #7
0
def main():
    model = GameModel()
    view = GameView(800, 600)
    controller = GameController(model, view)
    # ---
    while (True):
        controller.update()
def test_check_all_positions():
    gc = GameController(400, 400)
    bd = Board(4, 4, gc)
    # Tests case where board is filled by all black
    # manually insert a white disk at point table[0][0]
    # game ends and method returns expected tuple
    for y in range(len(bd.table)):
        for x in range(len(bd.table)):
            bd.table[y][x] = Disk(y, x, 0)
    bd.table[0][0] = Disk(0, 0, 255)
    assert bd.check_all_positions() == (15, 1)

    # Tests case where board is not filled but
    # there are no more possible valid moves for
    # both sides and game ends. Test returns expected tuple
    gc1 = GameController(400, 400)
    bd1 = Board(4, 4, gc1)
    bd1.table[1][1] = 0
    bd1.table[1][2] = 0
    bd1.table[2][1] = 0
    bd1.table[2][2] = 0
    bd1.table[0][0] = Disk(0, 0, 0)
    bd1.table[0][1] = Disk(0, 1, 255)
    bd1.makevalidmove(250, 0)
    assert bd1.check_all_positions() == (3, 0)
예제 #9
0
 def play(self, login, password):
     game_controller = GameController()
     game_controller.load_board()
     board = self.get_board()
     # self.board.show()
     solver = Solver(board)
     solver.solve()
예제 #10
0
    def __init__(self, board_width, game_size, player_name, player_color):
        '''
        Initializing the game with class Board, and class GameController
        '''
        self.board = Board(board_width, game_size)
        self.tiles = [Tile(board_width / game_size)
                      for _ in range(game_size ** 2)]
        self.gc = GameController(board_width, board_width,
                                 player_name, player_color)

        tile = self.tiles.pop()
        tile.set_white()
        self.board.grids[game_size//2 - 1][game_size//2 - 1] = tile

        tile = self.tiles.pop()
        tile.set_black()
        self.board.grids[game_size // 2][game_size//2 - 1] = tile

        tile = self.tiles.pop()
        tile.set_black()
        self.board.grids[game_size//2 - 1][game_size // 2] = tile

        tile = self.tiles.pop()
        tile.set_white()
        self.board.grids[game_size // 2][game_size // 2] = tile

        self.valid_grids = set({})
        self.is_black = True
        # self.game_start()
        # self.skip_times = 0
        self.is_control = False
예제 #11
0
def main():
    gc = GameController()

    print("------------------------------------")
    print("Welcome to the simplified BlackJack!")

    gc.start_play()
예제 #12
0
파일: main.py 프로젝트: wkamel/slowotok
 def play(self, login, password):
     game_controller = GameController()
     game_controller.load_board()
     board = self.get_board()
     # self.board.show()
     solver = Solver(board)
     solver.solve()
def main():
    logger = get_logger()
    logger.info("取得開始")
    game = GameController()
    old = 0
    # 数字データ
    numbers = get_numbers_ndarray()
    while True:
        screen = game.take_png_screenshot_for_win10(True)
        screen = screen[90:90 + 40, -190:-1]  # だいたいスキルアイコンの下あたりにある想定でクロップ
        mask_image = cv2.inRange(screen, np.array([255, 34, 34]),
                                 np.array([255, 34, 34]))  # 赤色文字のみ抽出
        mask_image, contours, hierarchy = cv2.findContours(
            mask_image, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
        rects = convert_contours_to_rects(contours)
        rects = remove_same_x_rect(rects)
        text = ""
        for [x, y, w, h] in rects:
            for i, number in enumerate(numbers):
                if np.allclose(mask_image[y:y + 9, x:x + 2], number):
                    text = text + str(i)
        if text != "":
            num = int(text)
            if old != 0:
                number_per_minute = num - old
                old = num
                logger.info("差分撃破数:{0}".format(number_per_minute))
            else:
                old = num
                logger.info("初回取得完了 数字:{0}".format(num))
        else:
            old = 0
            logger.info("撃破数取得エラー")
        time.sleep(60)
예제 #14
0
    def fight_start(self):
        """
        START按钮响应流程
        :return:
        """
        self.scaling = self.get_scaling()
        if not self.scaling:
            return False
        self.clear_time = self.get_clear_time()
        if not self.clear_time:
            return False
        self.delay_time = self.get_delay_time()
        if not self.delay_time:
            return False
        self.timing_value = self.get_timimg()
        if not self.timing_value:
            return False
        self.info_save()

        # 获取游戏窗口句柄
        self.hwnd = check_hwnd(self.label)
        if not self.hwnd:
            messagebox.showinfo(title='提示', message='游戏没有运行')
            return False
        # self.shell = win32com.client.Dispatch("WScript.Shell")
        # self.shell.SendKeys('%')

        jump_window(self.hwnd)
        time.sleep(0.5)
        self.fight = GameController(self.hwnd, self.scaling)
        if self.debug:
            self.fight.setdebug(True)
        threads = []
        thread1 = threading.Thread(target=self.fight_thread,
                                   name='fight_thread')
        threads.append(thread1)
        thread2 = threading.Thread(target=self.offer_thread,
                                   name='offer_thread')
        threads.append(thread2)
        thread3 = threading.Thread(target=self.fullrepo_thread,
                                   name='fullrepo_thread')
        threads.append(thread3)
        if self.listbox_timing_mode.get(
        ) == '超鬼王模式1' or self.listbox_timing_mode.get() == '超鬼王模式2':
            thread4 = threading.Thread(target=self.boss_monitoring_thread,
                                       name='boss_thread')
            threads.append(thread4)
        # 将线程状态、队列内容置为1
        self._running = 1
        if self.queue.empty():
            self.queue.put(1)
        else:
            self.queue.get()
            self.queue.put(1)
        self.start_ctn.configure(state='disabled')
        self.stop_ctn.configure(state='active')
        for thread in threads:
            thread.setDaemon(True)
            thread.start()
예제 #15
0
def test_change_color():
    """Test change color"""
    gc = GameController(800, 100)
    # the original color is 0 (black color)
    assert gc.color == 0
    gc.change_color()  # execute change color method
    # new color is 255 (white color)
    assert gc.color == 255
예제 #16
0
 def _compete_game(self, player1, player2):
     controller = GameController(player1, player2)
     winner = None
     moves = []
     while winner is None:
         winner, move = controller.make_move()
         moves.append(move)
     return winner, moves
예제 #17
0
def test_player_move():
    """ Test player's move """
    gc = GameController(400, 400, 4)
    gc.board.tiles.counting_tile()
    lst = gc.board.legal_move(0)
    gc.player_make_move(200, 300)
    assert gc.board.tiles.t_total[2][3].get_color() == 0
    assert gc.board.tiles.t_total[2][2].get_color() == 0
    assert gc.board.tiles.t_total[2][3].get_color() == 0
예제 #18
0
def test_col_win():
    gc = GameController(SPACE, filename)
    board = [[-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1],
             [-1, -1, -1, -1, -1, -1, -1], [-1, -1, 1, 0, -1, -1, -1],
             [-1, 1, 1, 0, -1, -1, -1], [-1, 0, 1, 0, -1, -1, -1]]
    assert not gc.col_win(board, HUMAN)
    assert not gc.col_win(board, AI)
    board[2][2] = 1
    assert gc.col_win(board, HUMAN)
예제 #19
0
def test_row_win():
    gc = GameController(SPACE, filename)
    board = [[-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1],
             [-1, -1, -1, -1, -1, -1, -1], [-1, 0, 0, 0, -1, -1, -1],
             [-1, 1, 1, 1, -1, -1, -1], [-1, 0, 1, 0, 1, -1, -1]]
    assert not gc.row_win(board, HUMAN)
    assert not gc.row_win(board, AI)
    board[4][4] = 1
    assert gc.row_win(board, HUMAN)
예제 #20
0
 def start_game(self, player_types_dict):
     self.player1 = self.get_and_load_player(self.player1,
                                             player_types_dict["x"],
                                             Board.X)
     self.player2 = self.get_and_load_player(self.player2,
                                             player_types_dict["o"],
                                             Board.O)
     self.controller = GameController(self.player1, self.player2)
     return self._get_game_info(None)
예제 #21
0
def main(stdscr):
    model = Model()
    agent = A2CAgent(model)
    learning_environment = LearningEnvironment()

    agent.initialize_model(learning_environment)
    agent.load_model_if_previously_saved()

    game_controller = GameController(stdscr)
    game_controller.play(agent, learning_environment)
def test_read_file():
    WIDTH = 600
    stone = Stone(WIDTH)
    gc = GameController(WIDTH, stone)

    assert gc.score_list == []
    # The default when scores.txt is blank

    gc.read_file('test_scores.txt')
    assert gc.score_list == [['Khai4', 22], ['Khai3', 20]]
예제 #23
0
def test_ranked_flipped_space():
    """Test ranked flipped space method"""
    gc = GameController(800, 100)
    assert (gc.ranked_flipped_space({
        (3, 2): {(3, 3)},
        (5, 4): {(4, 4), (4, 5)},
        (4, 5): {(4, 4)},
        (2, 3): {(3, 3)}
    })) == [((5, 4), {(4, 5), (4, 4)}), ((3, 2), {(3, 3)}), ((4, 5), {(4, 4)}),
            ((2, 3), {(3, 3)})]
예제 #24
0
    def perform(puzzle, row, col):
        listofmoves = []
        q = Queue.Queue()
        fifo = puzzle
        puzzlee = deepcopy(puzzle)
        steps = 0
        moves = {}  # dictionary that holds the visited nodes to refer to
        path = []
        coord = ["start"]  # list of moves
        path.append((puzzlee, coord))  # keep track of the path of each node

        moves[str(
            deepcopy(puzzle))] = "visited"  # Add the puzzel as a visited node
        while (GameController.is_solved(fifo) !=
               1):  # while the puzzle is not solved search for solution
            for i in range(row):
                for e in range(col):
                    pmove = GameController.perform_move(
                        deepcopy(fifo), i, e)  # perform move on the puzzle
                    check = str(
                        pmove)  # add state afer performing move to check
                    steps = steps + 1  # count the number of steps
                    c = str(e) + str(i)  # store coordinates of move in C

                    if check in moves:  # if the node has been visited do nothing
                        pass

                    else:
                        moves[deepcopy(
                            check
                        )] = "visited"  # add the new state to dictionary of visited nodes
                        coord.append(c)
                        q.put(
                            deepcopy(pmove))  # put the state in our LIFO queue
                        path.append(
                            (deepcopy(pmove), deepcopy(coord))
                        )  # Keep track of the path that leads to the state

                        coord.pop()

            fifo = q.get()  # get the first state
            currentstate, coord = path.pop(
                1)  # get the state and the matching path to get to it

        ret = []
        for i in range(row):
            for e in range(col):
                if coord.count(
                    (str(i) + str(e))
                ) % 2 == 1:  # if coordinates occur in any muitple of two then it is the same as not
                    # performing the move so we only want odd number moves
                    listofmoves.append(str(i) + str(e))
                    ret.append([str(i), str(e)])

        return ret
예제 #25
0
def test_game_can_proceed():
    """Test the game_can_proceed method."""
    tiles = Tiles(800, 100)
    board = Board(800, 100, tiles)
    player = Player('Alfred', board, 'black')
    ai = AI(board, player)
    game_controller = GameController(player, ai, board)
    assert game_controller.game_can_proceed() is True
    for pair in board.on_board:
        board.tiles_list[pair[0]][pair[1]].color = 'white'
    assert game_controller.ai_has_move() is False
예제 #26
0
def main():
    print("--------------------------------\n\
Welcome to street craps!\n")
    print("Rules:")
    print("If you roll 7 or 11 on your first roll, you win.\n\
If you roll 2, 3, or 12 on your first roll, you lose.\n\
If you roll anything else, that's your 'point', and\n\
you keep rolling until you either roll your point\n\
again (win) or roll a 7 (lose)\n")
    gc = GameController()
    gc.start_play()
예제 #27
0
def test_search_flips():
    gc1 = GameController(800, 800)
    b1 = Board(800, 800, gc1)
    gc2 = GameController(800, 800)
    b2 = Board(800, 800, gc2)
    # Illegal move.
    flips1 = b1.search_flips(0, 0, 0)
    # Legal move.
    flips2 = b2.search_flips(2, 3, 0)
    assert flips1 == {}
    assert flips2["right"] == [(3, 3)]
예제 #28
0
def test_minimax():
    gc = GameController(SPACE, filename)
    board = [[-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, -1, -1, -1, -1],
             [-1, -1, -1, -1, -1, -1, -1], [-1, -1, -1, 0, -1, -1, -1],
             [-1, -1, -1, 1, 0, -1, -1], [-1, -1, 0, 1, 1, -1, 1]]
    depth = 3
    alpha = -sys.maxsize
    beta = sys.maxsize
    maximizing = True
    best_col = gc.minimax(board, depth, alpha, beta, maximizing)[0]
    assert best_col == 5
def test_can_go():
    WIDTH = 600
    stone = Stone(WIDTH)
    gc = GameController(WIDTH, stone)
    gc.counter = 2
    gc.stone.total_row[3][3].color = 0  # 4 starting stones
    gc.stone.total_row[4][4].color = 0
    gc.stone.total_row[3][4].color = 1
    gc.stone.total_row[4][3].color = 1
    gc.can_go()
    assert len(gc.moves_list) == 4  # First move: 4 valids moves for player
예제 #30
0
def test_get_open_row():
    gc = GameController(SPACE, filename)
    board = [[-1, -1, 1, 1, -1, -1, -1], [-1, -1, 0, 0, -1, -1, -1],
             [-1, 1, 0, 1, -1, -1, -1], [-1, 0, 0, 0, -1, -1, -1],
             [-1, 1, 1, 1, -1, -1, -1], [-1, 0, 1, 0, 1, -1, -1]]
    col0 = 0
    col1 = 1
    col4 = 4
    assert gc.get_open_row(board, col0) == 5
    assert gc.get_open_row(board, col1) == 1
    assert gc.get_open_row(board, col4) == 4
예제 #31
0
    def _train_game(self, player1, player2):
        controller = GameController(player1, player2)
        winner = None
        while winner is None:
            winner, _ = controller.make_move()
            run_if_learner(player1, lambda: player1.store_state())
            run_if_learner(player2, lambda: player2.store_state())

        run_if_learner(player1, lambda: player1.set_reward(winner))
        run_if_learner(player2, lambda: player2.set_reward(winner))
        return winner
예제 #32
0
파일: main.py 프로젝트: jschaf/Tetris-Math
def main():

    
    pygame.init()
    screen = pygame.display.set_mode ((1024, 768), SWSURFACE)
    pygame.display.set_caption('Tetris Math')

    clock = pygame.time.Clock()
    MAX_FPS = 80
    controller = GameController(screen)

#    try:
    while controller.running:
            controller.update()
            controller.draw()
            clock.tick(MAX_FPS)
예제 #33
0
    def perform(puzzle, row, col):
        listofmoves = []
        q = Queue.Queue()
        fifo = puzzle
        puzzlee = deepcopy(puzzle)
        steps = 0
        moves = {}  # dictionary that holds the visited nodes to refer to
        path = []
        coord = ["start"]  # list of moves
        path.append((puzzlee, coord))  # keep track of the path of each node

        moves[str(deepcopy(puzzle))] = "visited"  # Add the puzzel as a visited node
        while (GameController.is_solved(fifo) != 1):  # while the puzzle is not solved search for solution
            for i in range(row):
                for e in range(col):
                    pmove = GameController.perform_move(deepcopy(fifo), i, e)  # perform move on the puzzle
                    check = str(pmove)  # add state afer performing move to check
                    steps = steps + 1  # count the number of steps
                    c = str(e) + str(i)  # store coordinates of move in C

                    if check in moves:  # if the node has been visited do nothing
                        pass

                    else:
                        moves[deepcopy(check)] = "visited"  # add the new state to dictionary of visited nodes
                        coord.append(c)
                        q.put(deepcopy(pmove))  # put the state in our LIFO queue
                        path.append(
                            (deepcopy(pmove), deepcopy(coord)))  # Keep track of the path that leads to the state

                        coord.pop()

            fifo = q.get()  # get the first state
            currentstate, coord = path.pop(1)  # get the state and the matching path to get to it

        ret = []
        for i in range(row):
            for e in range(col):
                if coord.count((str(i) + str(
                        e))) % 2 == 1:  # if coordinates occur in any muitple of two then it is the same as not
                    # performing the move so we only want odd number moves
                    listofmoves.append(str(i) + str(e))
                    ret.append([str(i),str(e)])

        return ret
예제 #34
0
    def perform(puzzle, row, col):
        # dictionary to keep track of visited nodes
        moves = {}
        moves[str(deepcopy(puzzle))] = "visited"
        listofmoves = []
        q = Queue.LifoQueue()
        state = puzzle
        steps = 0
        path = []
        coord = ["start"]
        path.append((state, coord))

        while (GameController.is_solved(state) != 1):  # while puzzle is not solved
            for i in range(row):
                for e in range(col):
                    move = GameController.perform_move(deepcopy(state), i, e)  # perform move on puzzle
                    check = str(move)
                    steps = steps + 1  # count the number of steps
                    c = str(e) + str(i)  # store coordinates of move in C
                    if check in moves:  # if node has been visited then do nothing
                        pass


                    else:
                        moves[deepcopy(check)] = "visited"  # add state to visited nodes dictionary
                        coord.append(c)
                        q.put(deepcopy(move))  # put the state in our LIFO queue
                        path.append((deepcopy(move), deepcopy(coord)))  # Keep track of the path that leads to the state
                        coord.pop()

            # get the last state added to the queue (LIFO) --> this is the next state to perform move on
            state = q.get()
            currentstate, coord = path.pop()

        ret = []
        for i in range(row):
            for e in range(col):
                if coord.count((str(i) + str(
                        e))) % 2 == 1:  # if coordinates occur in any muitple of two then it is the same as not
                    # performing the move so we only want odd number moves
                    listofmoves.append(str(i) + str(e))
                    ret.append([str(i),str(e)])

        return ret
예제 #35
0
    def __init__(self, delay, collect_cases=False, use_merge_input_nodes=False, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.title("2048-solver Neural nets")
        self.cell_width = self.cell_height = 100
        self.dim = (4, 4)
        self.delay=delay
        screen_width = self.dim[0]*self.cell_width+1
        screen_height = self.dim[1]*self.cell_height+1
        self.canvas = tk.Canvas(self, width=screen_width, height=screen_height, borderwidth=0, highlightthickness=0)
        self.canvas.pack(side="top", fill="both", expand="true")
        self.color_dict = self.fill_color_dict()
        #self.bind_keys()

        self.controller = GameController(collect_cases=collect_cases, use_merge_input_nodes=use_merge_input_nodes)
        self.do_iteration()
예제 #36
0
class Gui(tk.Tk):
    def __init__(self, delay, collect_cases=False, use_merge_input_nodes=False, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.title("2048-solver Neural nets")
        self.cell_width = self.cell_height = 100
        self.dim = (4, 4)
        self.delay=delay
        screen_width = self.dim[0]*self.cell_width+1
        screen_height = self.dim[1]*self.cell_height+1
        self.canvas = tk.Canvas(self, width=screen_width, height=screen_height, borderwidth=0, highlightthickness=0)
        self.canvas.pack(side="top", fill="both", expand="true")
        self.color_dict = self.fill_color_dict()
        #self.bind_keys()

        self.controller = GameController(collect_cases=collect_cases, use_merge_input_nodes=use_merge_input_nodes)
        self.do_iteration()

    def do_iteration(self):
        self.controller.run_algorithm()
        self.draw_board()
        if self.controller.continuing:
            self.after(self.delay, lambda: self.do_iteration())

    def bind_keys(self):
        self.bind('<Up>', lambda event: self.move(self, self.game_board.move_up()))
        self.bind('<Down>', lambda event: self.move(self, self.game_board.move_down()))
        self.bind('<Right>', lambda event: self.move(self, self.game_board.move_right()))
        self.bind('<Left>', lambda event: self.move(self, self.game_board.move_left()))

    def move(self, event, is_moved):
        if is_moved:
            self.game_board.generate_new_node()
            self.draw_board()

    def draw_board(self):
        self.canvas.delete("all")
        for y in range(self.dim[1]):
                for x in range(self.dim[0]):
                    x1 = x * self.cell_width
                    y1 = self.dim[1]*self.cell_height - y * self.cell_height
                    x2 = x1 + self.cell_width
                    y2 = y1 - self.cell_height
                    cell_type = self.controller.board[y][x]
                    text = str(self.controller.board[y][x])
                    color = self.color_dict[str(self.controller.board[y][x])]
                    self.canvas.create_rectangle(x1, y1, x2, y2, fill=color, tags="rect")
                    if cell_type != 0:
                        self.canvas.create_text(x1+self.cell_width/2, y1-self.cell_height/2, text=text)

    def fill_color_dict(self):
        color_dict = {
            '0': "white",
            '2': "lemon chiffon",
            '4': "peach puff",
            '8': "sandy brown",
            '16': "dark orange",
            '32': "salmon",
            '64': "tomato",
            '128': "khaki",
            '256': "khaki",
            '512': "red",
            '1024': "light goldenrod",
            '2048': "firebrick",
            '4096': "dim grey",
            '8192': "light goldenrod",
        }
        return color_dict
예제 #37
0
        if (choice == '1'):
            pass
        elif (choice == '2'):
            print "Claim functionality not supported yet"
            continue
        elif (choice == '3'):
            break
        else:
            print "Wrong Input"  # can put try/except with loop instead
            continue

        # TODO Use with to control context

        game_id = 24  # TODO This has to be generated and used in DB
        game_session = GameController(game_id, _delay) # STARTS new thread
        #print "#####", game_session

        player_handler = PlayerInputHandler(game_session)
        player_handler_thread = threading.Thread(target=player_handler.worker_thread)
        player_handler_thread.start()

        #print "+++++", player_handler_thread

        print "Starting Game\n"
        game_session.start()

        while (game_session.is_game_over() == False):
            #time.sleep(5) # Debug code
            # if tkt_claimed from KB, call GamController.keyPress
            key = raw_input()
예제 #38
0
from game_controller import GameController
from bfs import BFS
from dfs import DFS
from a_star import AStar


# work with hash map because checking of already existing state


# -------------------------------------------------------------------------

# row = int(input('Enter number of Rows (Must be > 1): '))
row = 2
# col  int(input('Enter number of Columns (Must be > 1): '))
col = 3
puzzel = GameController.create_puzzle(row, col)

puzzel = GameController.scramble(puzzel)

# puzzel = [[' 0 ', ' 0 ', ' 0 '], [' 1 ', ' 0 ', ' 1 ']]

puzzelorg = deepcopy(puzzel)
puzzeldfs = deepcopy(puzzel)

# -------------------------------------------------------------------------
# uncomment this block to use the dfs_ai search algorithm
moves = DFS.perform(puzzel, row, col)

# uncomment to use the A* search
# moves =  AStar.perform(puzzel, row,col)
예제 #39
0
def main():
    logging.basicConfig(format='[%(asctime)s] [%(threadName)13s] %(levelname)7s: %(message)s', level=logging.DEBUG)

    logging.info("Starting up...")

    # ## Loading Configuration
    logging.debug("Loading configuration...")
    config = configparser.ConfigParser()
    config.read('config.ini')
    # General
    gui_enabled = config["General"].getboolean("GUI")
    configure_all(config)
    logging.debug("Configuration loaded.")

    ### Starting up Matrix
    matrix_controller = MatrixController()

    game_controller = GameController(matrix_controller)

    ### Starting up Webserver
    webserver = MatrixWebserver(game_controller, address="", port=8000)
    webserver.start()

    root = None
    if gui_enabled:
        ### Starting up GUI
        try:
            root = tkinter.Tk()
        except tkinter.TclError:
            logging.warning("Could not initialise Tk class - Disabling GUI")
            gui_enabled = False
        else:
            root.geometry("302x750+50+50")
            root.title("LED control panel")
            app = GUIapp(root, game_controller)
            # Matrix controller will trigger GUI update when data changes
            matrix_controller.connect("data_update", app.update)

    game_controller.set_game_mode(GameController.Mode.test)

    if gui_enabled:
        logging.debug("Entering tkinter mainloop")
        ### MAIN LOOP when GUI is enabled
        root.mainloop()
        logging.debug("Tkinter mainloop has exited.")
    else:
        try:
            ### MAIN LOOP when gui is disabled
            run = True
            while run:
                user_input = input("Type 'q' to stop or 'reset id' to reset all ID's.\n")
                if user_input == "q":
                    run = False
                elif user_input == "reset id":
                    matrix_controller.reset_id_all()
        except KeyboardInterrupt:
            logging.info("Keyboard interrupt received.")

    ### STOPPING
    logging.info("Stopping...")
    webserver.join()
    matrix_controller.stop()
    logging.info("Stopped.")
예제 #40
0
    def perform2(puzzle, row, col):
        listofmoves = []
        q = Queue.PriorityQueue()
        fifo = puzzle
        steps = 0
        moves = {}
        moves[str(deepcopy(puzzle))] = "visited"
        path = Queue.PriorityQueue()
        coord = ["start"]

        while (GameController.is_solved(fifo) != 1):

            for i in range(row):
                for e in range(col):

                    if (fifo != "empty"):  # empty is used to represent nodes that have been visited

                        pmove = GameController.perform_move(deepcopy(fifo), i, e)  # perform move on the puzzel
                        check = str(pmove)
                        steps = steps + 1  # count the number of steps
                        state = deepcopy(pmove)
                        lights = GameController.count_lights(pmove)  # count the number of lights
                        c = str(e) + str(i)  # store coordinates of move in C

                        if check in moves:  # if node has been been visited then do nothing
                            pass


                        else:
                            # prioritize puzzles that have been solved
                            if lights == 0:
                                moves[deepcopy(check)] = "visited"
                                q.put((1, state))  # put the state in our queue
                                coord.append(c)
                                path.put((1, (
                                    deepcopy(pmove),
                                    deepcopy(coord))))  # Keep track of the path that leads to the state
                                coord.pop()

                            # prioritize puzzles that have one more move to solve next
                            elif lights == 5:
                                moves[deepcopy(check)] = "visited"
                                q.put((2, state))  # put the state in our queue
                                coord.append(c)
                                path.put((2, (
                                    deepcopy(pmove),
                                    deepcopy(coord))))  # Keep track of the path that leads to the state
                                coord.pop()

                            # prioritize puzzles that have one more move to solve next
                            elif lights == 3:
                                moves[deepcopy(check)] = "visited"
                                q.put((3, state))  # put the state in our queue
                                coord.append(c)
                                path.put((3, (
                                    deepcopy(pmove),
                                    deepcopy(coord))))  # Keep track of the path that leads to the state
                                coord.pop()

                            else:  # else treat as a regular state to explore
                                moves[deepcopy(check)] = "visited"
                                q.put((4, state))  # put the state in our queue
                                coord.append(c)
                                path.put((4, (
                                    deepcopy(pmove),
                                    deepcopy(coord))))  # Keep track of the path that leads to the state
                                coord.pop()

            junk, fifo = q.get()  # get the highest priority state
            priority, info = path.get()
            coord = info[1]

        ret = []
        for i in range(row):
            for e in range(col):
                if coord.count((str(i) + str(
                        e))) % 2 == 1:  # if coordinates occur in any muitple of two then it is the same as not
                    # performing the move so we only want odd number moves
                    listofmoves.append(str(i) + str(e))
                    ret.append([str(i), str(e)])

        return ret