예제 #1
0
 def __init__(self, screen_size=(1024, 768)):
     super().__init__("", dict())
     self.FPS = 60
     self.WIDTH, self.HEIGHT = screen_size
     self.screen = pygame.display.set_mode((self.WIDTH, self.HEIGHT),
                                           pygame.RESIZABLE)
     pygame.display.set_caption("Сборник игр: Таблица рекордов")
     self.screen.fill((0, 0, 0))
     pygame.display.flip()
     self.close_button_icon = load_image("data/close_button.png", pygame)
     self.left_button_icon = load_image("data/ArrowLeft.png", pygame)
     self.right_button_icon = load_image("data/ArrowRight.png", pygame)
     self.goto_menu = Button(100,
                             100,
                             self.screen,
                             pygame,
                             active_clr=(255, 0, 0))
     self.next_game = Button(100, 100, self.screen, pygame)
     self.previous_game = Button(100, 100, self.screen, pygame)
     self.clock = pygame.time.Clock()
     with sqlite3.connect("leaderboard.db") as connection:
         cursor = connection.cursor()
         self.games = cursor.execute(
             """SELECT name FROM sqlite_master WHERE type='table';"""
         ).fetchall()
         self.currentgame = 0
         if len(self.games) > 0:
             self.gamename = self.games[self.currentgame][0]
             self.records = self._GetRecords()
             if len(self.records) > 0:
                 rows = len(self.records)
                 columns = len(self.records[0])
                 self.Board = Board(self.WIDTH - 80, min(rows * 20, 550),
                                    columns, rows)
                 self._SetNewGame()
