Beispiel #1
0
class ScoreBoard(object):
    def __init__(self, names, screen, event_manager):
        self.names = names
        self.screen = screen
        self.background = pygame.Surface((SCREEN_WIDTH, CONTROLS_HEIGHT))
        self.rect = self.background.get_rect()
        self.rect.topleft = (0, BOARD_HEIGHT)
        self.leaderboard = LeaderBoard()

        self.scores = [0, 0]

    def update(self, winner):
        self.scores[winner] += 1
        self.render()

    def render(self):
        self.background.fill(ORANGE)
        for number in xrange(2):
            self.background.blit(
                NORMAL.render(str(self.scores[number]), True, WHITE),
                (HALF_WIDTH * (number + 1) - HALF_BORDER - 40, HALF_BORDER))
            self.background.blit(
                NORMAL.render(self.names[number], True, WHITE),
                (HALF_WIDTH * number + HALF_BORDER, HALF_BORDER))
        self.screen.blit(self.background, self.rect)
        pygame.display.update(self.rect)

    def store_result(self):
        for index in range(2):
            self.leaderboard.store_match_result(
                self.names[index], self.scores[index] - self.scores[index ^ 1])
Beispiel #2
0
    def __init__(self, names, screen, event_manager):
        self.names = names
        self.screen = screen
        self.background = pygame.Surface((SCREEN_WIDTH, CONTROLS_HEIGHT))
        self.rect = self.background.get_rect()
        self.rect.topleft = (0, BOARD_HEIGHT)
        self.leaderboard = LeaderBoard()

        self.scores = [0, 0]
Beispiel #3
0
    def __init__(self, mode=2, width=16, height=16, mines_count=40):
        super().__init__(width, height)
        self.lb = LeaderBoard(
            "minesweeper", {
                "Nick": str,
                "Time Spent": datetime.time,
                "Playing date": datetime.datetime,
                "Mode": str
            })
        self.lost = False
        self.not_win = True
        self.warning = False
        self.cheat_mode = False
        # cheat_mode позволяет смотреть расположение мин. Удобно для тестирования и обучения игре в сапер
        self.mode = mode
        # установка режима игры. Параметр mode устанавливает пользователь при запуске, на стартовом экране
        if self.mode == 2:
            self.width = width
            self.height = height
            self.mines_count = mines_count
        elif self.mode == 1:
            self.width = 9
            self.height = 9
            self.mines_count = 10
            Minesweeper.set_view(self, 10, 10, 50)
        elif self.mode == 3:
            self.width = 9
            self.height = 9
            self.mines_count = 10
            self.cheat_mode = True
            Minesweeper.set_view(self, 10, 10, 50)
        elif self.mode == 4:
            self.width = width
            self.height = height
            self.mines_count = mines_count
            self.cheat_mode = True
            Minesweeper.set_view(self, 10, 10, 25)
        self.tagged_mines = 0
        self.board = [[-1] * width for _ in range(height)]

        # Генерация мин. Ищет местоположение для мин, пока не установит все
        i = 0
        while i < self.mines_count:
            x = randrange(self.width)
            y = randrange(self.height)
            if self.board[y][x] != 10:
                self.board[y][x] = 10
                i += 1

        # значения по умолчанию
        self.left = 10
        self.top = 10
        self.cell_size = 30
        self.size_x = self.width * self.cell_size + self.left
        self.size_y = self.height * self.cell_size + self.top
Beispiel #4
0
 def main(self) -> None:
     """Run the game. The loop continues until
     either the snake hits the wall or eats his tail.
     """
     # Initialize pygame, generate screen and field
     self._set_player_name()
     self._leaderboard = LeaderBoard(self.player)
     self._screen = self._init_screen()
     pygame.init()
     clock = pygame.time.Clock()
     fps = 5
     while True:
         self._handle_screen(self._screen)
         pygame.display.update()
         clock.tick(fps)
Beispiel #5
0
    def __init__(self, screen, event_manager):
        super(LeaderBoardPage, self).__init__(screen, CORNSILK, event_manager)

        header = LARGE.render("Leaderboard", True, ORANGE)
        header_rect = header.get_rect()
        header_rect.midtop = (HALF_WIDTH, 20)

        heading = SMALL.render(
            "Rank |         Name         | Matches Played | Wins | Losses | Point Difference | Win Percentage",
            True, ORANGE)
        heading_rect = heading.get_rect()
        heading_rect.midtop = (HALF_WIDTH, 150)

        self.texts.extend([(header, header_rect), (heading, heading_rect)])

        self.leaderboard = LeaderBoard()
