Beispiel #1
0
    def generate_initial_board(self):
        generator = Generate()
        fields = generator.generate_all_ships_positions()
        self.computer = AI(fields)
        field_id = 1
        for field_row in fields:
            for field in field_row:
                background_color = utils.get_color_from_hex('#66e0ff')  # water
                if field == 2:
                    background_color = utils.get_color_from_hex('#a6a6a6')  # ship
                # if field == FieldType.Occupied:
                #     background_color = utils.get_color_from_hex('#ffff00')  # occupied

                field_button = Button(
                    id=str(field_id),
                    text=str(field),
                    background_color=background_color)

                if not self.is_computer:
                    field_button.bind(on_release=self.player_hit_field)
                self.add_widget(field_button)
                field_id += 1
        if self.is_computer:
            self.add_widget(Label(text="PLANSZA GRACZA", text_size=(300, None), halign='right'))
        else:
            self.add_widget(Label(text="PLANSZA KOMPUTERA", text_size=(300, None), halign='right'))
Beispiel #2
0
def index():
    if request.method == 'POST':
        if request.method == 'POST':
            # check if the post request has the file part
            print('received')
            print(str(request.files))
            file = request.files['wavFile']
            # if user does not select file, browser also
            # submit an empty part without filename
            if file.filename == '':
                print('no file')
                flash('No selected file')
                return redirect(request.url)
            print('GOOD')
            filename = file.filename
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        name = file.filename
        bass, vocal, originality = main(name)
        feat = ',' in request.form['artistNames']
        instrument = request.form['mainInstrument']
        #get all the values

        conn = get_db_connection()
        exists = len(
            conn.execute('SELECT * FROM songs WHERE name=?',
                         (name, )).fetchall()) > 0
        print(f'exitsts={exists}')
        if not exists:
            conn.execute(
                "INSERT INTO songs (name,bass,feat,vocal,instrument,originality) VALUES (?,?,?,?,?,?)",
                (name, bass, feat, vocal, instrument,
                 originality))  #params are added as second param
            conn.commit()
            print('inserted!')
        conn.close()

        songObj = Song(name, bass, feat, vocal, instrument, originality)
        isBop = AI(songObj)
        if isBop:
            predictionString = 'It IS a bop!'
        else:
            predictionString = 'It IS NOT a bop!'
        return render_template('index.html',
                               prediction=predictionString,
                               feedback=url_for('feedback'))
    return render_template(
        'index.html',
        prediction="Please upload a file to get your prediction!",
        feedback='#')
