починил авторизацию, ускорил систему с помощью сервера, сделал спрайты по правильному

This commit is contained in:
2023-02-02 19:08:31 +07:00
parent a451ce7e84
commit 0bfa52f011
14 changed files with 328 additions and 104 deletions
+1 -1
View File
@@ -1,4 +1,4 @@
[Settings] [Settings]
difficulty = Ïðîñòàÿ difficulty = Проигрывать весело
sound = True sound = True
+40 -49
View File
@@ -1,10 +1,46 @@
from loguru import logger from loguru import logger
from PyQt5 import uic from PyQt5 import uic
import sys import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QDialog from PyQt5.QtWidgets import QApplication, QDialog
from PyQt5.QtGui import QIcon from PyQt5.QtGui import QIcon
from modules.Game import Game from modules.Game import Game
from modules.Mathematics import start_calculating from modules.Mathematics import start_calculating
import requests
class Login(QDialog):
"""Авторизация пользователя по логину и паролю"""
def __init__(self):
super().__init__()
self.w1 = None
uic.loadUi('login.ui', self)
self.setWindowIcon(QIcon('web.png'))
"""задаём в качестве иконки приложения мою любимую пикчу с жабой"""
"""любите жаб!"""
self.setWindowTitle('login')
self.Check_Button.clicked.connect(self.authorization)
def show_window_1(self):
self.w1 = Login()
self.Check_Button.clicked.connect(self.authorization)
self.w1.Check_Button.clicked.connect(self.w1.close)
self.w1.show()
def authorization(self):
"""Функция отвечающая за проверку введённого пароля"""
response = requests.get("http://194.61.1.147:52540/authorization",
params={
"login": self.Login_input.text(),
"password": self.Password_input.text()
})
if response.status_code == 200:
self.close()
from modules.GameMenu import difficulty
game = Game(difficulty)
game.start()
else:
print(response.text)
def main(): def main():
@@ -12,56 +48,11 @@ def main():
logger.add("conf/log.log", level="DEBUG") logger.add("conf/log.log", level="DEBUG")
logger.info("Игра запущена") logger.info("Игра запущена")
start_calculating() start_calculating()
from modules.GameMenu import difficulty
game = Game(difficulty)
game.start()
class Login(QDialog):
"""авторизация пользователя по логину и паролю"""
def __init__(self):
super().__init__()
self.w1 = None
uic.loadUi('login.ui', self)
self.setWindowIcon(QIcon('web.png'))
"""задаём в качевстве иконки приложения мою любимую пикчу с жабой"""
"""любите жаб!"""
self.setWindowTitle('login')
self.Check_Button.clicked.connect(self.autorization)
def show_window_1(self):
self.w1 = Login()
self.Check_Button.clicked.connect(self.autorization)
self.w1.Check_Button.clicked.connect(self.w1.close)
self.w1.show()
def autorization(self):
"""функция отвечающая за проверку введённого пароля"""
login = "j"
password = "y"
full_password = "your"
full_login = "jaba"
if self.Login_input.text() == login and \
self.Password_input.text() == password:
main()
elif self.Login_input.text() == full_login and \
self.Password_input.text() == full_password:
"""записываем результаты ввода пароля в файл check.txt
(разные возможности в зависимости от пользователя)"""
check = open("check.txt", mode="r")
if not check.readline():
check = open("check.txt", mode="w", encoding='UTF-8')
check.write('успешно')
check.close()
main()
def start():
"""запуск окна авторизации"""
app = QApplication(sys.argv) app = QApplication(sys.argv)
ex = Login() ex = Login()
ex.show() ex.show()
sys.exit(app.exec()) app.exec()
start() if __name__ == '__main__':
main()
+10 -3
View File
@@ -1,5 +1,6 @@
import pygame as pg import pygame as pg
from modules import DB from modules import DB
from modules.sprites import FrogsInBook
def get_frogs_img(name): def get_frogs_img(name):
@@ -65,9 +66,15 @@ class Book: # Окно с необходимой информацией
i = row + 6 i = row + 6
else: else:
i = row + 9 i = row + 9
myimage = pg.image.load(get_frogs_img(frogs[i][0]))
scaled_image = pg.transform.smoothscale(myimage, (34, 34)) all_sprites = pg.sprite.Group()
screen.blit(scaled_image, (100 + 120 * col + 1, 375 + 40 * row + 1)) FrogsInBook(get_frogs_img(frogs[i][0]), 100 + 120 * col + 1, 375 + 40 * row + 1, all_sprites)
all_sprites.draw(screen)
all_sprites.update()
# myimage = pg.image.load(get_frogs_img(frogs[i][0]))
# scaled_image = pg.transform.smoothscale(myimage, (34, 34))
# screen.blit(scaled_image, (100 + 120 * col + 1, 375 + 40 * row + 1))
pg.draw.rect(screen, (0, 0, 0), (100 + 120 * col, 375 + 40 * row, 35, 35), pg.draw.rect(screen, (0, 0, 0), (100 + 120 * col, 375 + 40 * row, 35, 35),
3) # Рамка с портретом лягушки 3) # Рамка с портретом лягушки
text = font.render(f'{frogs[i][0]} - ', True, (255, 255, 255)) text = font.render(f'{frogs[i][0]} - ', True, (255, 255, 255))
+2 -2
View File
@@ -2,6 +2,7 @@ import pygame
import pygame_menu import pygame_menu
import configparser import configparser
from modules.DB import UseDB from modules.DB import UseDB
import requests
def set_difficulty(value: dict, _) -> None: def set_difficulty(value: dict, _) -> None:
@@ -44,8 +45,7 @@ def start_new_game() -> None:
config['Settings']['sound'] = sound # перезаписываю настройку звука config['Settings']['sound'] = sound # перезаписываю настройку звука
with open('conf/config.ini', 'w') as configfile: # открываю файл для записи with open('conf/config.ini', 'w') as configfile: # открываю файл для записи
config.write(configfile) # записываю config.write(configfile) # записываю
db = UseDB("game") requests.get("http://194.61.1.147:52540/create_new_game")
db.create_new_game()
menu.toggle() # останавливаю меню menu.toggle() # останавливаю меню
+8 -30
View File
@@ -1,44 +1,22 @@
from modules.DB import UseDB from modules.DB import UseDB
from loguru import logger from loguru import logger
import random
import configparser import configparser
import requests
def get_random_event(): def get_random_event():
db = UseDB("events") response = requests.get("http://194.61.1.147:52540/get_random_event")
response = db.find_document({}) return response.json()
random_event = random.choices([i["_id"] for i in response],
weights=[i["probability"] for i in response])
return db.find_document({"_id": random_event[0]})[0]
def recalculation_events(well): def recalculation_events(well):
difficulties = {
"Простая": [5, 5],
"Средняя": [5, 2],
"Сложная": [5, 1],
"Проигрывать весело": [10, 1]
}
config = configparser.ConfigParser() config = configparser.ConfigParser()
config.read("conf/config.ini") config.read("conf/config.ini")
difficulty = config['Settings']['difficulty'] requests.get("http://194.61.1.147:52540/recalculation_events",
db = UseDB("events") params={
not_well_events = db.find_document({"well": False}) "well": well,
well_events = db.find_document({"well": True}) "difficulty": config['Settings']['difficulty']
if well: })
for i in not_well_events:
db.update_document({"_id": i["_id"]},
{"probability": i["probability"] + difficulties[difficulty][0]})
ratio = len(not_well_events) * difficulties[difficulty][0] / len(well_events)
for i in well_events:
db.update_document({"_id": i["_id"]}, {"probability": i["probability"] - ratio})
else:
for i in well_events:
db.update_document({"_id": i["_id"]},
{"probability": i["probability"] + difficulties[difficulty][1]})
ratio = len(well_events) * difficulties[difficulty][1] / len(not_well_events)
for i in not_well_events:
db.update_document({"_id": i["_id"]}, {"probability": i["probability"] - ratio})
def start_calculating(): def start_calculating():
+26 -18
View File
@@ -7,16 +7,23 @@ class Game:
def __init__(self): def __init__(self):
self.line = None self.line = None
self.old_color = None self.old_color = None
self.interval_x = None
self.interval_y = None self.interval_y = None
self.colors = [tuple([randrange(50, 256, 40) for _ in range(3)]) for _ in range(10)] self.interval_x = None
self.colors = [(235, 26, 26), (235, 26, 235), (51, 51, 255),
(255, 128, 0), (51, 255, 153), (255, 255, 0),
(255, 255, 255), (139, 69, 19), (0, 255, 127),
(255, 218, 185), (147, 112, 219), (128, 0, 128),
(128, 128, 0), (47, 79, 79), (139, 0, 0),
(255, 192, 203), (124, 252, 0), (46, 139, 87),
(0, 128, 128), (0, 255, 255)]
self.need_colors = sample(self.colors, 10)
self.intervals_x = [(430, 460), (350, 430), (245, 350), (165, 245), (130, 165), (130, 165), (165, 245), self.intervals_x = [(430, 460), (350, 430), (245, 350), (165, 245), (130, 165), (130, 165), (165, 245),
(245, 350), (350, 430), (430, 460)] (245, 350), (350, 430), (430, 460)]
self.intervals_y = [(170, 265), (113, 170), (113, 113), (113, 170), (170, 265), (265, 360), (360, 425), self.intervals_y = [(170, 265), (113, 170), (113, 113), (113, 170), (170, 265), (265, 360), (360, 425),
(425, 425), (365, 425), (265, 365)] (425, 425), (365, 425), (265, 365)]
self.line_color = choice(self.colors) self.line_color = choice(self.need_colors)
self.clock = pg.time.Clock() self.clock = pg.time.Clock()
self.speed = 15 # Здесь можно менять скорость self.speed = 25 # Здесь можно менять скорость
self.right = False self.right = False
self.lose = False self.lose = False
self.corner = 440 self.corner = 440
@@ -25,25 +32,25 @@ class Game:
self.y = 430 self.y = 430
def render(self, screen_move): # Создание круга из случайных цветов и стрелки def render(self, screen_move): # Создание круга из случайных цветов и стрелки
pg.draw.arc(screen_move, (self.colors[0]), pg.draw.arc(screen_move, (self.need_colors[0]),
(120, 90, 350, 350), 0, pi / 5, 7) (120, 90, 350, 350), 0, pi / 5, 7)
pg.draw.arc(screen_move, (self.colors[1]), pg.draw.arc(screen_move, (self.need_colors[1]),
(120, 90, 350, 350), pi / 5, 2 * pi / 5, 7) (120, 90, 350, 350), pi / 5, 2 * pi / 5, 7)
pg.draw.arc(screen_move, (self.colors[2]), pg.draw.arc(screen_move, (self.need_colors[2]),
(120, 90, 350, 350), 2 * pi / 5, 3 * pi / 5, 7) (120, 90, 350, 350), 2 * pi / 5, 3 * pi / 5, 7)
pg.draw.arc(screen_move, (self.colors[3]), pg.draw.arc(screen_move, (self.need_colors[3]),
(120, 90, 350, 350), 3 * pi / 5, 4 * pi / 5, 7) (120, 90, 350, 350), 3 * pi / 5, 4 * pi / 5, 7)
pg.draw.arc(screen_move, (self.colors[4]), pg.draw.arc(screen_move, (self.need_colors[4]),
(120, 90, 350, 350), 4 * pi / 5, pi, 7) (120, 90, 350, 350), 4 * pi / 5, pi, 7)
pg.draw.arc(screen_move, (self.colors[5]), pg.draw.arc(screen_move, (self.need_colors[5]),
(120, 90, 350, 350), pi, 6 * pi / 5, 7) (120, 90, 350, 350), pi, 6 * pi / 5, 7)
pg.draw.arc(screen_move, (self.colors[6]), pg.draw.arc(screen_move, (self.need_colors[6]),
(120, 90, 350, 350), 6 * pi / 5, 7 * pi / 5, 7) (120, 90, 350, 350), 6 * pi / 5, 7 * pi / 5, 7)
pg.draw.arc(screen_move, (self.colors[7]), pg.draw.arc(screen_move, (self.need_colors[7]),
(120, 90, 350, 350), 7 * pi / 5, 8 * pi / 5, 7) (120, 90, 350, 350), 7 * pi / 5, 8 * pi / 5, 7)
pg.draw.arc(screen_move, (self.colors[8]), pg.draw.arc(screen_move, (self.need_colors[8]),
(120, 90, 350, 350), 8 * pi / 5, 9 * pi / 5, 7) (120, 90, 350, 350), 8 * pi / 5, 9 * pi / 5, 7)
pg.draw.arc(screen_move, (self.colors[9]), pg.draw.arc(screen_move, (self.need_colors[9]),
(120, 90, 350, 350), 9 * pi / 5, 2 * pi, 7) (120, 90, 350, 350), 9 * pi / 5, 2 * pi, 7)
pg.draw.line(screen_move, self.line_color, [300, 270], [self.x, self.y], 9) pg.draw.line(screen_move, self.line_color, [300, 270], [self.x, self.y], 9)
@@ -64,13 +71,14 @@ class Game:
if color_change: if color_change:
self.old_color = self.line_color self.old_color = self.line_color
while self.old_color == self.line_color: while self.old_color == self.line_color:
self.line_color = choice(self.colors) self.line_color = choice(self.need_colors)
self.interval_x = self.intervals_x[self.colors.index(self.old_color)] self.interval_x = self.intervals_x[self.need_colors.index(self.old_color)]
self.interval_y = self.intervals_y[self.colors.index(self.old_color)] self.interval_y = self.intervals_y[self.need_colors.index(self.old_color)]
if self.interval_x[0] <= round(self.x) <= self.interval_x[1] and \ if self.interval_x[0] <= round(self.x) <= self.interval_x[1] and \
((round(self.y) <= self.interval_y[0] == self.interval_y[1]) or ((round(self.y) <= self.interval_y[0] == self.interval_y[1]) or
(self.interval_y[0] <= round(self.y) <= self.interval_y[1])): (self.interval_y[0] <= round(self.y) <= self.interval_y[1]) or
(round(self.y) >= self.interval_y[0] == self.interval_y[1])):
self.scores += 1 self.scores += 1
self.speed += 10 self.speed += 10
else: else:
+22
View File
@@ -0,0 +1,22 @@
import os
import sys
import pygame
def load_image(name, x, y):
fullname = os.path.join(name)
if not os.path.isfile(fullname):
print(f"Файл с изображением '{fullname}' не найден")
sys.exit()
image = pygame.image.load(fullname)
image = pygame.transform.smoothscale(image, (x, y))
return image
class FrogsInBook(pygame.sprite.Sprite):
def __init__(self, img, x, y, *group):
super().__init__(*group)
self.image = load_image(img, 34, 34)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
+3
View File
@@ -7,3 +7,6 @@ setuptools==65.6.3
wheel==0.38.4 wheel==0.38.4
configparser==5.3.0 configparser==5.3.0
pygame-menu==4.3.2 pygame-menu==4.3.2
PyQt5~=5.15.8
requests~=2.28.2
certifi~=2022.12.7
+131
View File
@@ -0,0 +1,131 @@
from pymongo import MongoClient
class UseDB:
"""
Класс для работы с базой данных
"""
def __init__(self, collection_name):
self.series_collection = None
self.client = MongoClient('194.61.1.147', 52530)
self.db = self.client['toads']
self.series_collection = self.db[collection_name]
def find_document(self, elements: dict) -> list:
"""
Функция поиска элемента в базе данных
:param elements: dict - элемент, который надо искать
:return: list - сам элемент
"""
return [x for x in self.series_collection.find(elements)]
def insert_document(self, data: dict) -> list:
"""
Функция добавления элемента в базу данных
:param data: dict - элемент, который надо добавить
:return: list - созданный элемент
"""
return self.series_collection.insert_one(data).inserted_id
def update_document(self, query_elements: dict, new_values: dict) -> None:
"""
Функция обновления элемента в базе данных
:param query_elements: dict - элемент, который надо обновить
:param new_values: dict - элемент, этот самый элемент
:return: None
"""
self.series_collection.update_one(query_elements, {'$set': new_values})
def del_document(self, query_elements: dict) -> None:
"""
Функция удаления элемента в базу данных
:param query_elements: dict - элемент, который надо удалить
:return: None
"""
self.series_collection.delete_one(query_elements)
def create_new_game(self):
import datetime
data_now = datetime.datetime.now()
new_format_data = data_now.strftime("%d.%m.%Y")
self.series_collection.drop()
self.series_collection.insert_one({
"day": 0,
"frogs": [
{
"name": "Квакуша",
"hp": 100,
"hunger": 0
},
{
"name": "Квакша",
"hp": 100,
"hunger": 0
},
{
"name": "Квак",
"hp": 100,
"hunger": 0
},
{
"name": "Ква",
"hp": 100,
"hunger": 0
},
{
"name": "Кваква",
"hp": 100,
"hunger": 0
},
{
"name": "Джабба-хатт",
"hp": 100,
"hunger": 0
},
{
"name": "Квендальф",
"hp": 100,
"hunger": 0
},
{
"name": "Лягуша",
"hp": 100,
"hunger": 0
},
{
"name": "Жаба",
"hp": 100,
"hunger": 0
},
{
"name": "Абажаю",
"hp": 100,
"hunger": 0
},
{
"name": "Пучеглазый",
"hp": 100,
"hunger": 0
},
{
"name": "Вафля",
"hp": 100,
"hunger": 0
}
],
"money": 0,
"save": {
"name": "start",
"data": new_format_data
}
})
+13
View File
@@ -0,0 +1,13 @@
from fastapi import responses, status
from DB import UseDB
from secrets import compare_digest
def authorization(login, password):
db = UseDB("accounts")
response = db.find_document({"login": login})
if not response:
return responses.JSONResponse(status_code=status.HTTP_401_UNAUTHORIZED, content="Нет такого логина")
if not compare_digest(response[0]["password"], password):
return responses.JSONResponse(status_code=status.HTTP_401_UNAUTHORIZED, content="Ошибка пароля")
return responses.JSONResponse(status_code=status.HTTP_200_OK, content=" ")
+15
View File
@@ -0,0 +1,15 @@
import random
from fastapi import responses, status
from DB import UseDB
from fastapi import Response
import json
def get_random_event_func():
db = UseDB("events")
response = db.find_document({})
random_event = random.choices([i["_id"] for i in response],
weights=[i["probability"] for i in response])
json_str = json.dumps(db.find_document({"_id": random_event[0]})[0], indent=4, default=str)
return Response(content=json_str, media_type='application/json')
@@ -0,0 +1,27 @@
from DB import UseDB
def recalculation_events_func(difficulty, well):
difficulties = {
"Простая": [5, 5],
"Средняя": [5, 2],
"Сложная": [5, 1],
"Проигрывать весело": [10, 1]
}
db = UseDB("events")
not_well_events = db.find_document({"well": False})
well_events = db.find_document({"well": True})
if well:
for i in not_well_events:
db.update_document({"_id": i["_id"]},
{"probability": i["probability"] + difficulties[difficulty][0]})
ratio = len(not_well_events) * difficulties[difficulty][0] / len(well_events)
for i in well_events:
db.update_document({"_id": i["_id"]}, {"probability": i["probability"] - ratio})
else:
for i in well_events:
db.update_document({"_id": i["_id"]},
{"probability": i["probability"] + difficulties[difficulty][1]})
ratio = len(well_events) * difficulties[difficulty][1] / len(not_well_events)
for i in not_well_events:
db.update_document({"_id": i["_id"]}, {"probability": i["probability"] - ratio})
+25
View File
@@ -0,0 +1,25 @@
from fastapi import FastAPI
from functinos import authorization, recalculation_events_func, get_random_event_func
from DB import UseDB
app = FastAPI()
@app.get("/authorization")
async def root(login: str, password: str):
return authorization.authorization(login, password)
@app.get("/create_new_game")
async def root():
return UseDB("game").create_new_game()
@app.get("/recalculation_events")
async def recalculation_events(difficulty: str, well: bool):
return recalculation_events_func.recalculation_events_func(difficulty, well)
@app.get("/get_random_event")
async def get_random_event():
return get_random_event_func.get_random_event_func()
+4
View File
@@ -0,0 +1,4 @@
GET http://194.61.1.147:52540/get_random_event
Accept: application/json
###