починил все баги

начал доставать всё из базы
сделал новую игру
This commit is contained in:
2023-01-26 17:01:39 +07:00
parent d86f87f64f
commit a877b80606
6 changed files with 257 additions and 29 deletions
+13 -19
View File
@@ -1,35 +1,29 @@
import pygame as pg
from modules import DB
class Book: # Окно с необходимой информацией
@staticmethod
def info(screen, event):
db = DB.UseDB("game")
response = db.find_document({})[0]
pg.draw.rect(screen, (38, 33, 55), (85, 0, 520, 500))
pg.draw.rect(screen, (255, 255, 255), (100, 90, 495, 280), 1)
texts = ['День ***', 'Сегодня произошло следующее:', f"{event['name']}\n{event['description']}"]
sizes = [60, 30, 30]
coords = [(260, 30), (110, 100), (110, 150)]
texts = [f'День {response["day"]}', 'Сегодня произошло следующее:',
f"{event['name']}", f"{event['description']}"]
sizes = [60, 30, 30, 30]
coords = [(260, 30), (110, 100), (110, 150), (110, 190)]
for i in range(len(texts)):
font = pg.font.Font(None, sizes[i])
text = font.render(texts[i], True, (255, 255, 255))
screen.blit(text, coords[i])
frogs = [('Квакуша', [100, 100]),
('Квакша', [100, 100]),
('Квак', [100, 100]),
('Ква', [100, 100]),
('Кваква', [100, 100]),
('Джабба-хатт', [100, 100]),
('Квендальф', [100, 100]),
('Лягуша', [100, 100]),
('Жаба', [100, 100]),
('Абажаю', [100, 100]),
('Пучеглазый', [100, 100]),
('Вафля', [100, 100])] # Имя лягушки со здоровьем и сытостью (как пример)
frogs = []
for i in response["frogs"]:
frogs.append((i["name"], [i["hp"], i["hunger"]]))
font = pg.font.Font(None, 15) # Здесь будет указана информация о некоторых лягушках
for col in range(4):
for row in range(3):
for col in range(1):
for row in range(1):
pg.draw.rect(screen, (255, 255, 255), (100 + 120 * col, 375 + 40 * row, 35, 35),
1) # Рамка с портретом лягушки
if col == 0:
@@ -44,5 +38,5 @@ class Book: # Окно с необходимой информацией
screen.blit(text, (140 + 120 * col, 375 + 40 * row))
text = font.render(f'{frogs[i][-1][0]}% зд.,', True, (255, 255, 255))
screen.blit(text, (140 + 120 * col, 385 + 40 * row))
text = font.render(f'{frogs[i][-1][1]}% сыт.', True, (255, 255, 255))
text = font.render(f'{frogs[i][-1][1]}% голода', True, (255, 255, 255))
screen.blit(text, (140 + 120 * col, 395 + 40 * row))
+17
View File
@@ -5,6 +5,7 @@ class UseDB:
"""
Класс для работы с базой данных
"""
def __init__(self, collection_name):
self.series_collection = None
self.client = MongoClient('194.61.1.147', 52530)
@@ -52,3 +53,19 @@ class UseDB:
:return: None
"""
self.series_collection.delete_one(query_elements)
def create_new_game(self):
self.series_collection.drop()
self.series_collection.insert_one({
"day": 0,
"frogs": [{
"name": "Квакуша",
"hp": 100,
"hunger": 0
}],
"money": 0,
"save": {
"name": "start",
"data": "25.01.2023" # TODO:получить дату нормально
}
})
+20 -2
View File
@@ -1,6 +1,7 @@
import pygame
import pygame_menu
import configparser
from modules.DB import UseDB
def set_difficulty(value: dict, _) -> None:
@@ -21,6 +22,20 @@ def start_the_game() -> None:
"""
Функция запуска игры
:return: None
"""
config = configparser.ConfigParser() # создаю объект ConfigParser
config.read('conf/config.ini') # читаю файл
config['Settings']['sound'] = sound # перезаписываю настройку звука
with open('conf/config.ini', 'w') as configfile: # открываю файл для записи
config.write(configfile) # записываю
menu.toggle() # останавливаю меню
def start_new_game() -> None:
"""
Функция запуска игры
:return: None
"""
config = configparser.ConfigParser() # создаю объект ConfigParser
@@ -29,6 +44,8 @@ def start_the_game() -> None:
config['Settings']['sound'] = sound # перезаписываю настройку звука
with open('conf/config.ini', 'w') as configfile: # открываю файл для записи
config.write(configfile) # записываю
db = UseDB("game")
db.create_new_game()
menu.toggle() # останавливаю меню
@@ -56,12 +73,13 @@ surface = pygame.display.set_mode((600, 400)) # создаю полотно
mytheme = pygame_menu.themes.THEME_DARK.copy() # создаю свою тему
mytheme.background_color = pygame_menu.baseimage.BaseImage(image_path='styles/background.jpg')
# натягиваю свой background
menu = pygame_menu.Menu('Welcome', 600, 400, theme=mytheme) # создаю меню
menu = pygame_menu.Menu('Toads', 600, 400, theme=mytheme) # создаю меню
menu.add.label("Сложность") # добавляю label сложности
menu.add.selector('', [('Простая', 1), ('Средняя', 2), ('Сложная', 3), ('Проигрывать весело', 4)],
onchange=set_difficulty) # добавляю selector с выбором сложности
menu.add.label("Музыка") # добавляю label музыки
menu.add.selector('', [("Да", 1), ("Нет", 1)], onchange=test) # добавляю selector с выбором настроек музыки
menu.add.button('Play', start_the_game) # добавляю кнопку начала игры
menu.add.button('Продолжить', start_the_game) # добавляю кнопку начала игры
menu.add.button('Новая игра', start_new_game) # добавляю кнопку начала игры
menu.add.button('Quit', pygame_menu.events.EXIT) # добавляю кнопку выхода
menu.mainloop(surface) # запускаю меню
+10 -6
View File
@@ -1,5 +1,5 @@
import pygame as pg
from modules import Book, GameOver, Mathematics
from modules import Book, GameOver, Mathematics, DB
from modules.RewardWindow import RewardWindow
@@ -50,7 +50,8 @@ class Swamp:
(self.x, self.y, self.cell_size, self.cell_size), 1)
font = pg.font.Font(None, 50)
text_string = "Ваш баланс мух составляет: 1000"
db = DB.UseDB("game")
text_string = f"Ваш баланс мух составляет: {db.find_document({})[0]['money']}"
text = font.render(text_string, True, (255, 255, 255))
size = font.size(text_string)
screen.blit(text, (350 - (size[0] / 2.), 50))
@@ -87,12 +88,15 @@ class Swamp:
def get_cell(self, mouse_pos):
board_width = self.width * self.cell_size
board_height = self.height * self.cell_size
if self.left_area < mouse_pos[0] < self.left_area + board_width:
if self.top_area < mouse_pos[1] < self.top_area + board_height:
if self.left_area <= mouse_pos[0] <= self.left_area + board_width:
if self.top_area <= mouse_pos[1] <= self.top_area + board_height:
cell_coords = (mouse_pos[0] - self.top_area) // self.cell_size + 1, \
(mouse_pos[1] - self.left_area) // self.cell_size - 1
self.cell_info = self.board[cell_coords[1]][cell_coords[0]]
self.time_to_close = 100
try:
self.cell_info = self.board[cell_coords[1]][cell_coords[0]]
except IndexError:
self.cell_info = self.board[-1][cell_coords[0]]
self.time_to_close = 10
return cell_coords
elif self.left_book < mouse_pos[0] < self.right_book:
if self.top_book < mouse_pos[1] < self.down_book and self.book_use is False: