Пример #1
0
    def fill_board(self):
        for key in self.__letter_mapping:
            self[key + '7'] = Pawn(BLACK, self)
            self[key + '2'] = Pawn(WHITE, self)

        self['A1'] = Rook(WHITE, self)
        self['H1'] = Rook(WHITE, self)
        self['A8'] = Rook(BLACK, self)
        self['H8'] = Rook(BLACK, self)

        self['B1'] = Knight(WHITE, self)
        self['G1'] = Knight(WHITE, self)
        self['B8'] = Knight(BLACK, self)
        self['G8'] = Knight(BLACK, self)

        self['C1'] = Bishop(WHITE, self)
        self['F1'] = Bishop(WHITE, self)
        self['C8'] = Bishop(BLACK, self)
        self['F8'] = Bishop(BLACK, self)

        self['D1'] = Queen(WHITE, self)
        self['D8'] = Queen(BLACK, self)

        self['E1'] = King(WHITE, self)
        self['E8'] = King(BLACK, self)
Пример #2
0
    def play(self):
        """Metoda za pokretanje igre.

        Metoda se pokreće iz glavnog programa.

        Stavite opis metode, parametre i atribute, seealso i todo.
        """
        self.player = Knight()
        self._occupy_huts()
        acquired_hut_counter = 0

        self.show_game_mission()
        self.player.show_health(bold=True)

        while acquired_hut_counter < 5:
            try:
                idx = self._process_user_choice()
                self.player.acquire_hut(self.huts[idx - 1])

                if self.player.health_meter <= 0:
                    print_bold("Izgubili ste  :(")
                    break

                if self.huts[idx - 1].is_acquired:
                    acquired_hut_counter += 1
            except KeyboardInterrupt:
                print('nKorisnik je izašao iz igre.')
                # izadji iz programa
                sys.exit(1)

        if acquired_hut_counter == 5:
            print_bold("Cestitke! Pobijedili ste!!!")
Пример #3
0
    def add_pieces(self):
        """ Appends the proper pieces and locations to each team list.
        
        Team lists are used to get the possible moves and easily
        check the capture status of a piece.
        """

        self.wp.append(King(4, 7, True))
        self.wp.append(Queen(3, 7, True))
        self.wp.append(Rook(0, 7, True))
        self.wp.append(Rook(7, 7, True))
        self.wp.append(Knight(1, 7, True))
        self.wp.append(Knight(6, 7, True))
        self.wp.append(Bishop(2, 7, True))
        self.wp.append(Bishop(5, 7, True))
        for i in range(8):
            self.wp.append(Pawn(i, 6, True))

        self.bp.append(King(4, 0, False))
        self.bp.append(Queen(3, 0, False))
        self.bp.append(Rook(0, 0, False))
        self.bp.append(Rook(7, 0, False))
        self.bp.append(Knight(1, 0, False))
        self.bp.append(Knight(6, 0, False))
        self.bp.append(Bishop(2, 0, False))
        self.bp.append(Bishop(5, 0, False))
        for i in range(8):
            self.bp.append(Pawn(i, 1, False))
Пример #4
0
def test_white_knight(test_board):
    starting_file = "b"
    starting_rank = 1
    starting_space = test_board.get_space(starting_file, starting_rank)
    test_knight = Knight(PieceColor.WHITE)
    test_knight.place(starting_space)
    return test_knight
Пример #5
0
def test_black_knight(test_board):
    starting_file = "b"
    starting_rank = 8
    starting_space = test_board.get_space(starting_file, starting_rank)
    test_knight = Knight(PieceColor.BLACK)
    test_knight.place(starting_space)
    return test_knight
Пример #6
0
    def __init__(self):
        self.board = [[None for j in range(8)] for i in range(8)]
        self.pieces = []
        
        # set white board
        pieces = []
        for i in range(8):
            pieces.append(Pawn(i, 1, COLOR.WHITE))
        pieces.append(Rook(0, 0, COLOR.WHITE))
        pieces.append(Rook(7 ,0, COLOR.WHITE))
        pieces.append(Knight(1, 0, COLOR.WHITE))
        pieces.append(Knight(6, 0, COLOR.WHITE))
        pieces.append(Bishop(2, 0, COLOR.WHITE))
        pieces.append(Bishop(5, 0, COLOR.WHITE))
        pieces.append(King(3, 0, COLOR.WHITE))
        pieces.append(Queen(4, 0, COLOR.WHITE))

        #set black peices
        for i in range(8):
            pieces.append(Pawn(i, 6, COLOR.BLACK))
        pieces.append(Rook(0, 7, COLOR.BLACK))
        pieces.append(Rook(7 ,7, COLOR.BLACK))
        pieces.append(Knight(1, 7, COLOR.BLACK))
        pieces.append(Knight(6, 7, COLOR.BLACK))
        pieces.append(Bishop(2, 7, COLOR.BLACK))
        pieces.append(Bishop(5, 7, COLOR.BLACK))
        pieces.append(King(3, 7, COLOR.BLACK))
        pieces.append(Queen(4, 7, COLOR.BLACK))

        for _piece in pieces:
            self.pieces.append(_piece)
            self.board[_piece._x][_piece._y] = _piece
Пример #7
0
    def init_board(self):
        new_b = []
        for i in range(64):
            # white
            if i == 0 or i == 7:
                new_b.append(Tile(Rook('W')))
            elif i == 1 or i == 6:
                new_b.append(Tile(Knight('W')))
            elif i == 2 or i == 5:
                new_b.append(Tile(Bishop('W')))
            elif i == 3:
                new_b.append(Tile(Queen('W')))
            elif i == 4:
                new_b.append(Tile(King('W')))
            elif i >= 8 and i <= 15:
                new_b.append(Tile(Pawn('W')))
            # black
            elif i == 56 or i == 63:
                new_b.append(Tile(Rook('B')))
            elif i == 57 or i == 62:
                new_b.append(Tile(Knight('B')))
            elif i == 58 or i == 61:
                new_b.append(Tile(Bishop('B')))
            elif i == 59:
                new_b.append(Tile(Queen('B')))
            elif i == 60:
                new_b.append(Tile(King('B')))
            elif i >= 48 and i <= 55:
                new_b.append(Tile(Pawn('B')))
            # empty
            else:
                new_b.append(Tile())

        return new_b
Пример #8
0
 def test_knight_attacks(self):
     knight1 = Knight(Colour.WHITE, (4, 4))
     pawn1 = Pawn(Colour.WHITE, (3, 6))
     pawn2 = Pawn(Colour.BLACK, (3, 2))
     pawn3 = Pawn(Colour.BLACK, (3, 3))
     self.assertEquals(set(knight1.list_attacks([pawn1, pawn2, pawn3])),
                           set([(3, 2)]))
Пример #9
0
def parse(fin):
    white_pieces = []
    black_pieces = []
    with open(fin, "r") as file_in:
        lines = file_in.read().splitlines()
        for line in lines:
            if int(line[-1:]) > 0:
                for idx in range(0, int(line[-1:])):
                    if (line[-7:-2] == 'WHITE'):
                        temp = line[:-8]
                        if (temp == 'BISHOP'):
                            white_pieces.append(Bishop(Position(), True))
                        elif (temp == 'KNIGHT'):
                            white_pieces.append(Knight(Position(), True))
                        elif (temp == 'QUEEN'):
                            white_pieces.append(Queen(Position(), True))
                        elif (temp == 'ROOK'):
                            white_pieces.append(Rook(Position(), True))

                    elif (line[-7:-2] == 'BLACK'):
                        temp = line[:-8]
                        if (temp == 'BISHOP'):
                            black_pieces.append(Bishop(Position(), False))
                        elif (temp == 'KNIGHT'):
                            black_pieces.append(Knight(Position(), False))
                        elif (temp == 'QUEEN'):
                            black_pieces.append(Queen(Position(), False))
                        elif (temp == 'ROOK'):
                            black_pieces.append(Rook(Position(), False))

    file_in.close()
    return white_pieces, black_pieces
Пример #10
0
    def _init_pieces(self):
        if not self._positions:
            king = King(color=self._color)
            self._positions.update({str(king.position): king})

            queen = Queen(color=self._color)
            self._positions.update({str(queen.position): queen})

            for i in range(1, 9):
                pawn = Pawn(self._color, col=i)
                self._positions.update({str(pawn.position): pawn})

            knight = Knight(self._color, col=2)
            self._positions.update({str(knight.position): knight})

            knight = Knight(self._color, col=7)
            self._positions.update({str(knight.position): knight})

            rook = Rook(self._color, col=1)
            self._positions.update({str(rook.position): rook})

            rook = Rook(self._color, col=8)
            self._positions.update({str(rook.position): rook})

            bishop = Bishop(self._color, col=3)
            self._positions.update({str(bishop.position): bishop})

            bishop = Bishop(self._color, col=6)
            self._positions.update({str(bishop.position): bishop})
Пример #11
0
    def play(self):
        """Workhorse method to play the game.

        Controls the high level logic to play the game. This is called from
        the main program to begin the game execution.
        """
        self.player = Knight()
        self._occupy_huts()
        acquired_hut_counter = 0

        self.show_game_mission()
        self.player.show_health(bold=True)

        while acquired_hut_counter < 5:
            idx = self._process_user_choice()
            self.player.acquire_hut(self.huts[idx-1])

            if self.player.health_meter <= 0:
                print_bold("YOU LOSE  :(  Better luck next time")
                break

            if self.huts[idx-1].is_acquired:
                acquired_hut_counter += 1

        if acquired_hut_counter == 5:
            print_bold("Congratulations! YOU WIN!!!")
Пример #12
0
    def play(self):
        self.player = Knight()
        self.occupy_huts()
        # 确认木屋全部检查过
        acquire_hut_count = 0

        # 游戏人物及人物血量
        self.show_game_mission()
        self.player.show_health(bold=True)

        # 开始War
        while acquire_hut_count < 5:
            # 玩家选择攻占的木屋
            idx = self._process_user_choice()
            # 开始占据木屋
            self.player.acquire_hut(self.huts[idx-1])

            # 结束条件
            if self.player.health_meter <= 0:
                print("You Lose, Better luck next time!")
                break

            if self.huts[idx-1].is_acquire:
                acquire_hut_count += 1

        if acquire_hut_count == 5:
            print("Congratulation for you! You Win!!!")
Пример #13
0
 def __init__(self):
     self._running = True
     self.screen = pygame.display.set_mode((self.W, self.H))
     pygame.display.set_caption('Lovag')
     self.bg = Background(self.W, self.H, self.sizeFaktorX, self.sizeFaktorY)
     self.kn = Knight(self.W, self.H, self.sizeFaktorX, self.sizeFaktorY)
     self.clock = None
Пример #14
0
    def test_attack_by_hand(self):
        # in-line setup
        knight = Knight(100)

        # exercise
        pain = knight.attack_power()

        # verify
        self.assertEqual(pain, Hand().attack_power())
Пример #15
0
def main():
    """Executes the main application.

    Keyword arguments:
    <None>
    """
    # Instantiate the x & y position variables.
    x = 9
    y = 9

    # Take x & y initial inputs. Loop while invalid.
    while (x < 1 or x > BOARD_SIZE) or (y < 1 or y > BOARD_SIZE):
        x, y = input("Enter x & y (1-" + str(BOARD_SIZE)
                     + ") separated by a space (e.g. 4 4): ").split()
        x, y = [int(x), int(y)]

        if x < 1 or x > BOARD_SIZE:
            print("ERROR:: x must be 1-" + str(BOARD_SIZE))

        if y < 1 or y > BOARD_SIZE:
            print("ERROR:: y must be 1-" + str(BOARD_SIZE))

    print()

    # Create a Knight object to move around the board.
    knight = Knight(x, y)

    # Instantiate a board and set the initial Knight position with move 1.
    board = Board(BOARD_SIZE)
    board.place_knight(1, knight.x, knight.y)

    # Test special cases for all the moves.
    for current_move in range(2, MAX_MOVES + 1):
        num_possibilities, next_x, next_y = get_num_possibilities(knight, board)
        min_exits_idx = 0

        # If there are no possibilities left, then end the tour prematurely.
        if num_possibilities == 0:
            print("The knight's tour ended prematurely at (" + str(knight.x + 1)
                  + "," + str(knight.y + 1) + ") during move #"
                  + str(current_move - 1) + ".")
            print()
            break
        
        # If there is more than 1 possibility, then find the next squares with the
        # minimum number of exits.
        elif num_possibilities > 1:
            exits = find_min_exits(board, num_possibilities, next_x, next_y)
            min_exits_idx = get_idx_smallest_num_exits(num_possibilities, exits)

        # Move the knight and mark its position on the board.     
        knight.move(next_x[min_exits_idx], next_y[min_exits_idx])
        board.place_knight(current_move, knight.x, knight.y)

    # Print out the board.
    board.print_board()
Пример #16
0
    def test_attack_by_knife(self):
        # in-line setup
        knight = Knight(100)
        knight.arms = Knife()

        # exercise
        pain = knight.attack_power()

        # verify
        self.assertEqual(pain, Knife().attack_power())
Пример #17
0
def main():
    """Executes the main application."""
    # Instantiate the x & y co-ordinates. Note that 9 and 9 are 'off the board' and therefore invalid.
    x = 9
    y = 9

    # Take x & y User input. For error tolerance, Loop until we receive a valid input (i.e. cannot start the Knight 'off' the board).
    while (x < 1 or x > BOARD_SIZE) or (y < 1 or y > BOARD_SIZE):
        x, y = input(
            "Enter the Knight's starting position as X & Y co-ordinates (1-" +
            str(BOARD_SIZE) + ") separated by a space (e.g. 4 4): ").split()
        x, y = [int(x), int(y)]

        if x < 1 or x > BOARD_SIZE:
            print("ERROR::Invalid input: x must be 1-" + str(BOARD_SIZE))

        if y < 1 or y > BOARD_SIZE:
            print("ERROR::Invalid input: y must be 1-" + str(BOARD_SIZE))

    print()

    # Create a Knight object at the given X,Y input.
    knight = Knight(x, y)

    # Instantiate the board. The Knight's initial position (input) is given with move 1.
    board = Board(BOARD_SIZE)
    board.place_knight(1, knight.x, knight.y)

    #  Test for all valid possible moves and special cases.
    for current_move in range(2, MAX_MOVES + 1):
        num_possibilities, next_x, next_y = get_num_possibilities(
            knight, board)
        min_exits_idx = 0  #index of minimum number of exits

        # If there are no possibilities left, then end the tour prematurely. Special case that doesn't come up often.
        if num_possibilities == 0:
            print("The knight's tour ended prematurely at (" +
                  str(knight.x + 1) + "," + str(knight.y + 1) +
                  ") during move #" + str(current_move - 1) + ".")
            print()
            break

        # If there's more than 1 move possible, find next tile with the
        # fewest number of exits. This is the core of Warndorff's Rule.
        elif num_possibilities > 1:
            exits = find_min_exits(board, num_possibilities, next_x, next_y)
            min_exits_idx = get_idx_smallest_num_exits(num_possibilities,
                                                       exits)

        # Move the knight, marking its location on the board.
        knight.move(next_x[min_exits_idx], next_y[min_exits_idx])
        board.place_knight(current_move, knight.x, knight.y)

    # Print the board to the console. The board is represented as a move map.
    board.print_board()
Пример #18
0
 def load_knight(hue):
     knight_x, knight_y = self.map.get_coordinates(9 * hue, 9 * hue)
     direction = hue and Direction.WEST or Direction.SOUTH
     knight = Knight(knight_x, knight_y, direction)
     knight.zindex=10
     knight.color = 255 - (150 * hue), 255 - (150 * ((hue + 1) % 2)), 255
     mage_x, mage_y = self.map.get_coordinates(7 * hue + 1, 7 * hue + 1)
     mage = Mage(mage_x, mage_y, direction)
     mage.zindex=10
     mage.color = 255 - (150 * hue), 255 - (150 * ((hue + 1) % 2)), 255
     return [knight, mage]
Пример #19
0
 def load_knight(hue):
     knight_x, knight_y = self.map.get_coordinates(9 * hue, 9 * hue)
     direction = hue and Direction.WEST or Direction.SOUTH
     knight = Knight(knight_x, knight_y, direction)
     knight.zindex = 10
     knight.color = 255 - (150 * hue), 255 - (150 *
                                              ((hue + 1) % 2)), 255
     mage_x, mage_y = self.map.get_coordinates(7 * hue + 1, 7 * hue + 1)
     mage = Mage(mage_x, mage_y, direction)
     mage.zindex = 10
     mage.color = 255 - (150 * hue), 255 - (150 * ((hue + 1) % 2)), 255
     return [knight, mage]
Пример #20
0
def enter():
    gfw.world.init(['bg_base', 'bg_back', 'bg_platform', 'platform', 'enemy', 'hornet', 'needle', 'knight', 'slash', 'bg_front', 'ui'])

    bg_base = FixedBackground('res/map/base.png')
    gfw.world.add(gfw.layer.bg_base, bg_base)
    bg_back = FixedBackground('res/map/back.png')
    gfw.world.add(gfw.layer.bg_back, bg_back)
    bg_platform = FixedBackground('res/map/platform.png')
    gfw.world.add(gfw.layer.bg_platform, bg_platform)
    bg_front = FixedBackground('res/map/front.png')
    gfw.world.add(gfw.layer.bg_front, bg_front)

    global platform
    platform = Platform('res/map/platform.json')
    for r in platform.rects:
        r.bg = bg_platform
        gfw.world.add(gfw.layer.platform, r)

    crawlid = Crawlid()
    crawlid.bg = bg_platform
    gfw.world.add(gfw.layer.enemy, crawlid)

    global knight
    knight = Knight()
    knight.bg = bg_platform

    bg_back.target = knight
    bg_platform.target_bg = bg_back
    bg_front.target_bg = bg_back

    bg_back.update()
    bg_platform.update()
    bg_front.update()
    gfw.world.add(gfw.layer.knight, knight)

    global frame
    frame = Frame(knight)
    gfw.world.add(gfw.layer.ui, frame)

    global hornet
    hornet = Hornet()
    hornet.bg = bg_platform
    hornet.target = knight
    gfw.world.add(gfw.layer.hornet, hornet)

    global bgm, opening_sting, enemy_damaged
    bgm = gfw.sound.load_m('res/Sound/cave_wind_loop.mp3')
    opening_sting = gfw.sound.load_w('res/Sound/S75 Opening Sting-08.wav')
    enemy_damaged = gfw.sound.load_w('res/Sound/enemy_damage.wav')

    opening_sting.set_volume(50)
    bgm.repeat_play()
    opening_sting.play()
Пример #21
0
    def setup_game_scenario(self):
        """Create player and huts and then randomly pre-occupy huts.

        The huts might be ledt empty as weel. This method also prints the game
        mission which could be refactored out of this as an exercise.

        .. seealso:: :py:meth: `self.play`,
                     :py:meth: `self._occupy_huts`
        """
        self.player = Knight()
        self._occupy_huts()
        self.show_game_mission()
        self.player.show_health(bold=True)
Пример #22
0
class KnightTest(unittest.TestCase):

    def setUp(self) -> None:
        self.attacker = Knight(100)
        self.attackee = SpyKnight()

    def test_attack_by_hand(self):
        # exercise
        self.attacker.attack(self.attackee)

        # verify
        self.assertTrue(self.attackee.is_hp_called)
        self.assertTrue(self.attackee.is_defense_called)
Пример #23
0
    def test_knight_jump(self, test_board, test_white_knight):
        assert test_board
        assert test_white_knight
        assert test_white_knight.current_space

        # Place Knights on the two spaces in front of the test Knight to check that the
        # test Knight is able to jump over them, i.e. their presence along the Knight's movement
        # path do not prevent the Knight from legally making the move, and that the
        # pieces along the path remain where they were after the Knight is done with its move.

        current_space = test_white_knight.current_space
        ahead = test_board.get_space(current_space.file,
                                     current_space.rank + 1)
        two_ahead = test_board.get_space(current_space.file,
                                         current_space.rank + 2)
        target = test_board.get_space(chr(ord(current_space.file) + 1),
                                      current_space.rank + 2)

        first_obstacle_knight = Knight(PieceColor.WHITE)
        first_obstacle_knight.place(ahead)
        second_obstacle_knight = Knight(PieceColor.BLACK)
        second_obstacle_knight.place(two_ahead)

        test_white_knight.move(target)
        assert test_white_knight.current_space is target
        assert first_obstacle_knight.current_space is ahead
        assert second_obstacle_knight.current_space is two_ahead
