commit 83c902d6c36acce5dff6bcd92cb9d057523e1678 Author: Xatiko <107261855+Anymorexxx@users.noreply.github.com> Date: Mon Nov 18 00:49:14 2024 +0300 Initial commit diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/.idea/Dog_Academy.iml b/.idea/Dog_Academy.iml new file mode 100644 index 0000000..b6731d8 --- /dev/null +++ b/.idea/Dog_Academy.iml @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/.idea/inspectionProfiles/profiles_settings.xml b/.idea/inspectionProfiles/profiles_settings.xml new file mode 100644 index 0000000..105ce2d --- /dev/null +++ b/.idea/inspectionProfiles/profiles_settings.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..65f5335 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,7 @@ + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..0a731dc --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/__pycache__/config.cpython-313.pyc b/__pycache__/config.cpython-313.pyc new file mode 100644 index 0000000..700288b Binary files /dev/null and b/__pycache__/config.cpython-313.pyc differ diff --git a/config.py b/config.py new file mode 100644 index 0000000..be71e20 --- /dev/null +++ b/config.py @@ -0,0 +1,16 @@ +# config.py + +# Интерфейс +BACKGROUND_COLOR = "#f8e1e1" +PRIMARY_COLOR = "#ff6347" +BUTTON_COLOR = "#87ceeb" +BUTTON_TEXT_COLOR = "white" +FONT = ("Comic Sans MS", 25) +BIG_FONT = ("Comic Sans MS", 40) + +# Данные для авторизации администратора +ADMIN_LOGIN = "admin" +ADMIN_PASSWORD = "admin123" + +# База данных +DATABASE_URL = "sqlite:///database/DogAcademy.db" # Обновлено на правильный путь diff --git a/database/DogAcademy.db b/database/DogAcademy.db new file mode 100644 index 0000000..3f0c2bb Binary files /dev/null and b/database/DogAcademy.db differ diff --git a/database/__init__.py b/database/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/database/__pycache__/__init__.cpython-313.pyc b/database/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000..1dbaed6 Binary files /dev/null and b/database/__pycache__/__init__.cpython-313.pyc differ diff --git a/database/__pycache__/db_events.cpython-313.pyc b/database/__pycache__/db_events.cpython-313.pyc new file mode 100644 index 0000000..87f6cf4 Binary files /dev/null and b/database/__pycache__/db_events.cpython-313.pyc differ diff --git a/database/__pycache__/db_session.cpython-313.pyc b/database/__pycache__/db_session.cpython-313.pyc new file mode 100644 index 0000000..ba13851 Binary files /dev/null and b/database/__pycache__/db_session.cpython-313.pyc differ diff --git a/database/__pycache__/models.cpython-313.pyc b/database/__pycache__/models.cpython-313.pyc new file mode 100644 index 0000000..00ae4eb Binary files /dev/null and b/database/__pycache__/models.cpython-313.pyc differ diff --git a/database/db_events.py b/database/db_events.py new file mode 100644 index 0000000..38d4ac7 --- /dev/null +++ b/database/db_events.py @@ -0,0 +1,28 @@ +from database.db_session import get_session +from database.models import Auth +from sqlalchemy.exc import SQLAlchemyError + +def create_user(login, password): + """Создание нового пользователя в базе данных.""" + session = get_session() + try: + new_user = Auth(login=login, password=password) + session.add(new_user) + session.commit() + except SQLAlchemyError as e: + print(f"Ошибка при создании пользователя: {e}") + session.rollback() + finally: + session.close() + +def check_user(login, password): + """Проверка данных пользователя для авторизации.""" + session = get_session() + try: + user = session.query(Auth).filter_by(login=login, password=password).first() + return user is not None + except SQLAlchemyError as e: + print(f"Ошибка при проверке пользователя: {e}") + return False + finally: + session.close() diff --git a/database/db_session.py b/database/db_session.py new file mode 100644 index 0000000..7e8b40e --- /dev/null +++ b/database/db_session.py @@ -0,0 +1,24 @@ +# database/db_session.py +from sqlalchemy import create_engine +from sqlalchemy.orm import sessionmaker +from config import DATABASE_URL +from database.models import Base +import os + +# Создание движка SQLAlchemy +engine = create_engine(DATABASE_URL, echo=True) + +# Создание фабрики сессий +Session = sessionmaker(bind=engine) + +def init_db(): + """Инициализация базы данных: создание файла и таблиц.""" + if not os.path.exists("database/DogAcademy.db"): + print("База данных не найдена. Создаём новую...") + Base.metadata.create_all(bind=engine) + else: + print("База данных уже существует.") + +def get_session(): + """Возвращает сессию для работы с базой данных.""" + return Session() diff --git a/database/models.py b/database/models.py new file mode 100644 index 0000000..4198539 --- /dev/null +++ b/database/models.py @@ -0,0 +1,55 @@ +from sqlalchemy import Column, Integer, String, ForeignKey, Text +from sqlalchemy.orm import relationship +from sqlalchemy.ext.declarative import declarative_base + +Base = declarative_base() + + +class Auth(Base): + __tablename__ = 'auth' + user_id = Column(Integer, primary_key=True) + login = Column(String, unique=True, nullable=False) + password = Column(String, nullable=False) + + # Связь с таблицей Users + user = relationship("Users", back_populates="auth", uselist=False) + + +class Users(Base): + __tablename__ = 'users' + user_id = Column(Integer, ForeignKey('auth.user_id'), primary_key=True) + dog_id = Column(Integer, ForeignKey('dogs.dog_id')) + username = Column(String, nullable=False) + level = Column(Integer, default=1) + achievement = Column(Text) + + # Связи + auth = relationship("Auth", back_populates="user") # Обратная связь с Auth + dog = relationship("Dogs", back_populates="users") # Связь с таблицей Dogs + + +class Dogs(Base): + __tablename__ = 'dogs' + dog_id = Column(Integer, primary_key=True) + breed = Column(String) + characteristics = Column(Text) + behavior = Column(Text) + care_info = Column(Text) + admin_comments = Column(Text) + + # Связь с таблицей Users + users = relationship("Users", back_populates="dog") + # Связь с таблицей Questions + questions = relationship("Questions", back_populates="dog") + + +class Questions(Base): + __tablename__ = 'questions' + question_id = Column(Integer, primary_key=True) + dog_id = Column(Integer, ForeignKey('dogs.dog_id')) + question_text = Column(Text, nullable=False) + image_url = Column(String) + helpful_info = Column(Text) + + # Связь с таблицей Dogs + dog = relationship("Dogs", back_populates="questions") diff --git a/requirements b/requirements new file mode 100644 index 0000000..5c10195 --- /dev/null +++ b/requirements @@ -0,0 +1,2 @@ +sqlalchemy +tk diff --git a/src/__pycache__/auth.cpython-313.pyc b/src/__pycache__/auth.cpython-313.pyc new file mode 100644 index 0000000..8f21deb Binary files /dev/null and b/src/__pycache__/auth.cpython-313.pyc differ diff --git a/src/auth.py b/src/auth.py new file mode 100644 index 0000000..90be51b --- /dev/null +++ b/src/auth.py @@ -0,0 +1,19 @@ +from database.db_session import session +from database.models import Auth, Users + +def register_user(login, password, username): + if session.query(Auth).filter_by(login=login).first(): + return False, "Логин уже используется." + new_auth = Auth(login=login, password=password) + session.add(new_auth) + session.commit() + new_user = Users(user_id=new_auth.user_id, username=username) + session.add(new_user) + session.commit() + return True, "Регистрация успешна." + +def login_user(login, password): + user = session.query(Auth).filter_by(login=login, password=password).first() + if user: + return True, user.user_id + return False, "Неверный логин или пароль." diff --git a/src/main.py b/src/main.py new file mode 100644 index 0000000..2fce195 --- /dev/null +++ b/src/main.py @@ -0,0 +1,16 @@ +from tkinter import Tk +from src.ui.auth_ui import DogAcademyApp # Изменил на правильный путь +from database.db_session import init_db + +def main(): + """Основной запуск приложения.""" + # Инициализируем базу данных + init_db() + + # Запускаем графический интерфейс + root = Tk() + app = DogAcademyApp(root) + root.mainloop() + +if __name__ == "__main__": + main() diff --git a/src/ui/__pycache__/admin_ui.cpython-313.pyc b/src/ui/__pycache__/admin_ui.cpython-313.pyc new file mode 100644 index 0000000..0261396 Binary files /dev/null and b/src/ui/__pycache__/admin_ui.cpython-313.pyc differ diff --git a/src/ui/__pycache__/auth_ui.cpython-313.pyc b/src/ui/__pycache__/auth_ui.cpython-313.pyc new file mode 100644 index 0000000..452c157 Binary files /dev/null and b/src/ui/__pycache__/auth_ui.cpython-313.pyc differ diff --git a/src/ui/__pycache__/user_ui.cpython-313.pyc b/src/ui/__pycache__/user_ui.cpython-313.pyc new file mode 100644 index 0000000..4b3c551 Binary files /dev/null and b/src/ui/__pycache__/user_ui.cpython-313.pyc differ diff --git a/src/ui/admin_ui.py b/src/ui/admin_ui.py new file mode 100644 index 0000000..b94d102 --- /dev/null +++ b/src/ui/admin_ui.py @@ -0,0 +1,59 @@ +# admin_ui.py +import tkinter as tk +from config import BACKGROUND_COLOR, PRIMARY_COLOR, BUTTON_COLOR, BUTTON_TEXT_COLOR, FONT + +class AdminApp: + def __init__(self, root): + self.root = root + self.show_admin_dashboard() + + def show_admin_dashboard(self): + """Показать интерфейс администратора.""" + self.clear_frame() + self.current_frame = tk.Frame(self.root, bg=BACKGROUND_COLOR) + self.current_frame.pack(expand=True) + + # Заголовок + title = tk.Label( + self.current_frame, + text="Админ-Панель", + bg=BACKGROUND_COLOR, + fg=PRIMARY_COLOR, + font=FONT, + ) + title.pack(pady=50) + + # Кнопка для управления вопросами + manage_questions_button = tk.Button( + self.current_frame, + text="Управление вопросами", + bg=BUTTON_COLOR, + fg=BUTTON_TEXT_COLOR, + font=FONT, + command=self.manage_questions, + ) + manage_questions_button.pack(pady=20) + + # Кнопка для управления пользователями + manage_users_button = tk.Button( + self.current_frame, + text="Управление пользователями", + bg=BUTTON_COLOR, + fg=BUTTON_TEXT_COLOR, + font=FONT, + command=self.manage_users, + ) + manage_users_button.pack(pady=20) + + def manage_questions(self): + """Управление вопросами в игре.""" + pass + + def manage_users(self): + """Управление пользователями игры.""" + pass + + def clear_frame(self): + """Очистить текущий фрейм.""" + if hasattr(self, 'current_frame') and self.current_frame: + self.current_frame.destroy() diff --git a/src/ui/auth_ui.py b/src/ui/auth_ui.py new file mode 100644 index 0000000..7e0f3ae --- /dev/null +++ b/src/ui/auth_ui.py @@ -0,0 +1,222 @@ +import tkinter as tk +from tkinter import messagebox +from config import BACKGROUND_COLOR, PRIMARY_COLOR, BUTTON_COLOR, BUTTON_TEXT_COLOR, FONT, BIG_FONT, ADMIN_LOGIN, ADMIN_PASSWORD +from src.ui.admin_ui import AdminApp # Импорт интерфейса администратора +from database.db_events import create_user, check_user +from src.ui.user_ui import UserApp + +class DogAcademyApp: + def __init__(self, root): + self.root = root + self.root.title("Dog Academy Game") + self.root.geometry("1920x1080") + self.root.configure(bg=BACKGROUND_COLOR) + self.current_frame = None + self.show_main_menu() + + def clear_frame(self): + """Очистить текущий фрейм.""" + if self.current_frame: + self.current_frame.destroy() + + def show_main_menu(self): + """Показать главное меню с названием игры и кнопками.""" + self.clear_frame() + self.current_frame = tk.Frame(self.root, bg=BACKGROUND_COLOR) + self.current_frame.pack(expand=True) + + # Название игры + title = tk.Label( + self.current_frame, + text="Dog Academy Game", + bg=BACKGROUND_COLOR, + fg=PRIMARY_COLOR, + font=BIG_FONT, + ) + title.pack(pady=50) + + # Кнопка "Войти" + login_button = tk.Button( + self.current_frame, + text="Войти", + bg=BUTTON_COLOR, + fg=BUTTON_TEXT_COLOR, + font=FONT, + command=self.show_login_screen, + ) + login_button.pack(pady=20) + + # Кнопка "Зарегистрироваться" + register_button = tk.Button( + self.current_frame, + text="Зарегистрироваться", + bg=BUTTON_COLOR, + fg=BUTTON_TEXT_COLOR, + font=FONT, + command=self.show_registration_screen, + ) + register_button.pack(pady=20) + + def show_login_screen(self): + """Показать экран авторизации.""" + self.clear_frame() + self.current_frame = tk.Frame(self.root, bg=BACKGROUND_COLOR) + self.current_frame.pack(expand=True) + + # Заголовок + title = tk.Label( + self.current_frame, + text="Авторизация", + bg=BACKGROUND_COLOR, + fg=PRIMARY_COLOR, + font=BIG_FONT, + ) + title.pack(pady=50) + + # Логин + self.login_entry = tk.Entry(self.current_frame, font=FONT) + self.login_entry.pack(pady=10) + + # Пароль + self.password_entry = tk.Entry(self.current_frame, show="*", font=FONT) + self.password_entry.pack(pady=10) + + # Кнопка "Показать пароль" + show_password_button = tk.Button( + self.current_frame, + text="Показать пароль", + bg=BUTTON_COLOR, + fg=BUTTON_TEXT_COLOR, + font=FONT, + command=self.toggle_password, + ) + show_password_button.pack(pady=10) + + # Кнопка "Войти" + login_button = tk.Button( + self.current_frame, + text="Войти", + bg=BUTTON_COLOR, + fg=BUTTON_TEXT_COLOR, + font=FONT, + command=self.login_user, + ) + login_button.pack(pady=20) + + # Кнопка "Вернуться на главную" + back_button = tk.Button( + self.current_frame, + text="Вернуться на главную", + bg=BUTTON_COLOR, + fg=BUTTON_TEXT_COLOR, + font=FONT, + command=self.show_main_menu, + ) + back_button.pack(pady=20) + + def toggle_password(self): + """Переключение видимости пароля.""" + if self.password_entry.cget('show') == '*': + self.password_entry.config(show='') + else: + self.password_entry.config(show='*') + + def login_user(self): + """Проверка данных для авторизации.""" + login = self.login_entry.get() + password = self.password_entry.get() + + if login == ADMIN_LOGIN and password == ADMIN_PASSWORD: + messagebox.showinfo("Успех", "Вы успешно авторизованы как администратор!") + self.show_admin_panel() # Переходим к админ-панели + elif check_user(login, password): + messagebox.showinfo("Успех", "Вы успешно авторизованы!") + self.show_user_dashboard() # Переходим к панели пользователя + else: + messagebox.showerror("Ошибка", "Неверные данные. Попробуйте снова.") + + def show_admin_panel(self): + """Отображение интерфейса администратора.""" + self.clear_frame() + AdminApp(self.root) # Создаем экземпляр админ-панели + + def show_registration_screen(self): + """Показать экран регистрации.""" + self.clear_frame() + self.current_frame = tk.Frame(self.root, bg=BACKGROUND_COLOR) + self.current_frame.pack(expand=True) + + # Заголовок + title = tk.Label( + self.current_frame, + text="Регистрация", + bg=BACKGROUND_COLOR, + fg=PRIMARY_COLOR, + font=BIG_FONT, + ) + title.pack(pady=50) + + # Логин + self.reg_login_entry = tk.Entry(self.current_frame, font=FONT) + self.reg_login_entry.pack(pady=10) + + # Пароль + self.reg_password_entry = tk.Entry(self.current_frame, show="*", font=FONT) + self.reg_password_entry.pack(pady=10) + + # Кнопка "Показать пароль" + show_password_button = tk.Button( + self.current_frame, + text="Показать пароль", + bg=BUTTON_COLOR, + fg=BUTTON_TEXT_COLOR, + font=FONT, + command=self.toggle_registration_password, + ) + show_password_button.pack(pady=10) + + # Кнопка "Зарегистрироваться" + register_button = tk.Button( + self.current_frame, + text="Зарегистрироваться", + bg=BUTTON_COLOR, + fg=BUTTON_TEXT_COLOR, + font=FONT, + command=self.register_user, + ) + register_button.pack(pady=20) + + # Кнопка "Вернуться на главную" + back_button = tk.Button( + self.current_frame, + text="Вернуться на главную", + bg=BUTTON_COLOR, + fg=BUTTON_TEXT_COLOR, + font=FONT, + command=self.show_main_menu, + ) + back_button.pack(pady=20) + + def toggle_registration_password(self): + """Переключение видимости пароля для регистрации.""" + if self.reg_password_entry.cget('show') == '*': + self.reg_password_entry.config(show='') + else: + self.reg_password_entry.config(show='*') + + def register_user(self): + """Регистрация нового пользователя.""" + login = self.reg_login_entry.get() + password = self.reg_password_entry.get() + + if login and password: + create_user(login, password) + messagebox.showinfo("Успех", "Вы успешно зарегистрированы!") + self.show_login_screen() + else: + messagebox.showerror("Ошибка", "Пожалуйста, заполните все поля.") + + def show_user_dashboard(self): + """Перейти к главному меню пользователя после авторизации.""" + UserApp(self.root, self) + diff --git a/src/ui/user_ui.py b/src/ui/user_ui.py new file mode 100644 index 0000000..703daba --- /dev/null +++ b/src/ui/user_ui.py @@ -0,0 +1,56 @@ +import tkinter as tk +from config import BACKGROUND_COLOR, PRIMARY_COLOR, BUTTON_COLOR, BUTTON_TEXT_COLOR, FONT + +class UserApp: + def __init__(self, root, dog_academy_app): + self.root = root + self.dog_academy_app = dog_academy_app # Сохраняем ссылку на DogAcademyApp + self.show_user_dashboard() + + def show_user_dashboard(self): + """Показать интерфейс пользователя.""" + self.clear_frame() + self.current_frame = tk.Frame(self.root, bg=BACKGROUND_COLOR) + self.current_frame.pack(expand=True) + + # Заголовок + title = tk.Label( + self.current_frame, + text="Главное меню", + bg=BACKGROUND_COLOR, + fg=PRIMARY_COLOR, + font=FONT, + ) + title.pack(pady=50) + + # Кнопка "Играть" + play_button = tk.Button( + self.current_frame, + text="Играть", + bg=BUTTON_COLOR, + fg=BUTTON_TEXT_COLOR, + font=FONT, + command=self.play_game, + ) + play_button.pack(pady=20) + + # Кнопка "Выход" + logout_button = tk.Button( + self.current_frame, + text="Выход", + bg=BUTTON_COLOR, + fg=BUTTON_TEXT_COLOR, + font=FONT, + command=self.dog_academy_app.show_main_menu, # Вызываем метод из DogAcademyApp + ) + logout_button.pack(pady=20) + + def play_game(self): + """Запуск игры.""" + # TODO: Логика игры + pass + + def clear_frame(self): + """Очистить текущий фрейм.""" + if hasattr(self, 'current_frame') and self.current_frame: + self.current_frame.destroy()