Пример #1
0
def test_save_name_in_file():
    """Test save_name_in_file method"""
    # Lisa play the game and get her score, store her score in the file
    gc = GameController(800, 100)
    gc.save_name_in_file("Lisa", "test_save_name.txt")

    # Lee play the game and get his score, store his score in the file, it
    # shoule be on the top, because his score is higher than lisa's score
    for i in range(len(gc.grid)):
        for j in range(len(gc.grid)):
            gc.grid[i][j] = Disk(i, j, 0)
    gc.save_name_in_file("Lee", "test_save_name.txt")

    # Chris play the game and get his score, store his score in the file, it
    # shoule be on the bottom, because his score is lower than lee's score
    gc = GameController(800, 100)
    for i in range(len(gc.grid)):
        for j in range(len(gc.grid)):
            if i == 0:
                gc.grid[i][j] = Disk(i, j, 0)
    gc.save_name_in_file("Chris", "test_save_name.txt")

    # Check the first person and the last person in the file
    with open("test_save_name.txt") as file:
        assert file.readline().strip() == "Lee 64"
        assert file.readlines()[-1].strip() == "Chris 10"
Пример #2
0
def test_run():
    d = Disk(10, 10)
    d.node_dict[0] = Disk(122, 33)
    d.color, d.node_dict[0].display_on = True, True
    d.node_dict[0].node_dict[0] = Disk(85, 64)
    d.run(0, True)
    assert d.node_dict[0].color is False