Пример #24
0
    def fightImplementation(self):
        # [0] is knightHp, [1] is knightLevel, [2] is knightRingSign, [3] is journeyList
        knight = Knight(self.knightTuple[0], self.knightTuple[1],
                        self.knightTuple[2], self.knightTuple[3])

        # Get knight ring sign list
        knightRingSignList = knight.getRingSignList()

        index = 1
        for journey in knight.getJourneyList():
            #Get knight Hp
            knightHp = knight.getKnightHp()
            # If knight Hp <= 0 => Lose the game
            if knightHp <= 0: break
            # Get index of the journey
            indexJourney = index
            # Increase index
            index += 1

            # Create event object
            # print(str(journey) + " " + str(indexJourney))
            eventObj = Event(journey, indexJourney)

            # [0] is code, [1] is levelO, [2] is ringSignO
            eventTuple = eventObj.processEvent()

            # Get Event
            event = eventTuple[0]

            # Case finish journey
            if event == 0:
                print("Knight finish the competition !")
                break
            # Case pass journey
            elif event == -1:
                continue

            knightRingSignList, knightHp = self.processBattleCase(
                event, knightHp, knight.getKnightMaxHp(),
                knight.getKnightLevel(), knightRingSignList,
                eventObj.getLevelO(), eventObj.getRingSignO())

            knight.setKnightHp(knightHp)

        # print(knight.getRingSignList())
        stringRingSignList = [str(x) for x in knightRingSignList]
        stringRingSignList = "".join(stringRingSignList)

        return stringRingSignList, knight.getKnightHp()
Пример #25
0
 def setBoard(self, fen):
     row, column = 0, 0
     for character in fen:
         if character == 'R':
             self.addPiece(Rook(column, row, 'w', self.board.board))
             column += 1
         elif character == 'r':
             self.addPiece(Rook(column, row, 'b', self.board.board))
             column += 1
         elif character == 'N':
             self.addPiece(Knight(column, row, 'w', self.board.board))
             column += 1
         elif character == 'n':
             self.addPiece(Knight(column, row, 'b', self.board.board))
             column += 1
         elif character == 'B':
             self.addPiece(Bishop(column, row, 'w', self.board.board))
             column += 1
         elif character == 'b':
             self.addPiece(Bishop(column, row, 'b', self.board.board))
             column += 1
         elif character == 'P':
             self.addPiece(Pawn(column, row, 'w', self.board.board))
             column += 1
         elif character == 'p':
             self.addPiece(Pawn(column, row, 'b', self.board.board))
             column += 1
         elif character == 'K':
             self.addPiece(King(column, row, 'w', self.board.board))
             column += 1
         elif character == 'k':
             self.addPiece(King(column, row, 'b', self.board.board))
             column += 1
         elif character == 'Q':
             self.addPiece(Queen(column, row, 'w', self.board.board))
             column += 1
         elif character == 'q':
             self.addPiece(Queen(column, row, 'b', self.board.board))
             column += 1
         elif character == '/':
             column = 0
             row += 1
         else:
             if character >= '1' and character <= '9':
                 column += int(character)
             elif character == ' ':
                 i = fen.index(character) + 1
                 self.whitesTurn = True if fen[i] == 'w' else False
                 return