Beispiel #3
0
    def __init__(self, actorJSON):
        import Engine.RoomEngine
        import Engine.ActorEngine
        from Inventory.ActorInventory import ActorInventory
        from AI.AI import AI

        EventReceiver.__init__(self)

        attributes = {
            'id': '',
            'name': '',
            'description': [],
            'race': 'Human',
            'gender': '',
            'roomID': '0',
            'stats': {
                'strength': 0,  #physical skills, inventory limit
                'constitution': 0,  #combat tree, max hp
                'agility': 0,  #stealth tree, dodging
                'energy': 0,  #magic skills, max mana
                'focus': 0,  #psionic skills, mana regen
                'awareness': 0,  #traps tree, searching
                'ingenuity': 0,  #crafting tree, critical hits
                'composure': 0  #support tree, hp regen
            },
            'currentHP': 0,
            'maxHP': 0,
            'currentMana': 0,
            'maxMana': 0,
            'eventAdjusters': {},
            'eventHandlers': {},
            'inventory': None
        }

        out_adjusters = []
        inventory = None

        if actorJSON != None:
            for key in actorJSON.keys():
                if key == 'inventory':
                    inventory = actorJSON[key]
                elif key == 'eventHandlers':
                    for element in actorJSON[key]:
                        adjusters = (
                            lambda dictionary: dictionary.has_key('adjusters')
                            and dictionary['adjusters'] or None)(element)

                        self.addEventHandlerByNameWithAdjusters(
                            element['name'], adjusters)
                elif key == 'out_adjusters':
                    out_adjusters = actorJSON[key]
                elif key == 'AI':
                    self.attributes['AI'] = AI(actorJSON[key])
                else:
                    attributes[key] = actorJSON[key]

            for key in attributes.keys():
                self.attributes[key] = attributes[key]

            Engine.ActorEngine.addEventSubscriber(self)

            startingRoom = Engine.RoomEngine.getRoom(self.attributes['roomID'])

            startingRoom.addEventSubscriber(self)

            self.addEventHandlerByNameWithAdjusters(
                'Actor.EventHandlers.Actor.ActorAttemptedDropHandler', None)
            self.addEventHandlerByNameWithAdjusters(
                'Actor.EventHandlers.Actor.ItemDroppedHandler', None)
            self.addEventHandlerByNameWithAdjusters(
                'Actor.EventHandlers.Actor.ActorInitiatedItemGrabHandler',
                None)
            self.addEventHandlerByNameWithAdjusters(
                'Actor.EventHandlers.Actor.ActorGrabbedItemHandler', None)
            self.addEventHandlerByNameWithAdjusters(
                'Actor.EventHandlers.Actor.ActorAttemptedItemEquipHandler',
                None)
            self.addEventHandlerByNameWithAdjusters(
                'Actor.EventHandlers.Actor.ActorAttemptedItemRemovalHandler',
                None)
            self.addEventHandlerByNameWithAdjusters(
                'Actor.EventHandlers.Actor.ActorMovedFromRoomEventHandler',
                None)
            self.addEventHandlerByNameWithAdjusters(
                'Actor.EventHandlers.Actor.ActorGainedHealthFromTickHandler',
                None)

        #add event handlers specific to this actor's race

        filePath = '{}/Content/races/{}.txt'.format(currentDir,
                                                    self.attributes['race'])
        raceFile = open(filePath, 'r')
        jsonString = raceFile.read()
        jsonObj = json.loads(jsonString)
        handlers = jsonObj['eventHandlers']

        if jsonObj.has_key('out_adjusters'):
            out_adjusters = out_adjusters + jsonObj['out_adjusters']

        raceFile.close()

        for handler in handlers:
            adjusters = (lambda dictionary: dictionary.has_key('adjusters') and
                         dictionary['adjusters'] or None)(handler)

            self.addEventHandlerByNameWithAdjusters(handler['name'], adjusters)

        EventEmitter.__init__(self, out_adjusters)

        if inventory != None:
            self.attributes['inventory'] = ActorInventory(inventory, self)
        else:
            self.attributes['inventory'] = ActorInventory(None, self)
Beispiel #4
0

def posToCoordinates(position):
    column = position % 8
    row = math.floor(position / 8)
    x = column * 100
    y = row * 100
    return (x, y)


createBoard()
fillBCTP()

turn = "White"
player_color = "White"
gameAi = AI(chessBoard)
while not quitGame:
    x = 0
    y = 0
    for event in pygame.event.get():

        if event.type == pygame.QUIT:
            quitGame = True
            pygame.quit()
            quit()
        if turn != player_color:
            while (turn != player_color):
                best_move_tup = gameAi.minimax(chessBoard, 2, False, turn)
                print(best_move_tup)
                # print("rand move",best_move_tup[0].position,random_move_tup[1])
                coordinates_from = posToCoordinates(best_move_tup[1].position)