예제 #2
0
def flappy_bird(music_on_imported, size_counter=1):
    """Запуск игры Flappy bird"""
    global bird_sprite, floor_sprite, pipe_sprites, IF_PLAYING, RESTARTINGTICK, counter
    global width, height
    restart_skins()

    btns_top_coords = (0, 260), (0, 130)
    btns_floor_coords = [(0, 120), (650, 768)]

    close_button = load_image("data/close_button.png", pygame)
    pause_button = load_image("data/pause_button.png", pygame)
    play_button = load_image("data/play_button.png", pygame)
    restart_button = load_image("data/restart_button.png", pygame)

    music_on = sound_on, (30, 683), True
    if music_on_imported[2] != music_on[2]:
        music_on = music(music_on, pygame, sound_on, sound_off)

    bird_sprite = pygame.sprite.Group()
    floor_sprite = pygame.sprite.Group()
    pipe_sprites = pygame.sprite.Group()

    width, height = SCREEN_SIZES[size_counter % 2]

    screen = pygame.display.set_mode((width, height))
    pygame.display.set_caption("Сборник игр: Flappy bird")
    background = pygame.transform.scale(
        load_image('data/flappy_bird/background.png', pygame), (width, height))
    base = pygame.transform.scale(
        load_image('data/flappy_bird/base.png', pygame),
        (calc_x(1024), calc_y(70)))

    floor_x_pos = 0
    Bird(screen)

    # Границы экрана, соприкасаясь с которыми, Bird умирает
    x5, y5 = calc_x(5), calc_y(5)

    b1 = Border(x5, y5, width - x5, y5)
    b2 = Border(calc_x(70), height - calc_y(70), width - calc_x(70),
                height - calc_y(70))
    b3 = Border(x5, y5, x5, height - y5)
    b4 = Border(width - x5, y5, width - x5, height - y5)

    # Кнопки
    to_main_menu_local = to_main_menu_button(screen, pygame)
    pause_local = pause_button_func(screen, pygame)
    music_button = Button(100, 100, screen, pygame)
    play_again_btn = play_again_button(screen, pygame)
    screen_size_button = Button(100, 100, screen, pygame)

    # Счетчик очков (пройденных труб)
    counter = 0

    # Генерация трубы. Далее она сама генерирует следующую
    y = calc_y(random.randint(100, 300))
    Pipe(y=y, place="bottom")
    Pipe(y=y, place="top")

    # Пересчет координат кнопок под размер экрана
    play_again_coordinates, pause_local_coordinates, to_main_menu_local_coordinates, music_button_coordinates, screen_size_button_coordinates = resize_flappy(
    )

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.MOUSEBUTTONDOWN:
                if not (btns_floor_coords[0][0] < event.pos[0] < btns_floor_coords[0][1] and btns_floor_coords[1][0] <
                        event.pos[1] < btns_floor_coords[1][1]) \
                        and not (
                        btns_top_coords[0][0] < event.pos[0] < btns_top_coords[0][1] and btns_top_coords[1][0] <
                        event.pos[1] < btns_top_coords[1][1]):
                    if IF_PLAYING and RESTARTINGTICK >= 4000:
                        bird_sprite.update(event)
            elif event.type == pygame.VIDEORESIZE:
                width, height = event.w, event.h
                play_again_coordinates, pause_local_coordinates, to_main_menu_local_coordinates, music_button_coordinates, screen_size_button_coordinates = resize_flappy(
                )
                background = pygame.transform.scale(background,
                                                    (width, height))

                b1.set_coordinates(x5, y5, width - x5, y5)
                b2.set_coordinates(calc_x(70), height - calc_y(70),
                                   width - calc_x(70), height - calc_y(70))
                b3.set_coordinates(x5, y5, x5, height - y5)
                b4.set_coordinates(width - x5, y5, width - x5, height - y5)
            elif pygame.key.get_pressed()[pygame.K_r] or event == kill_event:
                # Перезапуск игры
                RESTARTINGTICK = 0
                IF_PLAYING = True
                restart_skins()
                pipe_sprites.update("kill")
                bird_sprite.update("reset")
                y = calc_y(random.randint(100, 300))
                Pipe(y=y, place="bottom")
                Pipe(y=y, place="top")
                counter = 0

        pygame.display.update()
        screen.blit(background, (0, 0))
        bird_sprite.draw(screen)
        pipe_sprites.draw(screen)

        # Отрисовка кнопок
        if to_main_menu_local.draw(to_main_menu_local_coordinates,
                                   image=close_button,
                                   font_size=70,
                                   cmd="close"):
            bird_sprite.update("kill")
            return music_on, size_counter

        if pause_local.draw(pause_local_coordinates,
                            image=pause_button if IF_PLAYING else play_button,
                            font_size=70,
                            cmd="pause"):
            IF_PLAYING = not IF_PLAYING

        if play_again_btn.draw(play_again_coordinates,
                               image=restart_button,
                               font_size=70,
                               cmd="again"):
            pygame.event.post(kill_event)

        if RESTARTINGTICK < 4000:
            print_text(f"{int(3999 - RESTARTINGTICK) // 1000}",
                       width // 2,
                       height // 2,
                       screen=screen,
                       pygame=pygame,
                       font_size=100)
        else:
            if IF_PLAYING:
                bird_sprite.update()
                pipe_sprites.update()
                floor_x_pos = draw_floor(floor_x_pos, screen,
                                         base)  # перемещение пола
            else:
                floor_x_pos = draw_floor(floor_x_pos, screen, base, pause=True)
        print_text("0" if counter < 0 else str(counter),
                   calc_x(450),
                   calc_y(50),
                   screen=screen,
                   pygame=pygame,
                   font_size=calc_y(100))

        a = music_button.draw(music_button_coordinates,
                              image=music_on[0],
                              action=music,
                              font_size=calc_y(70),
                              args=(music_on, pygame, sound_on, sound_off))
        if a:
            # Если была нажата кнопка звука, обновляем его состояние
            music_on = a

        sz_s = screen_size_button.draw(screen_size_button_coordinates,
                                       SCREEN_SIZES_LETTERS[size_counter % 2],
                                       action=pygame.display.set_mode,
                                       args=(SCREEN_SIZES[size_counter % 2], ))
        if sz_s:
            size_counter += 1
            width, height = SCREEN_SIZES[size_counter % 2]
            screen = pygame.display.set_mode((width, height))
            background = pygame.transform.scale(background, (width, height))
            base = pygame.transform.scale(base, (calc_x(1024), calc_y(70)))
            play_again_coordinates, pause_local_coordinates, to_main_menu_local_coordinates, music_button_coordinates, screen_size_button_coordinates = resize_flappy(
            )
            b1.set_coordinates(x5, y5, width - x5, y5)
            b2.set_coordinates(calc_x(70), height - calc_y(70),
                               width - calc_x(70), height - calc_y(70))
            b3.set_coordinates(x5, y5, x5, height - y5)
            b4.set_coordinates(width - x5, y5, width - x5, height - y5)

        a = clock.tick(FPS)
        RESTARTINGTICK += a if RESTARTINGTICK < 4000 else 0