Пример #26
0
    def battle(self):

        # Set knight attribute
        knight = Knight(self.knightTuple[0], self.knightTuple[1],
                        self.knightTuple[2], self.knightTuple[3])

        knightRingSignList = knight.getRingSignList()

        index = 1

        for journey in knight.getJourneyList():

            knightHp = knight.getKnightHP()

            # If knight Hp <= 0 => Lose the game
            if knightHp <= 0:
                print("Knight lose")
                break

            # Get journey index
            indexJourney = index

            index += 1

            # print(str(journey) + " " + str(indexJourney))
            eventObj = Event(journey, indexJourney)

            eventTuple = eventObj.checkEventCode()

            event = eventTuple[0]

            if event == 0:
                print("Knight win")
                break
            elif event == -1:
                continue

            knightRingSignList, knightHp = self.battleCase(
                event, knightHp, knight.getKnightMaxHp(),
                knight.getKnightLevel(), knightRingSignList,
                eventObj.getLevelO(), eventObj.getRingSignO())

            knight.setKnightHp(knightHp)

        # print(knight.getRingSignList())
        stringRingSignList = [str(x) for x in knightRingSignList]
        stringRingSignList = "".join(stringRingSignList)

        return stringRingSignList, knight.getKnightHP()
Пример #27
0
 def process_send_knights_orders(self):
     if self.orders.__len__() > 0:
         order = self.orders[0]
         self.gs.add_knight(Knight(order.road, self.team, self.gs))
         order.knights_to_send -= 1
         if order.knights_to_send == 0:
             self.orders.remove(order)
Пример #28
0
 def check_encounter(self, hero):
     #randomized value to determine if a user meets a enemy
     if (randint(0, 100) <= (self.encounter_rate * 100)):
         #create new enemy and pop a name from the list
         #if the list is empty then enter the final boss
         if (len(self.enemy_names) > 0):
             enemy_temp = self.enemy_names.pop()
             enemy = None
             _type = enemy_temp["type"]
             _name = enemy_temp["name"]
             if (_type == "warrior"):
                 print("You have encountered {} the warrior".format(_name))
                 enemy = Warrior(_name, False)
             elif (_type == "knight"):
                 print("You have encountered {} the knight".format(_name))
                 enemy = Knight(_name, "", False)
             elif (_type == "sorceress"):
                 print(
                     "You have encountered {} the sorceress".format(_name))
                 enemy = Sorceress(_name, False)
             elif (_type == "theif"):
                 print("You have encountered {} the theif".format(_name))
                 enemy = Theif(_name, False)
             for i in range(hero.level + self.level_inc):
                 enemy.level_up()
             return hero.enter_battle(enemy)
         else:
             return self.summon_boss(hero)
     print("Nothing around here...")
     return True
    def test_init(self):
        # test valido
        xs = [chr(ord('a') + i) for i in range(0, 8)]
        ys = [i for i in range(1, 8)]
        for x, y in product(xs, ys):
                k = Knight(x, y)
                moves = list(product([ord(x) - 1, ord(x) + 1], [y - 2, y + 2])) + list(product([ord(x) - 2, ord(x) + 2], [y - 1, y + 1]))
                result_moves = []
                for x, y in moves:
                    if ord('a') <= x <= ord('h') and 1 <= y <= 8:
                        result_moves.append((chr(x), y))

                try:
                    self.assertTrue(sorted(result_moves) == sorted(k.possible_poss()))
                except:
                    print(f'Somethings wrong...')
Пример #30
0
        def action(self):
            factory = self.__outer.unit()
            garrison = factory.structure_garrison()
            if garrison:
                direction = random.choice(list(bc.Direction))
                if self.__outer._gc.can_unload(factory.id, direction):
                    self.__outer._gc.unload(factory.id, direction)

                    location = factory.location.map_location().add(direction)
                    unit = self.__outer._gc.sense_unit_at_location(location)

                    if unit:  # TODO: Add other unit types' tree containers
                        strategy.Strategy.getInstance().removeInProduction(
                            unit.unit_type)
                        strategy.Strategy.getInstance().addUnit(unit.unit_type)
                        if unit.unit_type == bc.UnitType.Worker:
                            self.__outer._my_units.append(
                                Worker(unit.id, self.__outer._gc,
                                       self.__outer._maps,
                                       self.__outer._my_units))
                        elif unit.unit_type == bc.UnitType.Knight:
                            self.__outer._my_units.append(
                                Knight(unit.id, self.__outer._gc))
                        elif unit.unit_type == bc.UnitType.Healer:
                            self.__outer._my_units.append(
                                Healer(unit.id, self.__outer._gc,
                                       self.__outer._maps))
                        elif unit.unit_type == bc.UnitType.Ranger:
                            self.__outer._my_units.append(
                                Ranger(unit.id, self.__outer._gc))
                        elif unit.unit_type == bc.UnitType.Mage:
                            self.__outer._my_units.append(
                                Mage(unit.id, self.__outer._gc,
                                     self.__outer._maps))
            self._status = bt.Status.SUCCESS