Beispiel #6
0
class LeaderBoardPage(Page):
    def __init__(self, screen, event_manager):
        super(LeaderBoardPage, self).__init__(screen, CORNSILK, event_manager)

        header = LARGE.render("Leaderboard", True, ORANGE)
        header_rect = header.get_rect()
        header_rect.midtop = (HALF_WIDTH, 20)

        heading = SMALL.render(
            "Rank |         Name         | Matches Played | Wins | Losses | Point Difference | Win Percentage",
            True, ORANGE)
        heading_rect = heading.get_rect()
        heading_rect.midtop = (HALF_WIDTH, 150)

        self.texts.extend([(header, header_rect), (heading, heading_rect)])

        self.leaderboard = LeaderBoard()

    def display(self):
        del self.texts[2:]
        TOP = self.texts[1][1].top + 35

        format_string = "{rank:>4d} | {name:20s} | {matches_played:>14d} | {wins:>4d} | {losses:>6d} | {point_diff:>16d} | {win_per:>14.2f}"
        for index, leader in enumerate(self.leaderboard.get_top_number(10)):
            res = SMALL.render(
                format_string.format(**dict(
                    zip(("rank", "name", "matches_played", "wins", "losses",
                         "point_diff", "win_per"), leader))), True, BLACK)
            res_rect = res.get_rect()
            res_rect.top = TOP + 35 * index
            res_rect.centerx = HALF_WIDTH
            self.texts.append((res, res_rect))

        super(LeaderBoardPage, self).display()
 def __init__(self, screen, radius=30, x=100, y=400):
     super().__init__(bird_sprite)
     self.radius = radius
     self.x = x
     self.y = y
     self.last_jump_time = time.time()
     self.jumped = False
     self.image = bird_down
     self.rect = bird_down.get_rect()
     self.rect.x = self.x
     self.rect.y = self.y
     self.vy = 3 / FPS * 60
     self.screen = screen
     self.lb = LeaderBoard("flappybird", {
         "Nick": str,
         "Playing date": datetime.datetime,
         "Score": str
     })
Beispiel #8
0
def run():
    print('starting server...')

    if len(sys.argv) != 2:
        print("Usage: simple_scorer.py <data.json>", file=sys.stderr)
        exit(1)

    global lb
    with open(sys.argv[1], "rt") as f:
        lb = LeaderBoard(f.read())

    global tokens
    with open("allowed_tokens.txt", "rt") as f:
        tokens = {}
        for line in f:
            tokens[line.strip().lower()] = 10
    # Server settings
    # Choose port 8080, for port 80, which is normally used for a http server, you need root access
    server_address = ('127.0.0.1', 8081)
    httpd = HTTPServer(server_address, RequestHandler)
    print('running server...')
    httpd.serve_forever()
def run_game():
	# Initialize pygame, settings and create a screen object 
	pygame.init()
	settings = Settings()

	screen = pygame.display.set_mode((settings.screen_x, settings.screen_y))
	pygame.display.set_caption("Alien Invasion")

	# Make the Play as Guest Button
	play_button = Button(settings, screen, "Play as Guest", adj_y=60)

	# Create a instance to store game stats and create a scoreboard, leaderboard
	stats = GameStats(settings)
	sb = Scoreboard(settings, screen, stats)
	lb = LeaderBoard(settings, screen)

	# Create a ship, alien, and groups to store bullets and alien fleet
	ship = Ship(screen, settings)
	alien = Alien(settings, screen)
	bullets = Group()
	aliens = Group()

	# Create the fleet of aliens
	gf.create_fleet(settings, screen, ship, aliens)

	# Load in all time scores
	gf.get_top_score(stats, settings)

	# Start the main loop for the game
	while True:
		gf.check_events(settings, stats, screen, sb, lb, ship, aliens, bullets, play_button)
		if stats.game_active:
			ship.update()
			gf.update_bullets(settings, stats, screen, sb, ship, aliens, bullets)
			gf.update_aliens(settings, stats, screen, sb, lb, ship, aliens, bullets)
		gf.update_screen(settings, stats, screen, sb, lb, ship, aliens, bullets, play_button, True)