예제 #3
0
    if floor_pos <= calc_x(-1024):
        floor_pos = 0
    return floor_pos


counter = 0
FPS = 30
BASEWIDTH, BASEHEIGHT = 1024, 768
width, height = 1024, 768
IF_PLAYING = True
RESTARTINGTICK = 4000
bird_sprite = pygame.sprite.Group()
floor_sprite = pygame.sprite.Group()
pipe_sprites = pygame.sprite.Group()

sound_on = load_image("data/unmute.png", pygame)
sound_off = load_image("data/mute.png", pygame)

pipe_down_skins = {
    "green": load_image("data/flappy_bird/pipes/green/pipe-down.png", pygame),
    "red": load_image("data/flappy_bird/pipes/red/pipe-down.png", pygame)
}
pipe_up_skins = {
    "green": load_image("data/flappy_bird/pipes/green/pipe-up.png", pygame),
    "red": load_image("data/flappy_bird/pipes/red/pipe-up.png", pygame)
}

bird_down_skins = {
    "blue": load_image("data/flappy_bird/bird/blue/bird-midflap.png", pygame),
    "red": load_image("data/flappy_bird/bird/red/bird-midflap.png", pygame),
    "yellow": load_image("data/flappy_bird/bird/yellow/bird-midflap.png",
예제 #4
0
def start_screen(screen, FPS):
    intro_text = [
        "Правила игры",
        "Число в ячейке показывает, сколько мин скрыто вокруг данной ячейки. ",
        "Это число поможет понять вам, где находятся безопасные ячейки, а где находятся бомбы.",
        "Если рядом с открытой ячейкой есть пустая ячейка, то она откроется автоматически.",
        "Если вы открыли ячейку с миной, то игра проиграна..",
        "Что бы пометить ячейку, в которой находится бомба, нажмите её правой кнопкой мыши.",
        "После того, как вы отметите все мины, можно навести курсор на открытую ячейку и ",
        "нажать правую и левую кнопку мыши одновременно. ",
        "Тогда откроются все свободные ячейки вокруг неё",
        "Если в ячейке указано число, оно показывает, ",
        "сколько мин скрыто в восьми ячейках вокруг данной. ",
        "Это число помогает понять, где находятся безопасные ячейки.",
        "Игра продолжается до тех пор, пока вы не откроете все не заминированные ячейки",
        "И не отметите все мины флажком."
        " ", "Вам доступно 4 режима игры:", "1. Простой. Поле 9x9, 10 мин",
        "2. Средний. Поле 16x16, 40 мин",
        "3. Простой с просмотром мин. Поле 9x9, 10 мин",
        "4. Средний с просмотром мин. Поле 16x16, 40 мин", " ",
        "Для выбора нажмите соответствующую цифру на клавиатуре"
    ]

    fullname = os.path.join('data/minesweeper', 'fon.jpg')
    fon = pygame.transform.scale(load_image(fullname, pygame), (width, height))
    screen.blit(fon, (0, 0))
    if height > 600:
        font = pygame.font.Font(None, 30)
        str_height = 10
        text_coord = 30
    else:
        font = pygame.font.Font(None, 26)
        str_height = 9
        text_coord = 20

    for line in intro_text:
        string_rendered = font.render(line, True, pygame.Color('black'))
        intro_rect = string_rendered.get_rect()
        text_coord += str_height
        intro_rect.top = text_coord
        intro_rect.x = str_height
        text_coord += intro_rect.height
        screen.blit(string_rendered, intro_rect)

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                terminate()
            keys = pygame.key.get_pressed()
            if keys:
                global g_mode
                if keys[pygame.K_1]:
                    g_mode = 1
                    return

                if keys[pygame.K_2]:
                    g_mode = 2
                    return

                if keys[pygame.K_3]:
                    g_mode = 3
                    return

                if keys[pygame.K_4]:
                    g_mode = 4
                    return

        pygame.display.flip()
        clock.tick(FPS)
예제 #5
0
def minesweeper(music_on_imported, size_counter):
    global width, height, start_time

    width, height = SCREEN_SIZES[size_counter % 2]
    music_on = sound_on, (calc_y(910), calc_x(507)), True
    if music_on_imported[2] != music_on[2]:
        music_on = music(music_on,
                         pygame,
                         sound_on,
                         sound_off,
                         coords=(calc_y(910), calc_x(510)))
    screen = pygame.display.set_mode((width, height))
    FPS = 60
    pygame.display.set_caption("Сборник игр: Сапер")
    screen.fill((0, 0, 0))
    pygame.display.flip()
    start_screen(screen, FPS)

    close_button = load_image("data/close_button.png", pygame)
    restart_button = load_image("data/restart_button.png", pygame)
    music_button = Button(100, 100, screen, pygame)
    to_main_menu_local = to_main_menu_button(screen, pygame)
    play_again_but = play_again_button(screen, pygame)
    screen_size_button = Button(100, 100, screen, pygame)

    start_time = time.time()
    board = Minesweeper(g_mode)
    board.set_view(10, 10, 35)
    running = True

    to_main_menu_local_coordinates, play_again_but_coordinates, music_button_coordinates, screen_size_button_coordinates = resize_minesweeper(
    )

    while running:
        for event in pygame.event.get():
            keys = pygame.key.get_pressed()
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.MOUSEBUTTONDOWN:
                if not board.lost:
                    if event.button == 1:
                        board.get_click(event.pos)
                    elif event.button == 2:
                        print("middle mouse button")
                    elif event.button == 3:
                        board.mark_mine(event.pos)
                        if board.win():
                            board.lost = True
            if keys[pygame.K_r]:
                board.restart()

            elif event.type == pygame.VIDEORESIZE:
                to_main_menu_local_coordinates, play_again_but_coordinates, music_button_coordinates, screen_size_button_coordinates = resize_minesweeper(
                )

        screen.fill((187, 187, 187))
        all_sprites.draw(screen)
        board.render(screen)

        if to_main_menu_local.draw(to_main_menu_local_coordinates,
                                   image=close_button,
                                   font_size=70,
                                   cmd="close"):
            return music_on, size_counter

        if play_again_but.draw(play_again_but_coordinates,
                               image=restart_button,
                               font_size=70,
                               cmd="again"):
            board.restart()

        music_on = music_button.draw(
            music_button_coordinates,
            "",
            action=music,
            font_size=70,
            args=(music_on, pygame, sound_on, sound_off,
                  (calc_x(910), calc_y(506)))) or music_on

        sz_s = screen_size_button.draw(screen_size_button_coordinates,
                                       SCREEN_SIZES_LETTERS[size_counter % 2],
                                       action=pygame.display.set_mode,
                                       args=(SCREEN_SIZES[size_counter % 2], ))
        if sz_s:
            size_counter += 1
            width, height = SCREEN_SIZES[size_counter % 2]
            screen = pygame.display.set_mode((width, height))
            music_on = music(music_on, pygame, sound_on, sound_off,
                             (calc_x(910), calc_y(506)))
            music_on = music(music_on, pygame, sound_on, sound_off,
                             (calc_x(910), calc_y(506)))
            to_main_menu_local_coordinates, play_again_but_coordinates, music_button_coordinates, screen_size_button_coordinates = resize_minesweeper(
            )
        screen.blit(*music_on[:2])

        pygame.display.flip()
        if board.lost:
            pass
예제 #6
0
import pygame, time, sys, os, datetime
from random import randrange
from leaderboard import LeaderBoard
from scripts import load_image, render_text, to_main_menu_button, Button, music, play_again_button

clock = pygame.time.Clock()
all_sprites = pygame.sprite.Group()
tiles_group = pygame.sprite.Group()
BASEWIDTH, BASEHEIGHT = 1024, 768
size = width, height = 1024, 768

SCREEN_SIZES = [[1024, 768], [800, 600]]
SCREEN_SIZES_LETTERS = ["S", "B"]

sound_on = load_image("data/unmute.png", pygame)
sound_off = load_image("data/mute.png", pygame)

tile_images = {
    '0': load_image('data/minesweeper/0.png', pygame),
    '1': load_image('data/minesweeper/1.png', pygame),
    '2': load_image('data/minesweeper/2.png', pygame),
    '3': load_image('data/minesweeper/3.png', pygame),
    '4': load_image('data/minesweeper/4.png', pygame),
    '5': load_image('data/minesweeper/5.png', pygame),
    '6': load_image('data/minesweeper/6.png', pygame),
    '7': load_image('data/minesweeper/7.png', pygame),
    '8': load_image('data/minesweeper/8.png', pygame),
    'bomb': load_image('data/minesweeper/bomb.png', pygame),
    'marked': load_image('data/minesweeper/flagged.png', pygame),
    'empty': load_image('data/minesweeper/facingDown.png', pygame)
}
예제 #7
0
def start_screen():
    """Стартовый экран(главное меню)"""
    global music_on, screen, size, width, height, BASEWIDTH, BASEWIDTH

    intro_text = ["СБОРНИК ИГР", "", "Flappy bird,", "Сапер,", "Морской бой"]
    # Фон и постоянный текст
    background = pygame.transform.scale(
        load_image('data/menu_image.jpg', pygame), (width, height))
    screen.blit(background, (0, 0))
    font = pygame.font.Font(None, 50)
    text_coord = 30
    for line in intro_text:
        string_rendered = font.render(line, True, pygame.Color('black'))
        intro_rect = string_rendered.get_rect()
        text_coord += 10
        intro_rect.top = text_coord
        intro_rect.x = 10
        text_coord += intro_rect.height
        screen.blit(string_rendered, intro_rect)

    # Кнопки
    start_flappy_bird = Button(300, 70, screen, pygame)
    start_minesweeper = Button(170, 70, screen, pygame)
    quit_button = Button(200, 70, screen, pygame, active_clr=(255, 0, 0))
    music_button = Button(100, 100, screen, pygame)
    screen_size_button = Button(100, 100, screen, pygame)
    leaderboard_button = Button(300, 70, screen, pygame)

    start_flappy_bird_coordinates, start_minesweeper_coordinates, quit_button_coordinates, music_button_coordinates, screen_size_button_coordinates, leaderboard_button_coordinates = resize_main(
    )

    size_counter = 2
    size_counter2 = 0

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                terminate()
            elif event.type == pygame.VIDEORESIZE:
                size = width, height = event.w, event.h

                if width < 800 or height < 600:
                    screen = pygame.display.set_mode((800, 600))
                    width, height = 800, 600
                background = pygame.transform.scale(background,
                                                    (width, height))
                start_flappy_bird_coordinates, start_minesweeper_coordinates, quit_button_coordinates, music_button_coordinates, screen_size_button_coordinates, leaderboard_button_coordinates = resize_main(
                )

        screen.blit(background, (0, 0))
        try:
            music_on_local_flappy = start_flappy_bird.draw(
                start_flappy_bird_coordinates,
                "Flappy bird",
                action=flappy_bird.flappy_bird,
                font_size=70,
                args=(music_on, size_counter))
            if music_on_local_flappy:
                size_counter = music_on_local_flappy[1]
                width, height = SCREEN_SIZES[size_counter % 2]
                screen = pygame.display.set_mode((width, height))
                background = pygame.transform.scale(background,
                                                    (width, height))
                start_flappy_bird_coordinates, start_minesweeper_coordinates, quit_button_coordinates, music_button_coordinates, screen_size_button_coordinates, leaderboard_button_coordinates = resize_main(
                )
                pygame.display.set_caption("Сборник игр: главное меню")

                if music_on[2] != music_on_local_flappy[0][2]:
                    music_on = music(music_on, pygame, sound_on, sound_off)

            music_on_local_minesweeper = start_minesweeper.draw(
                start_minesweeper_coordinates,
                "Сапер",
                action=minesweeper.minesweeper,
                font_size=70,
                args=(music_on, size_counter))
            if music_on_local_minesweeper:
                size_counter = music_on_local_minesweeper[1]
                size_counter = music_on_local_minesweeper[1]
                width, height = SCREEN_SIZES[size_counter % 2]
                screen = pygame.display.set_mode((width, height))
                background = pygame.transform.scale(background,
                                                    (width, height))
                start_flappy_bird_coordinates, start_minesweeper_coordinates, quit_button_coordinates, music_button_coordinates, screen_size_button_coordinates, leaderboard_button_coordinates = resize_main(
                )
                pygame.display.set_caption("Сборник игр: главное меню")
                if music_on[2] != music_on_local_minesweeper[0][2]:
                    music_on = music(music_on, pygame, sound_on, sound_off)
        except Exception as e:
            print("Unknown Error. Write to developers.", e)

        quit_button.draw(quit_button_coordinates,
                         "Выход",
                         action=terminate,
                         font_size=70)
        music_on = music_button.draw(
            music_button_coordinates,
            image=music_on[0],
            action=music,
            font_size=70,
            cmd=True,
            args=(music_on, pygame, sound_on, sound_off)) or music_on

        sz_s = screen_size_button.draw(screen_size_button_coordinates,
                                       SCREEN_SIZES_LETTERS[size_counter % 2],
                                       action=pygame.display.set_mode,
                                       args=(SCREEN_SIZES[size_counter % 2], ))

        # обработка нажатия на кнопку изменения размера экрана
        if sz_s:
            if size_counter2 % 2 == 0:
                size_counter += 1
                width, height = SCREEN_SIZES[size_counter % 2]
                screen = pygame.display.set_mode((width, height))
                background = pygame.transform.scale(background,
                                                    (width, height))
                start_flappy_bird_coordinates, start_minesweeper_coordinates, quit_button_coordinates, music_button_coordinates, screen_size_button_coordinates, leaderboard_button_coordinates = resize_main(
                )

        lb = leaderboard_button.draw(leaderboard_button_coordinates,
                                     "Лидерборд",
                                     font_size=70,
                                     action=leaderboard.open_leaderboard,
                                     args=(pygame,
                                           SCREEN_SIZES[size_counter % 2]))
        # Если вернулись из лидерборда, то меняем название окна обратно
        if lb:
            pygame.display.set_caption("Сборник игр: главное меню")

        pygame.display.flip()
        clock.tick(60)
        clock.tick(FPS)
예제 #8
0
import pygame
import sys
from scripts import load_image, Button, music
import flappy_bird
import minesweeper
import leaderboard

FPS = 50
BASEWIDTH, BASEHEIGHT = 1024, 768
size = width, height = 1024, 768
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Сборник игр: главное меню")
clock = pygame.time.Clock()

sound_on = load_image("data/unmute.png", pygame)
sound_off = load_image("data/mute.png", pygame)
music_on = (sound_on, (30, 683), True)

SCREEN_SIZES = [[1024, 768], [800, 600]]
SCREEN_SIZES_LETTERS = ["S", "B"]


def resize_main():
    """Перерасчет положения кнопок при изменении размера окна"""
    start_flappy_bird_coordinates = (200 / BASEWIDTH) * width, (
        200 / BASEWIDTH) * width
    start_minesweeper_coordinates = (700 / BASEWIDTH) * width, (
        200 / BASEWIDTH) * width
    quit_button_coordinates = (450 / BASEWIDTH) * width, (500 /
                                                          BASEWIDTH) * width
    music_button_coordinates = (10 / BASEWIDTH) * width, (658 /