Beispiel #5
0
class Game():
    """Main game class"""
    def __init__(self,
                 board_size=8,
                 cell_size=50,
                 margin=20,
                 border_size=0.3,
                 ship_types=[
                     "Carrier", "Battleship", "Cruiser", "Submarine",
                     "Destroyer"
                 ]):
        pygame.init()
        pygame.mixer.init()
        self.previous_win = False
        self.replay = False
        self.board_size = board_size
        self.cell_size = cell_size
        self.margin = margin
        self.border_size = border_size
        self.ship_types_list = ship_types
        # Calculate window size
        self.subwindow_positions = {
            "AI Board": [self.margin, self.margin + 50],
            "Player Board":
            [2 * self.margin + board_size * cell_size, self.margin + 50],
        }
        # Set headings style
        self.heading_font = pygame.font.Font(
            './Resources/Fonts/Bebas-Regular.ttf', 24)
        self.text_color = pygame.Color(91, 196, 209)

        # Create game window
        self.window_size = [
            2 * board_size * cell_size + 3 * margin,
            board_size * cell_size + 2 * margin + 50
        ]
        self.screen = pygame.display.set_mode(self.window_size)
        pygame.display.set_caption("Battleships")
        self.screen.fill(pygame.Color(173, 200, 216))
        # Start background
        pygame.mixer.music.load("./Resources/Sounds/background.wav")
        pygame.mixer.music.play(-1, 0.0)

    def start(self):
        """Start game with main menu"""
        main_menu = self.main_menu()
        main_menu.mainloop(self.screen, fps_limit=30)

    def main_menu(self):
        """Build Main menu"""
        # Main menu style
        menu_theme = pygame_menu.themes.Theme(
            surface_clear_color=(173, 200, 216),
            background_color=pygame_menu.baseimage.BaseImage(
                image_path="./Resources/Images/logo.png",
                drawing_mode=pygame_menu.baseimage.IMAGE_MODE_SIMPLE,
                drawing_offset=(295, 10)),
            title_bar_style=pygame_menu.widgets.MENUBAR_STYLE_NONE,
            widget_font=pygame_menu.font.FONT_BEBAS,
            widget_font_color=(0, 0, 0))
        menu = pygame_menu.Menu(self.window_size[1],
                                self.window_size[0],
                                "",
                                theme=menu_theme)
        menu.add_button('Play', self.play)

        # Help menu style
        help_theme = pygame_menu.themes.Theme(
            background_color=(173, 200, 216),
            title_bar_style=pygame_menu.widgets.MENUBAR_STYLE_NONE,
            widget_font=pygame_menu.font.FONT_FRANCHISE,
            widget_font_color=(0, 0, 0),
            widget_font_size=32,
        )

        help_menu = pygame_menu.Menu(self.window_size[1],
                                     self.window_size[0],
                                     theme=help_theme,
                                     title='')
        HELP = [
            "Left Click to add/remove ships", "Right Click to rotate ships",
            "Press R to randomly place ships",
            "Press Escape to return to Main Menu"
        ]
        for m in HELP:
            help_menu.add_label(m, align=pygame_menu.locals.ALIGN_CENTER)
        help_menu.add_vertical_margin(25)
        help_menu.add_button('Return to Menu', pygame_menu.events.BACK)

        menu.add_button('Help', help_menu)
        menu.add_button('Quit', pygame_menu.events.EXIT)

        return menu

    def play(self):
        """
        Main game function
        Contains board population and main game loop
        """
        self.ai = AI(self.board_size)
        self.screen.fill(pygame.Color(33, 119, 148))
        # Display player board heading
        pboard_heading = self.heading_font.render("Player board", True,
                                                  self.text_color)
        pboard_heading_rect = pboard_heading.get_rect()
        pboard_heading_rect.center = (
            self.subwindow_positions["Player Board"][0] +
            self.board_size / 2 * self.cell_size, 40)
        self.screen.blit(pboard_heading, pboard_heading_rect)

        self.pboard = PlayerBoard(self.board_size, self.ship_types_list,
                                  self.cell_size, self.border_size,
                                  self.subwindow_positions["Player Board"])
        # Populate player board
        self.pboard.populate(self.screen, self.subwindow_positions["AI Board"])
        # Display AI board heading
        ai_heading = self.heading_font.render("Enemy board", True,
                                              self.text_color)
        ai_heading_rect = ai_heading.get_rect()
        ai_heading_rect.center = (self.subwindow_positions["AI Board"][0] +
                                  self.board_size / 2 * self.cell_size, 40)

        self.aiboard = AIBoard(self.board_size, self.ship_types_list,
                               self.cell_size, self.border_size,
                               self.subwindow_positions["AI Board"])
        # Turn sync
        is_player_turn = True
        is_ai_turn = False
        # Delay to allow sound effect to play properly
        delay_counter = 11

        while True:

            try:
                # Take turn
                if is_player_turn and delay_counter > 15:
                    is_player_turn = not self.player_turn()
                    is_ai_turn = not is_player_turn
                    delay_counter = 0

                elif is_ai_turn and delay_counter > 60:
                    is_ai_turn = not self.ai_turn()
                    is_player_turn = not is_ai_turn
                    delay_counter = 0
                else:
                    delay_counter += 1
            except Exception:
                # Exit exception
                break

            # Draw display components
            self.screen.fill(pygame.Color(33, 119, 148))
            self.screen.blit(ai_heading, ai_heading_rect)
            self.screen.blit(pboard_heading, pboard_heading_rect)
            self.aiboard.draw(self.screen)
            self.pboard.draw(self.screen)

            # Display frame
            pygame.display.flip()
            pygame.time.Clock().tick(60)

            # Display Game over screen and exit
            if self.game_over:
                # Overlay translucent screen
                score_surface = pygame.Surface(self.window_size)
                score_surface.set_alpha(200)
                score_surface.fill(pygame.Color(33, 119, 148))

                font = pygame.font.Font('./Resources/Fonts/Bebas-Regular.ttf',
                                        60)
                # Add result
                if self.win:
                    score = font.render("You Win!", True, self.text_color)
                else:
                    score = font.render("You Lose!", True, self.text_color)

                score_rect = score.get_rect()
                score_rect.center = (self.window_size[0] // 2,
                                     self.window_size[1] // 2)
                score_surface.blit(score, score_rect)

                self.screen.blit(score_surface, (0, 0))
                pygame.display.flip()
                pygame.time.Clock().tick(0.2)
                break

    def player_turn(self):
        """Uses input to decide if a shot is valid or not"""
        x, y, button = self.aiboard.get_coordinates()

        if button == -2:
            raise Exception("exit")

        if self.aiboard.valid_target(x, y):
            result = self.aiboard.shoot(x, y)
            if result == 2:
                # Explosion on hit
                Explosion(
                    pygame.Rect(
                        self.subwindow_positions["AI Board"][0] +
                        x * self.cell_size,
                        self.subwindow_positions["AI Board"][1] +
                        y * self.cell_size, self.cell_size,
                        self.cell_size)).play(self.screen)
            elif result == 1:
                # Splash on miss
                Ripple(
                    pygame.Rect(
                        self.subwindow_positions["AI Board"][0] +
                        x * self.cell_size,
                        self.subwindow_positions["AI Board"][1] +
                        y * self.cell_size, self.cell_size,
                        self.cell_size)).play(self.screen)
            return True
        else:
            return False

    def ai_turn(self):
        """Uses input to decide if a shot is valid or not"""
        x, y = -1, -1
        x, y = self.ai.getLoc(self.pboard)

        if self.pboard.valid_target(x, y):
            result = self.pboard.shoot(x, y)

            if result == 2:
                Explosion(
                    pygame.Rect(
                        self.subwindow_positions["Player Board"][0] +
                        x * self.cell_size,
                        self.subwindow_positions["Player Board"][1] +
                        y * self.cell_size, self.cell_size,
                        self.cell_size)).play(self.screen)
                if self.ai.ai_hit_count == 0 or self.ai.ai_hit_count == 1:
                    self.ai.ai_hit_count += 1
                    self.ai.attack_mode = 'd'

            elif result == 1:
                Ripple(
                    pygame.Rect(
                        self.subwindow_positions["Player Board"][0] +
                        x * self.cell_size,
                        self.subwindow_positions["Player Board"][1] +
                        y * self.cell_size, self.cell_size,
                        self.cell_size)).play(self.screen)
                if self.ai.ai_hit_count == 2 and self.ai.ai_miss_after_hit_count < 2:
                    self.ai.ai_miss_after_hit_count += 1
            return True
        else:
            return False

    @property
    def game_over(self):
        """Determines and prints the winner"""
        if self.aiboard.gameover:
            self.win = True
            return True
        elif self.pboard.gameover:
            self.win = False
            return True
        else:
            return False
Beispiel #6
0
    def play(self):
        """
        Main game function
        Contains board population and main game loop
        """
        self.ai = AI(self.board_size)
        self.screen.fill(pygame.Color(33, 119, 148))
        # Display player board heading
        pboard_heading = self.heading_font.render("Player board", True,
                                                  self.text_color)
        pboard_heading_rect = pboard_heading.get_rect()
        pboard_heading_rect.center = (
            self.subwindow_positions["Player Board"][0] +
            self.board_size / 2 * self.cell_size, 40)
        self.screen.blit(pboard_heading, pboard_heading_rect)

        self.pboard = PlayerBoard(self.board_size, self.ship_types_list,
                                  self.cell_size, self.border_size,
                                  self.subwindow_positions["Player Board"])
        # Populate player board
        self.pboard.populate(self.screen, self.subwindow_positions["AI Board"])
        # Display AI board heading
        ai_heading = self.heading_font.render("Enemy board", True,
                                              self.text_color)
        ai_heading_rect = ai_heading.get_rect()
        ai_heading_rect.center = (self.subwindow_positions["AI Board"][0] +
                                  self.board_size / 2 * self.cell_size, 40)

        self.aiboard = AIBoard(self.board_size, self.ship_types_list,
                               self.cell_size, self.border_size,
                               self.subwindow_positions["AI Board"])
        # Turn sync
        is_player_turn = True
        is_ai_turn = False
        # Delay to allow sound effect to play properly
        delay_counter = 11

        while True:

            try:
                # Take turn
                if is_player_turn and delay_counter > 15:
                    is_player_turn = not self.player_turn()
                    is_ai_turn = not is_player_turn
                    delay_counter = 0

                elif is_ai_turn and delay_counter > 60:
                    is_ai_turn = not self.ai_turn()
                    is_player_turn = not is_ai_turn
                    delay_counter = 0
                else:
                    delay_counter += 1
            except Exception:
                # Exit exception
                break

            # Draw display components
            self.screen.fill(pygame.Color(33, 119, 148))
            self.screen.blit(ai_heading, ai_heading_rect)
            self.screen.blit(pboard_heading, pboard_heading_rect)
            self.aiboard.draw(self.screen)
            self.pboard.draw(self.screen)

            # Display frame
            pygame.display.flip()
            pygame.time.Clock().tick(60)

            # Display Game over screen and exit
            if self.game_over:
                # Overlay translucent screen
                score_surface = pygame.Surface(self.window_size)
                score_surface.set_alpha(200)
                score_surface.fill(pygame.Color(33, 119, 148))

                font = pygame.font.Font('./Resources/Fonts/Bebas-Regular.ttf',
                                        60)
                # Add result
                if self.win:
                    score = font.render("You Win!", True, self.text_color)
                else:
                    score = font.render("You Lose!", True, self.text_color)

                score_rect = score.get_rect()
                score_rect.center = (self.window_size[0] // 2,
                                     self.window_size[1] // 2)
                score_surface.blit(score, score_rect)

                self.screen.blit(score_surface, (0, 0))
                pygame.display.flip()
                pygame.time.Clock().tick(0.2)
                break
Beispiel #7
0
class BoardLayout(GridLayout):

    def __init__(self, turn_dispatcher, is_computer):
        super(BoardLayout, self).__init__()
        self.turn_dispatcher = turn_dispatcher
        self.is_computer = is_computer
        self.board_turn = True
        self.ship_fields_hit = 0
        self.computer = None
        self.generate_initial_board()

    def generate_initial_board(self):
        generator = Generate()
        fields = generator.generate_all_ships_positions()
        self.computer = AI(fields)
        field_id = 1
        for field_row in fields:
            for field in field_row:
                background_color = utils.get_color_from_hex('#66e0ff')  # water
                if field == 2:
                    background_color = utils.get_color_from_hex('#a6a6a6')  # ship
                # if field == FieldType.Occupied:
                #     background_color = utils.get_color_from_hex('#ffff00')  # occupied

                field_button = Button(
                    id=str(field_id),
                    text=str(field),
                    background_color=background_color)

                if not self.is_computer:
                    field_button.bind(on_release=self.player_hit_field)
                self.add_widget(field_button)
                field_id += 1
        if self.is_computer:
            self.add_widget(Label(text="PLANSZA GRACZA", text_size=(300, None), halign='right'))
        else:
            self.add_widget(Label(text="PLANSZA KOMPUTERA", text_size=(300, None), halign='right'))

    def give_turn(self):
        self.board_turn = True
        if self.is_computer:
            self.computer_hit_field()

    def player_hit_field(self, button_instance):
        if self.board_turn:
            if button_instance.text == '2':
                button_instance.background_color = utils.get_color_from_hex('#66ff33')
                self.ship_fields_hit += 1
                if self.ship_fields_hit == 20:
                    self.add_widget(Label(text="PRZEGRANA", text_size=(200, None), halign='right'))
                    for element in self.children:
                        element.disabled = True
            else:
                button_instance.disabled = True
                button_instance.background_color = utils.get_color_from_hex('#ff0000')
                self.board_turn = False

                if self.turn_dispatcher.x == 'player':
                    self.turn_dispatcher.x = 'computer'
                #else:
                #    self.turn_dispatcher.x = 'player'

    def computer_hit_field(self):
        computer_turn = True
        while computer_turn:
            button_index = self.computer.make_move()
            for button in self.children:
                if button.id == str(button_index):
                    if button.text == '2':
                        button.background_color = utils.get_color_from_hex('#66ff33')
                        self.ship_fields_hit += 1
                        if self.ship_fields_hit == 20:
                            self.add_widget(Label(text="PRZEGRANA", text_size=(200, None), halign='right'))
                            for element in self.children:
                                element.disabled = True
                            break
                    else:
                        button.disabled = True
                        button.background_color = utils.get_color_from_hex('#ff0000')
                        self.board_turn = False
                        computer_turn = False
                    break

        if self.turn_dispatcher.x == 'computer':
            self.turn_dispatcher.x = 'player'