Beispiel #10
0
class Game:
    """ Game class controls the flow of the game.
    This class receives inputs from users and pass the inputs to other classes
    to update the state of a field.
    === Private Attributes ===
    _dim: the dimensions of a game.
    _game_over: declares if the game ended to display score view
    _field: an instance of a Field class representing a game field.
    _in_game: declares if the window displays the game view
    _view_leaderboard: declares if the window displays the leaderboard view.
    _menu_index: keeps the record of selected_menu.
    _screen: the pygame screen onto which the different scenes will display.
    _view_title: declares if the window displays the main menu view.
    === Public Attributes ===
    player: the player's alias.
    leaderboard: a LeaderBoard class instance to store the player's score.
    hand: declares handedness of player. 0 for left-handed; 1 for right-handed
    """
    # Attributes
    _dim: Tuple[int, int]
    _in_game: bool
    _game_over: bool
    _view_leaderboard: bool
    _view_title_screen: bool
    _menu_index: int
    _field: Optional[Field]
    _screen: pygame.Surface
    player: str
    _leaderboard: Optional[LeaderBoard]
    hand: int

    # Constants
    TEXT_COLOR = (50, 50, 50)
    TITLE_SCREEN_COLOR = (255, 255, 255)

    def __init__(self) -> None:
        """Initializer of game class with player <player_name>.
        """
        self._dim = (800, 800)
        self._in_game = False
        self._game_over = False
        self._menu_index = 0
        self._field = None
        self.player = None
        self._view_leaderboard = False
        self._view_title = True
        self.hand = None

    def main(self) -> None:
        """Run the game. The loop continues until
        either the snake hits the wall or eats his tail.
        """
        # Initialize pygame, generate screen and field
        self._set_player_name()
        self._leaderboard = LeaderBoard(self.player)
        self._screen = self._init_screen()
        pygame.init()
        clock = pygame.time.Clock()
        fps = 5
        while True:
            self._handle_screen(self._screen)
            pygame.display.update()
            clock.tick(fps)

    # --------------------------------------------------------
    # Helper function of main
    # --------------------------------------------------------
    def _set_player_name(self) -> None:
        """Ask a user to choose their name and controls
        they wish to use.
        """
        self.player = input("Enter your name \n")
        invalid_input = True
        while invalid_input:
            hand_input = input("If you want to play a game with WASD, press 0, or press 1 to use arrow keys \n")
            try:
                self.hand = int(hand_input)
                if self.hand not in [0, 1]:
                    print("Invalid input, Please enter 0 or 1.")
                else:
                    invalid_input = False
            except ValueError:
                print("Invalid input, Please enter 0 or 1.")

    def _init_screen(self) -> pygame.Surface:
        """Initialize title screen"""
        screen = pygame.display.set_mode(self._dim, pygame.RESIZABLE)
        screen.fill(self.TITLE_SCREEN_COLOR)
        pygame.display.set_caption("Snake game")
        self._menu_index = 0
        return screen

    def _handle_screen(self, screen: pygame.Surface):
        """Choose which screen to show"""
        # if in_leader_board and not in_title and not in_game:
        if self._view_title:
            self._display_title_screen()
        elif self._in_game:
            self._run_game(screen)
        elif self._game_over:
            self._display_score()
        else:
            self._display_scoreboard()

    # --------------------------------------------------------
    # Main function to create view
    # --------------------------------------------------------
    def _display_minimenu(self, title: str, size: int, where: int = None,
                          show_score: bool = False,
                          show_leader_board: bool = False) -> None:
        """Displays a screen with <title> and font <size>.
        Method also adds main menu options relative to <where>
        """
        # Enable exiting game and process user inputs
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                self._handle_key_input(event.key)
            elif event.type == pygame.VIDEORESIZE:
                self._dim = event.dict['size']
                self._screen = pygame.display.set_mode(self._dim, pygame.RESIZABLE)
                pygame.display.flip()
            else:
                pass
        # self._screen = pygame.display.set_mode(self._dim, RESIZABLE)
        self._screen.fill(self.TITLE_SCREEN_COLOR)
        self._create_title(title, size)
        self._create_menu_options(where)
        if show_score:
            margin_x = self._calc_margin_x(150)
            self._create_menu_label("Game Over!", (margin_x, 200))
            if self._field is None:
                results = ""
            else:
                results = self.player + ": " + str(self._field.get_score())
            result_margin = self._calc_margin_x(len(results) * 13)
            self._create_menu_label(results, (result_margin, 250))
        elif show_leader_board:
            self._format_scoreboard()


    # --------------------------------------------------------
    # Helper function of _display_mini_menu
    # --------------------------------------------------------
    def _create_menu_label(self, label_text: str,
                           location: Tuple[int, int]) -> None:
        """Draw menu label from given label text at given location"""
        menu_font = pygame.font.SysFont("Arial", 36)
        menu_label = menu_font.render(label_text, 1, self.TEXT_COLOR)
        self._screen.blit(menu_label, location)

    def _draw_menu_selection_arrow(self,
                                   x_location: int,
                                   y_location: int) -> None:
        """Draw menu selection arrow into screen"""
        menu_arrow_location = [[x_location, y_location + 2],
                               [x_location, y_location + 22],
                               [x_location + 20, y_location + 12]]
        pygame.draw.polygon(self._screen, self.TEXT_COLOR, menu_arrow_location)

    def _create_title(self, title: str, size: int,):
        """Create title label on the screen"""
        title_font = pygame.font.SysFont("monospace", size)
        title_label = title_font.render(title, 1, self.TEXT_COLOR)
        title_width, title_height = title_label.get_size()
        new_location = ((self._dim[0] - title_width) // 2, 50)
        self._screen.blit(title_label, new_location)

    def _create_menu_options(self, where: Optional[int]) -> None:
        """Create menu options with an arrow showing selected option"""
        margin_x = self._calc_margin_x(190) + 35
        if where is not None:
            self._create_menu_label("Play", (margin_x, where))
            self._create_menu_label("Leaderboard", (margin_x, where + 40) )
            self._create_menu_label("Quit", (margin_x, where + 80))
            self._draw_menu_selection_arrow(margin_x - 35,
                                            [where, where + 40, where + 80][self._menu_index])

        else:
            self._create_menu_label("Play", (margin_x, 300))
            self._create_menu_label("Leaderboard", (margin_x, 340), )
            self._create_menu_label("Quit", (margin_x, 380))
            self._draw_menu_selection_arrow(margin_x - 35,
                                        [300, 340, 380][self._menu_index])

    def _calc_margin_x(self, width: int) -> int:
        """Calculate horizontal margins based on given width"""
        margin = (self._screen.get_width() - width) // 2
        if margin < 0:
            margin *= -1
        return margin

    def _format_scoreboard(self) -> None:
        """Formats game history to display top 10 scores and players"""
        winners = self._leaderboard.get_top_ten()
        i, j = 1, 1
        for entry in winners:
            player, score = entry
            margin_x = self._calc_margin_x(700)
            self._create_menu_label(player, (margin_x, 100 + j * 40))
            self._create_menu_label(score,
                                    (self._screen.get_width() - margin_x - 50,
                                            100 + j * 40))
            i += 1
            j += 1

    # --------------------------------------------------------
    # Title Screen
    # --------------------------------------------------------
    def _display_title_screen(self) -> None:
        """Draw menu option arrow and update view"""
        # Clear current view contents
        self._display_minimenu("Snake game", 80)

    # --------------------------------------------------------
    # key_input_handler for title/score
    # --------------------------------------------------------
    def _handle_key_input(self, key_value: int) -> None:
        """Handle key inputs in title screen"""
        if key_value == pygame.K_UP:
            self._menu_index -= 1
            if self._menu_index < 0:
                self._menu_index = 2
        elif key_value == pygame.K_DOWN:
            self._menu_index += 1
            if self._menu_index > 2:
                self._menu_index = 0
        elif key_value == pygame.K_RETURN:
            self._change_view_flags()

    def _change_view_flags(self) -> None:
        """Helper function of handle_key_input"""
        if self._menu_index == 0:  # user chooses to play
            self._in_game = True
            self._view_leaderboard = False
            self._view_title = False
            self._game_over = False
            self._field = None
        elif self._menu_index == 1:  # user chooses to view leaderboard
            self._in_game = False
            self._view_leaderboard = True
            self._view_title = False
            self._game_over = False
        else:  # user chooses to exit GUI
            pygame.quit()
            sys.exit()

    # --------------------------------------------------------
    # run game
    # --------------------------------------------------------
    def _run_game(self, screen: pygame.Surface) -> None:
        """Recursively call this method until the game is over.
        This method should receive user inputs and update state of a field
        """
        key = None
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                key = event.key
        if self._field is None:
            self._field = Field(screen, self.hand)
        is_game_over = self._field.display_field(key)

        if is_game_over:
            self._game_over = True
            self._in_game = False
            score = self._field.get_score()
            self._leaderboard.set_player_score(score)
            self._display_score()

    def _display_score(self) -> None:
        """Display game instance results"""
        self._display_minimenu("Snake game", 80, None, True)

    # --------------------------------------------------------
    # Leader Board
    # --------------------------------------------------------
    def _display_scoreboard(self) -> None:
        """Display leaderboard screen with top 10 scores"""
        history_size = self._leaderboard.get_history_size()
        self._display_minimenu("LEADERBOARD", 54,
                               history_size * 55, False, True)
class Bird(pygame.sprite.Sprite):
    def __init__(self, screen, radius=30, x=100, y=400):
        super().__init__(bird_sprite)
        self.radius = radius
        self.x = x
        self.y = y
        self.last_jump_time = time.time()
        self.jumped = False
        self.image = bird_down
        self.rect = bird_down.get_rect()
        self.rect.x = self.x
        self.rect.y = self.y
        self.vy = 3 / FPS * 60
        self.screen = screen
        self.lb = LeaderBoard("flappybird", {
            "Nick": str,
            "Playing date": datetime.datetime,
            "Score": str
        })

    def update(self, *args):
        if IF_PLAYING:
            self.rect = self.rect.move(0, self.vy)
            self.y += self.vy
            if self.jumped:
                if time.time() - self.last_jump_time > 0.5:
                    self.image = bird_down
                    self.rect = bird_down.get_rect()
                    self.rect.x = self.x
                    self.rect.y = self.y
                    self.jumped = False
                    self.last_jump_time = time.time()

        if args:
            if "kill" in args:
                self.kill()
            if "reset" in args:
                self.x = 100
                self.y = 400
                self.image = bird_down
                self.rect = bird_down.get_rect()
                self.rect.x = self.x
                self.rect.y = self.y
            if IF_PLAYING:
                self.y -= 50
                self.image = bird_up
                self.rect = bird_up.get_rect()
                self.rect.x = self.x
                self.rect.y = self.y
                self.jumped = True

        if pygame.sprite.spritecollideany(
                self, floor_sprite) or pygame.sprite.spritecollideany(
                    self, pipe_sprites):
            global counter
            if os.name == "posix":
                nick = os.environ.get("USER")
            else:
                nick = os.environ.get("USERNAME")
            self.lb.AddRecord(nick, "datetime('now', '+3 hours')", counter)
            pygame.event.post(kill_event)
            print("Game over")
Beispiel #12
0
class Minesweeper(Board):
    def __init__(self, mode=2, width=16, height=16, mines_count=40):
        super().__init__(width, height)
        self.lb = LeaderBoard(
            "minesweeper", {
                "Nick": str,
                "Time Spent": datetime.time,
                "Playing date": datetime.datetime,
                "Mode": str
            })
        self.lost = False
        self.not_win = True
        self.warning = False
        self.cheat_mode = False
        # cheat_mode позволяет смотреть расположение мин. Удобно для тестирования и обучения игре в сапер
        self.mode = mode
        # установка режима игры. Параметр mode устанавливает пользователь при запуске, на стартовом экране
        if self.mode == 2:
            self.width = width
            self.height = height
            self.mines_count = mines_count
        elif self.mode == 1:
            self.width = 9
            self.height = 9
            self.mines_count = 10
            Minesweeper.set_view(self, 10, 10, 50)
        elif self.mode == 3:
            self.width = 9
            self.height = 9
            self.mines_count = 10
            self.cheat_mode = True
            Minesweeper.set_view(self, 10, 10, 50)
        elif self.mode == 4:
            self.width = width
            self.height = height
            self.mines_count = mines_count
            self.cheat_mode = True
            Minesweeper.set_view(self, 10, 10, 25)
        self.tagged_mines = 0
        self.board = [[-1] * width for _ in range(height)]

        # Генерация мин. Ищет местоположение для мин, пока не установит все
        i = 0
        while i < self.mines_count:
            x = randrange(self.width)
            y = randrange(self.height)
            if self.board[y][x] != 10:
                self.board[y][x] = 10
                i += 1

        # значения по умолчанию
        self.left = 10
        self.top = 10
        self.cell_size = 30
        self.size_x = self.width * self.cell_size + self.left
        self.size_y = self.height * self.cell_size + self.top

    def render(self, place):
        all_sprites.update()
        self.place = place
        cur_y = self.top
        if not self.not_win:
            render_text(self.place,
                        pygame,
                        self.size_x + 30,
                        150,
                        f"You win!",
                        scale=30,
                        colour=(0, 255, 0))
        if self.tagged_mines == self.mines_count and self.not_win:
            render_text(self.place,
                        pygame,
                        self.size_x + 30,
                        150,
                        f"Not all the mines have been marked",
                        scale=30,
                        colour=(0, 255, 0))
        if not self.lost:
            e = int(time.time() - start_time)

            render_text(self.place,
                        pygame,
                        self.size_x + 30,
                        50,
                        f"Mines left: {self.mines_count - self.tagged_mines}",
                        scale=30,
                        colour=(0, 255, 0))

            render_text(
                self.place,
                pygame,
                self.size_x + 30,
                100,
                f"Your time: {'{:02d}:{:02d}:{:02d}'.format(e // 3600, (e % 3600 // 60), e % 60)}",
                scale=30,
                colour=(0, 255, 0))
        else:
            render_text(self.place,
                        pygame,
                        self.size_x + 30,
                        50,
                        f"Mines left: {self.result_left_mines}",
                        scale=30,
                        colour=(0, 255, 0))

            render_text(self.place,
                        pygame,
                        self.size_x + 30,
                        100,
                        f"Your time: {self.total_time}",
                        scale=30,
                        colour=(0, 255, 0))

        for i in range(self.height):
            cur_x = self.left
            for j in range(self.width):
                if self.board[i][j] == 10 and self.lost or self.board[i][
                        j] == 10 and self.cheat_mode:
                    Tile("empty", cur_x, cur_y, self.cell_size)
                    Tile("bomb", cur_x, cur_y, self.cell_size)

                elif self.lost and type(
                        self.board[i]
                    [j]) == list and self.board[i][j][1] == 10:
                    Tile("marked", cur_x, cur_y, self.cell_size)
                    Tile("bomb", cur_x, cur_y, self.cell_size)

                elif self.board[i][j] in (0, 1, 2, 3, 4, 5, 6, 7, 8):
                    Tile(str(self.board[i][j]), cur_x, cur_y, self.cell_size)

                elif type(self.board[i][j]) == list:
                    Tile("marked", cur_x, cur_y, self.cell_size)

                else:
                    Tile("empty", cur_x, cur_y, self.cell_size)

                pygame.draw.rect(place, (0, 0, 0),
                                 (self.left, self.top, self.size_x - self.left,
                                  self.size_y - self.top), 3)
                cur_x += self.cell_size
            cur_y += self.cell_size

    def restart(self):
        self.__init__(self.mode)
        Minesweeper.set_view(self, 10, 10, 35)
        self.total_time = 0
        global start_time
        start_time = time.time()
        self.lost = False

    def is_mine(self, x, y):
        if self.board[y][x] == 10:
            return True
        return False

    def get_click(self, mouse_pos):
        try:
            cell = self.get_cell(mouse_pos)
            if cell:
                self.open_cell(cell)
        except Exception as e:
            print("Unknown Error. Write to developers.", e)

    # Функция для отмети мин(или не мин, если игрок ошибся). Есть возможность снять отметку мины
    def mark_mine(self, mouse_pos):
        cell = self.get_cell(mouse_pos)
        if cell:
            x, y = cell[0], cell[1]
            if type(self.board[y]
                    [x]) != list and self.tagged_mines < self.mines_count:
                self.board[y][x] = ["marked", self.board[y][x]]
                self.tagged_mines += 1
                # print("Marked", cell)
            elif type(self.board[y][x]) == list:
                self.board[y][x] = self.board[y][x][1]
                self.tagged_mines -= 1

    def open_cell(self, cell):
        x, y = cell[0], cell[1]
        counter = 0

        if self.board[y][x] == 10:
            self.lost = True
            e = int(time.time() - start_time)
            self.total_time = '{:02d}:{:02d}:{:02d}'.format(
                e // 3600, (e % 3600 // 60), e % 60)
            self.result_left_mines = self.mines_count - self.tagged_mines
            print("YOU LOST")

        # Алгоритм для автоматического открытия "безопастных" клеток
        if self.board[y][x] == -1:
            for y_edge in range(-1, 2):
                for x_edge in range(-1, 2):
                    if x + x_edge < 0 or x + x_edge >= self.width or y + y_edge < 0 or y + y_edge >= self.height:
                        continue

                    if self.board[y + y_edge][x + x_edge] == 10:
                        counter += 1

                    elif type(self.board[y + y_edge][x + x_edge]) == list and \
                            self.board[y + y_edge][x + x_edge][1] == 10:
                        counter += 1

            self.board[y][x] = counter

        if self.board[y][x] == 0:
            for y_edge in range(-1, 2):
                for x_edge in range(-1, 2):
                    if x + x_edge < 0 or x + x_edge >= self.width or y + y_edge < 0 or y + y_edge >= self.height:
                        continue

                    if self.board[y + y_edge][x + x_edge] == -1:
                        self.open_cell((x + x_edge, y + y_edge))

    # Функция - обработчик победы
    def win(self):
        self.counter = 0
        if self.tagged_mines == self.mines_count:
            for i in range(self.height):
                for j in range(self.width):
                    if type(self.board[i]
                            [j]) == list and self.board[i][j][1] == 10:
                        self.counter += 1

            if self.counter != self.mines_count:
                self.warning = True
                # print("Not all the mines have been marked")

            else:
                # print("You win!")
                e = int(time.time() - start_time)
                self.total_time = '{:02d}:{:02d}:{:02d}'.format(
                    e // 3600, (e % 3600 // 60), e % 60)
                self.result_left_mines = self.mines_count - self.tagged_mines
                self.not_win = False
                if os.name == "posix":
                    nick = os.environ.get("USER")
                else:
                    nick = os.environ.get("USERNAME")
                time_in_seconds = e
                game_mode = self.mode
                self.lb.AddRecord(nick,
                                  f"time('{time_in_seconds}', 'unixepoch')",
                                  "datetime('now', '+3 hours')", game_mode)
                # print(nick, time_in_seconds, date, game_mode, sep="\n")
                return True
        return False
Beispiel #13
0
import re
from flask import Flask, render_template, request, url_for, session, redirect
from flask_socketio import SocketIO, emit
from players import Players
from words import Words
from game_state import GameState
from leaderboard import LeaderBoard
from authentication import player_required


app = Flask(__name__)
config.load(app)
words = Words(app)
players = Players(app)
game_state = GameState(app)
leaderboard = LeaderBoard(app)
socketio = SocketIO(app, async_mode=None)

thread = None
stop_game = go_next = False
# TODO: look into using thread events instead of these flags

@app.route('/')
def index():
    return render_template('index.html', leaderboard=leaderboard.rankings(), player=session.get("player"))

@app.route("/signout")
def signout():
    session.clear()
    return redirect(url_for("index"))
Beispiel #14
0
from flask import Flask, redirect, render_template, request
from gevent.wsgi import WSGIServer

from predict import InstrumentClassifier
from leaderboard import LeaderBoard

app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 1 * 2**20

model_dir = 'data/working/single-notes-2000/models'
model_id = LeaderBoard(model_dir).best_model()
model = InstrumentClassifier(model_dir + '/' + model_id)

print('Using model:', model_id)


@app.route('/')
def hello():
    return render_template('home.html', model_id=model_id)


@app.route('/api/classify/instrument', methods=['POST'])
def classify():
    if 'audio_file' not in request.files:
        return redirect('/')

    # File-like object than can be directy passed to soundfile.read()
    # without saving to disk.
    audio_file = request.files['audio_file']

    if audio_file.filename == '':