Пример #3
0
 def __init__(self, WIDTH, HEIGHT, CELL, gr):
     self.WIDTH = WIDTH
     self.HEIGHT = HEIGHT
     self.cell = CELL
     num_start_disks = 2
     self.black_score = num_start_disks
     self.white_score = num_start_disks
     self.total_count = num_start_disks * 2
     self.gr = gr
     self.total_col = self.WIDTH // self.cell
     self.total_row = self.HEIGHT // self.cell
     self.table = [[0] * self.total_col for i in range(self.total_row)]
     half_cell = self.cell / 2
     self.disk1 = (Disk(self.WIDTH // 2 + half_cell,
                        self.HEIGHT // 2 - half_cell, self.cell))
     self.disk2 = (Disk(self.WIDTH // 2 - half_cell,
                        self.HEIGHT // 2 + half_cell, self.cell))
     self.disk3 = (Disk(self.WIDTH // 2 - half_cell,
                        self.HEIGHT // 2 - half_cell, self.cell))
     self.disk4 = (Disk(self.WIDTH // 2 + half_cell,
                        self.HEIGHT // 2 + half_cell, self.cell))
     self.table[self.disk1.row][self.disk1.column] = self.disk1
     self.table[self.disk2.row][self.disk2.column] = self.disk2
     self.table[self.disk3.row][self.disk3.column] = self.disk3
     self.table[self.disk4.row][self.disk4.column] = self.disk4
     self.disk3.draw_black = False
     self.disk4.draw_black = False
     self.legal_table = set()
Пример #4
0
def test_halo_run():
    d = Disk(10, 10)
    d.node_dict[0] = Disk(122, 33)
    d.color, d.node_dict[0].display_on = True, True
    d.node_dict[0].node_dict[0] = Disk(85, 64)
    d.halo_run(0, True)
    assert d.node_dict[0].node_dict[0].halo_tag is True
Пример #5
0
def test_check_win_horizontal():
    # initiate disk objects
    cw = Check_Win(matrix)
    dk1 = Disk("test")
    dk2 = Disk("test")
    dk3 = Disk("test")
    dk4 = Disk("test")

    # test horizontal by placing the disks
    cw.matrix[3][5] = dk1
    cw.matrix[4][5] = dk2
    cw.matrix[5][5] = dk3
    cw.matrix[6][5] = dk4

    # get result
    re = cw.check_win()
    assert len(cw.matrix) == 7 and \
        len(cw.matrix[5]) == 6 and \
        len(cw.matrix[6]) == 6 and \
        cw.matrix[3][5] != 0 and \
        matrix[4][5] != 0 and \
        matrix[5][5] != 0 and \
        matrix[6][5] != 0 and \
        matrix[3][5].color == "test" and \
        matrix[4][5].color == "test" and \
        matrix[5][5].color == "test" and \
        matrix[6][5].color == "test" and \
        re == "test"
Пример #6
0
def test_check_win_increasing_diaganol():
    # initiate the disk objects
    cw = Check_Win(matrix)
    dk1 = Disk("test")
    dk2 = Disk("test")
    dk3 = Disk("test")
    dk4 = Disk("test")
    # test increasing diaganol by placing the disks
    cw.matrix[2][2] = dk1
    cw.matrix[5][5] = dk2
    cw.matrix[4][4] = dk3
    cw.matrix[3][3] = dk4
    # get result
    re = cw.check_win()
    assert len(cw.matrix) == 7 and \
        len(cw.matrix[5]) == 6 and \
        len(cw.matrix[6]) == 6 and \
        cw.matrix[2][2] != 0 and \
        matrix[5][5] != 0 and \
        matrix[4][4] != 0 and \
        matrix[3][3] != 0 and \
        matrix[2][2].color == "test" and \
        matrix[5][5].color == "test" and \
        matrix[4][4].color == "test" and \
        matrix[3][3].color == "test" and \
        re == "test"
Пример #7
0
    def __create_instances(self, dep_id, common_section, config_sections):
        emailid = common_section.emailid
        instance_user_name = common_section.instance_user_name
        # Launch instances
        for section in config_sections:
            section_name = section.section_name
            count = int(section.count)
            tag = section.tag
            machinetype = section.machinetype
            disk1image = section.disk1image
            disk2image = section.disk2image
            disk1type = section.disk1type
            disk2type = section.disk2type
            disk1size = section.disk1size
            disk2size = section.disk2size

            for num in range(count):
                instance_name = emailid + "-" + dep_id + "-" + section_name + "-" + tag + "-" + str(
                    num)
                disk1 = Disk(instance_name + "-d1", disk1image, disk1size,
                             disk1type)
                disk2 = Disk(instance_name + "-d2", disk2image, disk2size,
                             disk2type)
                disk1.create()
                disk2.create()

                disk_list = [disk1, disk2]
                instance = Instance(instance_name, disk_list, machinetype,
                                    instance_user_name)
                instance.create(common_section)
                if section_name == "master":
                    self.master_instances.append(instance)
                else:
                    self.slave_instances.append(instance)
                self.instances.append(instance)
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 test_repr():
    """Test__repr__"""
    d = Disk(100, 150, 50)
    d.draw_black = True
    assert repr(d) == "Black"
    d1 = Disk(100, 150, 50)
    d1.draw_black = False
    assert repr(d1) == "White"
Пример #10
0
def test_clear_bad_moves():
    ai = othelloAI()
    d = Disk(-1000, '345')
    d2 = Disk(1, 1)
    ai.coordinate_extractor(d)
    ai.coordinate_extractor(d2)
    ai.fill_fin_avoid()
    assert ai.clear_bad_moves() == [(-1000, '345')]
Пример #11
0
def test_last_resort():
    ai = othelloAI()
    d = Disk(-1000, '345')
    d2 = Disk(1, 1)
    ai.coordinate_extractor(d)
    ai.coordinate_extractor(d2)
    ai.fill_fin_avoid()
    assert ai.last_resort() == [(-1000, '345')]
Пример #12
0
 def init_disk(self):
     """Put the initial four disk"""
     self.put(self.SIZE/2-1, self.SIZE/2-1,
              Disk(self.SIZE/2-1, self.SIZE/2-1, 255, self, self.DISKSIZE))
     self.put(self.SIZE/2-1, self.SIZE/2,
              Disk(self.SIZE/2-1, self.SIZE/2, 0, self, self.DISKSIZE))
     self.put(self.SIZE/2, self.SIZE/2-1,
              Disk(self.SIZE/2, self.SIZE/2-1, 0, self, self.DISKSIZE))
     self.put(self.SIZE/2, self.SIZE/2,
              Disk(self.SIZE/2, self.SIZE/2, 255, self, self.DISKSIZE))
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
Пример #14
0
 def initial_disk(self):
     """Initialize the first four disks"""
     middle = self.dimension // 200
     DIFF = 1
     self.grid[middle - DIFF][middle - DIFF] \
         = Disk(middle - DIFF, middle - DIFF, self.white_color)
     self.grid[middle - DIFF][middle] \
         = Disk(middle - DIFF, middle, self.black_color)
     self.grid[middle][middle - DIFF] \
         = Disk(middle, middle - DIFF, self.black_color)
     self.grid[middle][middle] = Disk(middle, middle, self.white_color)
Пример #15
0
    def add_disk(self, table_index_y, table_index_x):
        """Method to add a black or white disk to the board, checks if
        position that we want to add in already has a disk"""

        # If element in the linked list is already an object, end function
        if self.table[table_index_y][table_index_x]:
            return

        # Determines what color to put down based on flag.
        # Always starts with black, which is when color_flag is True
        if self.color_flag:
            self.table[table_index_y][table_index_x] = \
                Disk(table_index_y, table_index_x, 0)
            # Self Display method mentioned in pytest comments
            # For pytest to work, comment out self.display()
            # Functions will still work as normal, just without delay
            self.display()
            self.color_flag = False  # After put down disk, make flag False

        # If color_flag is False, means white disk is going to be put down
        elif not self.color_flag:
            self.table[table_index_y][table_index_x] = \
                Disk(table_index_y, table_index_x, 255)
            self.color_flag = True  # After put down disk, make flag True

        # The method isvalid() is called with this method - isvalid()
        # isvalid() checks all the valid moves at that turn for a specific
        # color and returns a set of tuples, which are (row, column) indexes
        # for that color

        self.isvalid()

        # If the first isvalid() check returns an empty set, which
        # is False, we change the color_flag to the opposite color and
        # print the statements accordingly.
        if not self.isvalid():
            if self.color_flag:
                self.color_flag = False
                print("No more moves for player. Computer's turn")

            elif not self.color_flag:
                self.color_flag = True
                print("No more moves for computer. Player's turn")

        # We check one more time after the color_flag has changed
        self.isvalid()

        # If the set is empty once again, it will empty this if statement
        if not self.isvalid():
            self.no_more_valid_moves = True
            print("No more valid moves. Game Over")
def test_isvalid():
    # Test to make sure isvalid() method functions
    # properly - returns the expected set with the valid
    # moves for the color at that turn
    gc = GameController(400, 400)
    bd = Board(4, 4, gc)
    assert bd.isvalid() == {(0, 1), (1, 0), (2, 3), (3, 2)}

    gc1 = GameController(400, 400)
    bd1 = Board(4, 4, gc1)
    bd1.table[0][1] = Disk(0, 1, 0)
    bd1.table[1][1] = Disk(1, 1, 0)
    bd1.color_flag = False
    assert bd1.isvalid() == {(0, 0), (2, 0), (0, 2)}
Пример #17
0
def generate_disks(n, rand_cv, static_cv, even_cv):
    ''' Populate disk list '''
    disks = []
    for i in range(n):
        if rand_cv:
            # Generate random cv and ensure it is even
            disks.append(Disk(random.randint(1, rand_cv), 0))
        elif static_cv:
            disks.append(Disk(static_cv, 0))
        elif even_cv:
            disks.append(Disk(random.randint(1, floor(even_cv / 2)) * 2, 0))
        else:
            disks.append(Disk(1, 0))

    return disks
Пример #18
0
def test_update():
    # call check function
    cw = Check_Win(matrix)
    dk1 = Disk("test")
    dk2 = Disk("test")
    dk3 = Disk("test")
    dk4 = Disk("test")
    # test horizontal
    cw.matrix[3][5] = dk1
    cw.matrix[4][5] = dk2
    cw.matrix[5][5] = dk3
    cw.matrix[6][5] = dk4
    # check the returned result
    result = cw.check_win()
    assert result == "test"
Пример #19
0
def init_disks(DISK_num, Latency_range):
    disk_id = 0
    disks = list()
    _min = Latency_range.get("min")
    _max = Latency_range.get("max")
    print("  min = " + str(_min) + ", max = " + str(_max))
    aver = (_min + _max) / 2
    sigma = (aver - _min) / 2  # 95% 的面积

    xli = list()
    yli = list()
    while disk_id < DISK_num:
        latency = int(round(random.gauss(aver, sigma)))
        if latency > 0 and latency < DISK_num:
            xli.append(disk_id)
            yli.append(latency)
            disk = Disk(disk_id, latency)
            disks.append(disk)
            disk_id = disk_id + 1

    # plt.figure()
    # plt.xticks(fontsize=14)
    # plt.yticks(fontsize=14)
    # plt.xlabel("disk", fontsize=14)
    # plt.ylabel("latency", fontsize=14)
    # plt.step(xli, yli, label="DISK-LATANCY", where="post")
    # plt.show()
    # print(len(disks))
    return disks
Пример #20
0
 def flip_tiles(self, x, y, is_black):
     """Flip tile colors in all eight directions.
     INT, INT -> BOOLEAN"""
     d = Disk(x, y, self.cell)
     position = (d.row, d.column)
     self._flip_tiles_one_dir(self._move_right(position), self._move_right,
                              is_black)
     self._flip_tiles_one_dir(self._move_left(position), self._move_left,
                              is_black)
     self._flip_tiles_one_dir(self._move_up(position), self._move_up,
                              is_black)
     self._flip_tiles_one_dir(self._move_down(position), self._move_down,
                              is_black)
     self._flip_tiles_one_dir(self._move_left_up(position),
                              self._move_left_up, is_black)
     self._flip_tiles_one_dir(self._move_left_down(position),
                              self._move_left_down, is_black)
     self._flip_tiles_one_dir(self._move_right_up(position),
                              self._move_right_up, is_black)
     self._flip_tiles_one_dir(self._move_right_down(position),
                              self._move_right_down, is_black)
     d.draw_black = is_black
     d.display()
     self.table[d.row][d.column] = d
     self.total_count += 1
     self.check_legal(self.gr.player_turn)
Пример #21
0
    def read_file(self):
        """Populate the simulation attrubutes"""
        with open(self.filename, encoding='utf-8') as file:
            json_file = json.load(file)

        cache_dict = json_file["Cache"]
        cache_params = get_param_list(cache_dict, CACHE_PARAMS)
        self.cache = Cache(*cache_params)

        tlb_dict = json_file["TLB"]
        tlb_params = get_param_list(tlb_dict, TLB_PARAMS)
        self.tlb = TLB(*tlb_params)

        memory_dict = json_file["MemoriaFisica"]
        memory_params = get_param_list(memory_dict, MEM_PARAMS)
        self.memory = Memory(*memory_params)

        disk_write = self.memory.write_speed * 10
        disk_read = self.memory.read_speed * 10
        self.disk = Disk(disk_write, disk_read)

        self.page_table_size = self.memory.frames * 2
        self.virtual_size = self.memory.size * 2
        self.bits_address = int(log(self.virtual_size, 2))
        self.bits_page = int(log(self.page_table_size, 2))

        programs = json_file["Programas"]
        for program_dic in programs:
            program_parameters = get_param_list(program_dic,
                                                ["Nombre", "Secuencia"])
            new_program = Program(*program_parameters, self.page_table_size)
            self.programs.append(new_program)
            self.program_map[new_program.id] = new_program
            self.stats[new_program.id] = ProgramStats()
Пример #22
0
def get_disk_info():
    du = psutil.disk_usage('/')
    pct_str = str(du.percent) + '%'
    disk = Disk(platform.platform(), size(du.total), size(du.used),
                size(du.free), pct_str)

    return get_response(disk)
Пример #23
0
 def play(self, x, y):
     """Put the disk, flipped the color and check legal space for the
     following disk"""
     self.grid[x][y] = Disk(x, y, self.color)
     self.flipover(x, y, self.color)
     self.change_color()
     self.check_legal_space(self.color)
Пример #24
0
    def player_make_move(self, x, y):
        self.legal_move = dict()  # reset the dictionary in every turn

        # get the x and y coordinates from the mouse click
        x = x // self.board.SPACING
        y = y // self.board.SPACING

        # find legal moves
        for i in range(len(self.board.spaces)):
            for item in self.board.spaces[i]:
                if item and item.color == BLACK:
                    self.find_moves(item, WHITE)

        # check if there is any legal move for the player.
        # if none, pass it to the AI.
        ## better to relocate these methods in game controller
        if not self.legal_move:
            self.turn = not self.turn
            self.no_player_moves = True
            self.turn_display("Computer's turn")
            return
        # update the player's move when every requirement is met.
        if (x, y) in self.legal_move and not self.board.spaces[x][y]:
            disk = Disk(BLACK, SPACING, DIAMATER, LOCATION, x, y)
            self.board.spaces[x][y] = disk
            disks_to_flip = self.legal_move[(x, y)]
            self.flip(disks_to_flip, BLACK)

            self.turn = not self.turn  # pass it to AI
            self.turn_display("Computer's turn")  # display that it's AI's turn
Пример #25
0
    def ai_make_move(self):
        self.legal_move = dict()  # reset the dictionary in every turn

        # find all the legal moves
        for i in range(len(self.board.spaces)):
            for item in self.board.spaces[i]:
                if item and item.color == WHITE:
                    self.find_moves(item, BLACK)

        # check if there are any legal moves for the AI.
        # if not, switch back to human player.
        if not self.legal_move:
            self.no_ai_moves = True
            self.turn = not self.turn
            self.turn_display("Player's turn")
            return
        # let the AI choose the "smartest" move
        ai_move = self.smart_ai(self.legal_move)

        # update the move: create the disk and flip the flippable steps
        disk = Disk(WHITE, SPACING, DIAMATER, LOCATION, ai_move[0], ai_move[1])
        self.board.spaces[ai_move[0]][ai_move[1]] = disk
        disks_to_flip = self.legal_move[ai_move]
        self.flip(disks_to_flip, WHITE)

        self.turn = not self.turn  # pass it to human player
        self.turn_display("Player's turn")  # display it's player's turn
Пример #26
0
def test_constructor():
    d = Disk(0, 0, 0, 200, 20)
    assert d.row == 0
    assert d.col == 0
    assert d.color == 0
    assert d.CELL_WIDTH == 200
    assert d.EDGE == 20
Пример #27
0
def construct_disk_list(file_name):
    disk_list = []
    with open(file_name, 'r') as file:
        for line in file:
            values = line.split()
            disk_list.append(Disk(values[0], values[1], values[2]))
    return disk_list
Пример #28
0
def main():
    """ Main Routine """

    print("\n[.] Initializing parameters/settings for simulator...")
    print("[.] Values in brackets represent reccommended/tested values.")
    print("[.] Using untested values may result in unstable behavior.\n")
    # Ask for parameters
    user_debug = input("[?] Enable debugging information [No]: ")
    debug = (user_debug == "Yes")
    memory_size = input("[?] Size of main memory (bytes) [100]: ")
    virtual_memory_size = input("[?] Size of virtual memory (bytes) [8000]: ")
    cache_size = input("[?] Size of cache (bytes)[40]: ")
    block_size = input("[?] Size of cache blocks (bytes)[4]: ")
    page_size = input("[?] Size of disk pages (bytes)[32]: ")
    table_size = input("[?] Number of TLB table entries (bytes)[10]: ")

    # Initialize components with bus and debug flag
    bus = Bus(debug)
    cpu = CPU(debug)
    cache = Cache(int(cache_size), int(block_size), debug)
    tlb = TLB(int(table_size), debug)
    memory = Memory(int(memory_size), int(virtual_memory_size), debug)
    disk = Disk(int(page_size), debug)

    # Initialize GUI
    menu = GUI(bus, cpu, cache, tlb, memory, disk, debug)
    menu.menu_loop()
Пример #29
0
    def run(self):
        if self.listProcess == []:
            reply = QMessageBox.information(self, 'SEM PROCESSOS',
                                            "Insira processos para rodar",
                                            QMessageBox.Ok)
            return
        self.file_open(True)

        self.quantum = self.quantum_sp.value()
        self.override = self.override_sp.value()
        self.type = self.comboCPU.currentText()
        self.typeMMU = self.comboMem.currentText()
        escalonator = Escalonator(self.type.upper(), self.override)
        self.processes = self.listProcess
        disk = Disk()
        vm = VirtualMemory(100, disk)
        mmu = MMU(vm, self.typeMMU.upper(), disk)
        io = IO(mmu, disk)
        io.escalonator = escalonator
        cpu = CPU(escalonator, mmu, io, self.quantum, disk=disk)
        escalonator.cpu = cpu
        n = len(self.processes)
        for i in self.processes:
            i.io = io
            escalonator.insertProcess(i)
            disk.insertProcess(i.id, i.numpages)

        escalonator.not_arrived.sort(key=lambda x: x.start)
        escalonator.queue()
        self.hide()
        self.gantt = Window_Gantt(n, cpu, escalonator, io, self.processes,
                                  self)
Пример #30
0
 def release_AI(self):
     '''release disk in the AI side'''
     # create AI side disk object
     self.disk_ball = Disk("Y")
     # randomly generate the column for dropping AI side disk
     # check if the column can drop AI side disk
     can_drop = True
     while can_drop:
         # column minus one as it's a closed range
         col = random.randint(0, (COLUMN - ONE))
         if not self.is_row_full(col):
             drop_height_index = self.matrix_update(col)
             # total disks in the matrix add 1
             self.total_disk += 1
             # end the while when can drop
             can_drop = False
         else:
             continue
     # pass x and y coordinates for AI side disk
     draw_x = col * ONE_HUDR + HALF_HUDR
     draw_y = HALF_HUDR
     self.disk_ball.draw_me(draw_x, draw_y)
     # calculate the targeted dropped height
     drop_height = MAX_DROP_HEIGHT - drop_height_index * ONE_HUDR
     # drop the disk
     self.disk_ball.down(drop_height)
     # trigger human side
     print("It's your turn:")
     self.countdown = COUNTDOWN
     self.ai_side = False