diff --git a/Game_menu/autho_and_reg.py b/Game_menu/autho_and_reg.py new file mode 100644 index 0000000..6af185b --- /dev/null +++ b/Game_menu/autho_and_reg.py @@ -0,0 +1,33 @@ +import sqlite3 as sq +from check_password import check_password + + +# Регистрация пользователя +def reg(login, password): + if check_password(password)[0]: + try: + with sq.connect("users.db") as db: + cur = db.cursor() + cur.execute("INSERT INTO users (login, password) VALUES (?, ?)", (login, password)) + db.commit() + return (True, None) + except: + return (False, 'Логин уже существует') + else: + check_password(password) + +# Авторизация пользователя, возвращает True если удачна, False если нет +def autho(login, password): + + with sq.connect("users.db") as db: + cur = db.cursor() + query = 'SELECT password FROM USERS WHERE login = ? ' + cur.execute(query, (login.lower(),)) + try: + if cur.fetchall()[0][0].lower() == password: + print('ok') + return True + except IndexError: + return False + + diff --git a/Game_menu/button_class.py b/Game_menu/button_class.py new file mode 100644 index 0000000..57546a7 --- /dev/null +++ b/Game_menu/button_class.py @@ -0,0 +1,17 @@ +import pygame +from load_img import load_image + + +class Button(pygame.sprite.Sprite): + def __init__(self, x_pos, y_pos, func, path, size=(200, 90)): + super(Button, self).__init__() + + self.func = func + self.image = pygame.transform.scale(load_image(path), (size)) + self.rect = self.image.get_rect() + self.rect.x = x_pos + self.rect.x -= 10 + self.rect.y = y_pos + + def update(self): + return self.func diff --git a/Game_menu/check_password.py b/Game_menu/check_password.py new file mode 100644 index 0000000..e4026a7 --- /dev/null +++ b/Game_menu/check_password.py @@ -0,0 +1,15 @@ +# Функция удовлетворения пароля при регистрации +# Принимает на вход пароль +# Возвращает кортеж, True or False если удалось создать или нет, если нет то какая ошибка + +def check_password(password): + if len(password) < 8: + return (False, "Длина пароля должна быть больше 8 символов") + + if not (password != password.lower() and password != password.upper()): + return (False, "В пароле отсутсвуют присутствуют большие и маленькие буквы любого алфавита.") + + if not (any([x.isdigit() for x in password])): + return (False, "Пароль должен содержать цифры") + + return (True, None) \ No newline at end of file diff --git a/Game_menu/load_img.py b/Game_menu/load_img.py new file mode 100644 index 0000000..40222d4 --- /dev/null +++ b/Game_menu/load_img.py @@ -0,0 +1,13 @@ +import pygame +import os +import sys + + +def load_image(name): + fullname = os.path.join('data', name) + # если файл не существует, то выходим + if not os.path.isfile(fullname): + print(f"Файл с изображением '{fullname}' не найден") + sys.exit() + image = pygame.image.load(fullname) + return image diff --git a/Game_menu/open_doc.py b/Game_menu/open_doc.py new file mode 100644 index 0000000..4b5924d --- /dev/null +++ b/Game_menu/open_doc.py @@ -0,0 +1,11 @@ +import os +import platform +import subprocess +def open_documentation(name): + path = os.path.join('data', name) + if platform.system() == 'Darwin': # macOS + subprocess.call(('open', path)) + elif platform.system() == 'Windows': # Windows + os.startfile(path) + else: # linux + subprocess.call(('xdg-open', path)) \ No newline at end of file diff --git a/Game_menu/our_font.ttf b/Game_menu/our_font.ttf new file mode 100644 index 0000000..3d41434 Binary files /dev/null and b/Game_menu/our_font.ttf differ diff --git a/Game_menu/test_menu.py b/Game_menu/test_menu.py new file mode 100644 index 0000000..579932d --- /dev/null +++ b/Game_menu/test_menu.py @@ -0,0 +1,176 @@ +from open_doc import open_documentation +from autho_and_reg import autho, reg +from load_img import load_image +import pygame +import sys +import random +import pyautogui +import os +from button_class import Button +import webbrowser + + +width, height = pyautogui.size() +# Инициализация игрового поля +screen_size = (width, height) +pygame.init() +pygame.display.set_caption('Крутая карточная игра') +screen = pygame.display.set_mode(screen_size) +mainClock = pygame.time.Clock() + + +def play_sound(filename): + path = os.path.join('sound', filename) + button_click = pygame.mixer.Sound(path) + button_click.play() + + +# Функция отрисовывания эффектов, на вход принимает координаты где надо отрисовывать +def create_particles(position): + # количество создаваемых частиц + particle_count = 10 + # возможные скорости + numbers = range(-5, 6) + for _ in range(particle_count): + Particle(position, random.choice(numbers), random.choice(numbers)) + + +# функция отрисовки текста, принимает на вход текст, размер, цвет, поле на котором отрисовывает, и координаты x y +def draw_text(text, font_size, color, surface, x, y): + font = pygame.font.Font('our_font.ttf', font_size) + textobj = font.render(text, True, color) + textrect = textobj.get_rect() + textrect.topleft = (x, y) + surface.blit(textobj, textrect) + return textobj.get_width() + + +class Particle(pygame.sprite.Sprite): + # сгенерируем частицы разного размера + fire = [load_image("star.png")] + for scale in (5, 10, 20): + fire.append(pygame.transform.scale(fire[0], (scale, scale))) + + def __init__(self, pos, dx, dy): + super().__init__(all_parcticles) + self.image = random.choice(self.fire) + self.rect = self.image.get_rect() + + # у каждой частицы своя скорость — это вектор + self.velocity = [dx, dy] + # и свои координаты + self.rect.x, self.rect.y = pos + + # гравитация будет одинаковой (значение константы) + self.gravity = 0.5 + + def update(self): + # применяем гравитационный эффект: + # движение с ускорением под действием гравитации + self.velocity[1] += self.gravity + # перемещаем частицу + + self.rect.x -= self.velocity[0] + self.rect.y += self.velocity[1] + # убиваем, если частица ушла за экран + if not self.rect.colliderect(0, 0, screen_size[0], screen_size[1]): + self.kill() + + +class InputBox: + + def __init__(self, x, y, w, h, text=''): + self.rect = pygame.Rect(x, y, w, h) + self.color = (212, 175, 55) + self.text = text + self.active = False + + def handle_event(self, event): + if event.type == pygame.MOUSEBUTTONDOWN: + if self.rect.collidepoint(event.pos): + self.active = not self.active + else: + self.active = False + + if event.type == pygame.KEYDOWN: + if self.active: + if event.key == pygame.K_BACKSPACE: + self.text = self.text[:-1] + else: + if draw_text(self.text, 20, (0, 170, 200), screen, self.rect.x + 5, self.rect.y + 5) + 10 < 400: + self.text += event.unicode + else: + draw_text(self.text, 20, (0, 170, 200), screen, self.rect.x + 5, self.rect.y + 5) + + def update(self): + text_size = draw_text(self.text, 20, (0, 170, 200), screen, self.rect.x + 5, self.rect.y + 5) + 10 + self.rect.w = max(410, text_size) + pygame.draw.rect(screen, self.color, self.rect, 2, 3) + + def give_text(self): + return self.text + + +# Создаю кнопки и поля ввода +all_parcticles = pygame.sprite.Group() +password = InputBox(850, 550, 200, 50) +login = InputBox(850, 490, 200, 50) +input_boxes = [login, password] +all_buttons = pygame.sprite.Group() +all_buttons.add(Button(100, 200, "print('сделать')", 'button_start_game.png')) +all_buttons.add(Button(100, 300, "print('сделать')", 'button_change_deck.png')) +all_buttons.add(Button(100, 400, "open_documentation('data.txt')", 'button_help.png')) +all_buttons.add(Button(100, 500, "print(2)", 'button_settings.png')) +all_buttons.add(Button(100, 600, "print('сделать')", 'button_stats.png')) +all_buttons.add(Button(850, 600, "autho(login.give_text(), password.give_text())", 'button_login.png')) +all_buttons.add(Button(1076, 600, "reg(login.give_text(), password.give_text())", 'button_reg.png')) +all_buttons.add(Button((width - 60), 10, "webbrowser.open('https://github.com/Sla1mer/PyGameProjectYandex'," + " new=2)", 'github_logo.png', (50, 50))) + + +# Задний фон +bg = pygame.transform.scale(load_image('background.jpg'), (width, height)) + + +# основной цикл программы +running = True + + +def main_menu(): + global running, screen + while running: + # выход из игры + for event in pygame.event.get(): + if event.type == pygame.QUIT: + running = False + pygame.quit() + sys.exit() + + if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1: + for button in all_buttons: + if button.rect.collidepoint(event.pos): + eval(button.update()) + play_sound('button_click.wav') + create_particles(pygame.mouse.get_pos()) + + for box in input_boxes: + box.handle_event(event) + + # подгружаю задний фон + screen.blit(bg, (0, 0)) + draw_text('Кардмастер', 100, (0, 170, 200), screen, width - 700, 50) + + all_buttons.draw(screen) + + for box in input_boxes: + box.update() + + all_parcticles.draw(screen) + all_parcticles.update() + + pygame.display.update() + mainClock.tick(60) + + +if __name__ == '__main__': + main_menu() diff --git a/Game_menu/users.db b/Game_menu/users.db new file mode 100644 index 0000000..cd265a4 Binary files /dev/null and b/Game_menu/users.db differ diff --git a/background.jpg b/background.jpg new file mode 100644 index 0000000..0d4f575 Binary files /dev/null and b/background.jpg differ diff --git a/button_change_deck.png b/button_change_deck.png new file mode 100644 index 0000000..67ffc7b Binary files /dev/null and b/button_change_deck.png differ diff --git a/button_click.wav b/button_click.wav new file mode 100644 index 0000000..acfa0d4 Binary files /dev/null and b/button_click.wav differ diff --git a/button_help.png b/button_help.png new file mode 100644 index 0000000..91ec659 Binary files /dev/null and b/button_help.png differ diff --git a/button_login.png b/button_login.png new file mode 100644 index 0000000..9d4e93f Binary files /dev/null and b/button_login.png differ diff --git a/button_reg.png b/button_reg.png new file mode 100644 index 0000000..3678bc7 Binary files /dev/null and b/button_reg.png differ diff --git a/button_settings.png b/button_settings.png new file mode 100644 index 0000000..1dd5e6a Binary files /dev/null and b/button_settings.png differ diff --git a/button_start_game.png b/button_start_game.png new file mode 100644 index 0000000..c95f55e Binary files /dev/null and b/button_start_game.png differ diff --git a/button_stats.png b/button_stats.png new file mode 100644 index 0000000..58596b8 Binary files /dev/null and b/button_stats.png differ diff --git a/data.txt b/data.txt new file mode 100644 index 0000000..a4a192a --- /dev/null +++ b/data.txt @@ -0,0 +1 @@ +Правила игры кардмастер \ No newline at end of file diff --git a/github_logo.png b/github_logo.png new file mode 100644 index 0000000..9fe4c5e Binary files /dev/null and b/github_logo.png differ diff --git a/star.png b/star.png new file mode 100644 index 0000000..0dda9d1 Binary files /dev/null and b/star.png differ