Пример #31
0
def run_game():
    pygame.init()

    sk_settings = Settings()
    background = pygame.image.load('images/freetileset/png/BG/BG.png')
    background = pygame.transform.smoothscale(
        background, (sk_settings.window_width, sk_settings.window_height))
    screen = pygame.display.set_mode(
        (sk_settings.window_width, sk_settings.window_height))

    pygame.display.set_caption('Super Knight')
    fps = pygame.time.Clock()
    knight = Knight(sk_settings, screen)

    sword_container = GroupSingle()
    arrows_right = Group()
    arrows_left = Group()
    zombies_top = Group()
    zombies_bottom = Group()
    zombies_left = Group()
    zombies_right = Group()
    gf.populate_zombies(sk_settings, screen, zombies_top, zombies_bottom,
                        zombies_left, zombies_right)

    while True:
        # everything redrawn every loop before flip called.
        # Step 1: Check for user input
        gf.check_events(sk_settings, screen, knight, arrows_right, arrows_left,
                        sword_container)

        # Step 2: Apply user input to game objects
        knight.update()
        gf.update_zombies(sk_settings, screen, knight, arrows_right,
                          arrows_left, zombies_top, zombies_bottom,
                          zombies_left, zombies_right)
        gf.update_arrows(sk_settings, screen, knight, arrows_right,
                         arrows_left, zombies_top, zombies_bottom,
                         zombies_left, zombies_right)
        gf.update_sword(sk_settings, screen, knight, sword_container,
                        zombies_top, zombies_bottom, zombies_left,
                        zombies_right)

        # Step 3: Redraw changes to game objects on the screen
        gf.update_screen(sk_settings, screen, knight, arrows_right,
                         arrows_left, fps, zombies_top, zombies_bottom,
                         zombies_left, zombies_right, background,
                         sword_container)
Пример #32
0
 def play(self):
     self.show_mission()
     dotted_line()
     self._occupy_huts()
     # continu_play=True
     self.player = Knight()
     occupant_nums = 0  #已占领数量
     while occupant_nums < 5:
         idx = self._play_choose()
         self.player.acquire_hut(self.huts[idx - 1])
         if self.player.health_meter <= 0:
             print('You lost:(better luck next time')
             break
         if self.huts[idx - 1].is_acquired:
             occupant_nums += 1
     if occupant_nums == 5:
         print_bold('\nCongratulation! you win')
Пример #33
0
 def _create_knight(self, knight_level=None):
     """
     Проверка на появление рыцаря.
     """
     from knight import Knight
     if knight_level is None:
         knight_level = Knight.start_level(self.dragon.reputation.level)
     if knight_level > 0:
         self.knight = Knight(level=knight_level,
                            gameRef=self, 
                            base_character=self.adv_character)
     else:
         self.knight = None
Пример #34
0
# board size
#N = int(sys.argv[1])


sizes = [5, 8, 16, 32, 64, 128, 256, 512, 1024]
for N in sizes:
	print "#############"
	print "%d=%d" % (N, N*N)
	print "#############"
	results = []
	sum_time2 = 0.0
	sum_time = 0.0
	for i in xrange(0, 30):

		#start = current_milli_time()
		# knights tour
		b = Board(N)
		k = Knight(b)
		r = k.knightsPath()
		#end = current_milli_time()
		#t = end-start

		#sum_time2 += t*t
		#sum_time += t
		results.append(r);

	#variance = (sum_time2 - (sum_time*sum_time)/30)/30-1;
	#standardDeviation = sqrt(variance);
	#print "Total time: %fms / Average time: %fms / Standard Deviation: %fms" % (sum_time,sum_time/30.0,standardDeviation)
	print results