Ejemplo n.º 1
0
 def __init__(self, score: int = 0, time: int = 0) -> None:
     self.window = ManagerWindows().window_score_timer
     self.score = score
     self.time = time
     self.last_time = lib_time.time()
     self.start_pause_timer = 0
     self.pause_timer = 0
Ejemplo n.º 2
0
 def __init__(self):
     self.manager_window = ManagerWindows()
     self.window = self.manager_window.window_info
     self.window.keypad(True)
     self.current_color = 10
     self.normal_color = 12
     self.current_position = 0
     self.pointer = "->"
Ejemplo n.º 3
0
 def __init__(self):
     """
     window_magic_creater
     :param manager_window: ManagerWindows
     """
     self.window = ManagerWindows().window_magic_creater
     self.start_x = 5
     self.start_y = 2
     self.current_object = None
     self.create()
Ejemplo n.º 4
0
 def __init__(self):
     self.manager_window = ManagerWindows()
     self.window = self.manager_window.window_menu
     self.window.keypad(True)
     self.current_color = 10
     self.normal_color = 12
     self.disable_color = 14
     self.current_position = 1
     self.pointer = "->"
     self.inactive_resume_game = True
     self.menu_list = [(3, 2, "resume game"), (5, 2, "start new game"), (7, 2, "top ten players"),
                       (9, 2, "info"), (11, 2, "exit")]
Ejemplo n.º 5
0
 def __init__(self):
     self.manager_window = ManagerWindows()
     self.window = self.manager_window.window_top_players
     self.window.keypad(True)
     self.name = str()
     self.score = 0
     self.time = 0
     self.current_color = 10
     self.normal_color = 12
     self.actual_sorted = False
     self.top_dict = {}
     self.sorted_list = []
Ejemplo n.º 6
0
 def __init__(self, depth_win: int, weight_win: int, corner_win_y: int, corner_win_x: int):
     self.weight_win = weight_win
     self.depth_win = depth_win
     self.corner_win_y = corner_win_y
     self.corner_win_x = corner_win_x
     self.manager_window = ManagerWindows(self.depth_win, self.weight_win, self.corner_win_y, self.corner_win_x)
     self.magic_creater = MagicCrearter()
     self.score_timer = ScoreTime()
     self.game_field = GameField(self.magic_creater, self.score_timer)
     self.menu: Menu = Menu()
     self.top_players: TopPlayers = TopPlayers()
     #  self.top_players.load_from_file()
     self.top_players.load_from_json()
     self.info: Info = Info()
     self.score: int = 0
     self.time: int = 0
Ejemplo n.º 7
0
class Info:
    def __init__(self):
        self.manager_window = ManagerWindows()
        self.window = self.manager_window.window_info
        self.window.keypad(True)
        self.current_color = 10
        self.normal_color = 12
        self.current_position = 0
        self.pointer = "->"

    def exit_to_menu(self):
        self.manager_window.set_status(ManagerWindowsStatus.MENU)

    def draw(self):
        self.window.addstr(15, 2, str("Pres 'Enter' to exit the menu"), curses.color_pair(14))
        c = self.manager_window.get_char()
        if c == curses.KEY_ENTER or c == 10 or c == 13:
            self.exit_to_menu()
        self.window.addstr(1, 12, "info:", curses.color_pair(11))
        self.window.border()
        self.window.refresh()
Ejemplo n.º 8
0
 def __init__(self, magic_creater: MagicCrearter, score_object: ScoreTime):
     self.magic_creater = magic_creater
     self.score_object = score_object
     self.manager_window = ManagerWindows()
     """
     window_field
     :param window: window
     """
     self.window = self.manager_window.window_field
     self.max_x = self.window.getmaxyx()[1] - 2
     self.max_y = self.window.getmaxyx()[0] - 2
     self.start_x = 5
     self.start_y = 2
     self.arr = [0 for v in range(self.max_x * self.max_y)]
     self.cur_figura = self.magic_creater.create()
     self.cur_figura.re_init_window(self.window, self.start_x, self.start_y,
                                    self.arr)
     self.window.keypad(True)  # режим клавивиатуры
     self.window.nodelay(True)  # getch() будет неблокирующим.
     self.last_time = time.time()
     self.pause_timer = 0
     self.start_pause_timer = 0
     self.pause_down = 0.5
Ejemplo n.º 9
0
class MyFavoriteGame:
    weight_win: int
    dept_win: int
    corner_win_y: int
    corner_win_x: int
    score_timer: ScoreTime
    magic_creater: MagicCrearter
    game_field: GameField
    manager_window: ManagerWindows

    def __init__(self, depth_win: int, weight_win: int, corner_win_y: int, corner_win_x: int):
        self.weight_win = weight_win
        self.depth_win = depth_win
        self.corner_win_y = corner_win_y
        self.corner_win_x = corner_win_x
        self.manager_window = ManagerWindows(self.depth_win, self.weight_win, self.corner_win_y, self.corner_win_x)
        self.magic_creater = MagicCrearter()
        self.score_timer = ScoreTime()
        self.game_field = GameField(self.magic_creater, self.score_timer)
        self.menu: Menu = Menu()
        self.top_players: TopPlayers = TopPlayers()
        #  self.top_players.load_from_file()
        self.top_players.load_from_json()
        self.info: Info = Info()
        self.score: int = 0
        self.time: int = 0

    def run_game(self):
        while True:
            self.manager_window.run_events()  # запуск событий после нажатий клавиш
            kb_push = self.manager_window.get_char()  # получение нажатий клавиш
            match self.manager_window.get_status():
                case ManagerWindowsStatus.START_GAME:
                    self.score_timer.reset()
                    self.game_field.reset()
                    self.manager_window.set_status(ManagerWindowsStatus.PLAY)

                case ManagerWindowsStatus.RESUME:
                    self.score_timer.pause_stop()
                    self.game_field.pause_stop()
                    self.manager_window.set_status(ManagerWindowsStatus.PLAY)

                case ManagerWindowsStatus.PLAY:
                    self.game_field.draw()
                    """
                    появление изображения в окне window_score_timer
                    """
                    self.score_timer.draw()
                    """
                    появление изображения в окне window_magic_creater
                    """
                    self.magic_creater.draw()
                    """
                    создание переменной, в к-рой хранится значение нажатой клавиши
                    """
                    if kb_push == ord("p"):
                        self.manager_window.set_status(ManagerWindowsStatus.PAUSE)

                case ManagerWindowsStatus.END_GAME:
                    self.menu.from_end_game()
                    self.top_players.set_score_time(self.score_timer.get_score(), self.score_timer.get_time())
                    curses.echo()
                    curses.curs_set(1)
                    self.top_players.draw()

                case ManagerWindowsStatus.PAUSE:
                    self.score_timer.pause_start()
                    self.game_field.pause_start()
                    self.menu.menu_from_pause()
                    self.manager_window.set_status(ManagerWindowsStatus.MENU)

                case ManagerWindowsStatus.EXIT:
                    #  self.top_players.save_to_file()
                    self.top_players.save_to_json()
                    break

                case ManagerWindowsStatus.MENU:
                    self.menu.draw()

                case ManagerWindowsStatus.TOP_PLAYERS:
                    curses.noecho()
                    curses.curs_set(0)
                    self.top_players.draw()

                case ManagerWindowsStatus.INFO:
                    self.info.draw()

            self.manager_window.clear_get()  # очистка полученных символов
Ejemplo n.º 10
0
class Menu:

    def __init__(self):
        self.manager_window = ManagerWindows()
        self.window = self.manager_window.window_menu
        self.window.keypad(True)
        self.current_color = 10
        self.normal_color = 12
        self.disable_color = 14
        self.current_position = 1
        self.pointer = "->"
        self.inactive_resume_game = True
        self.menu_list = [(3, 2, "resume game"), (5, 2, "start new game"), (7, 2, "top ten players"),
                          (9, 2, "info"), (11, 2, "exit")]

    def resume_game(self):
        self.manager_window.set_status(ManagerWindowsStatus.RESUME)

    def start_new_game(self):
        self.manager_window.set_status(ManagerWindowsStatus.START_GAME)

    def score(self):
        self.manager_window.set_status(ManagerWindowsStatus.TOP_PLAYERS)

    def exit(self):
        self.manager_window.set_status(ManagerWindowsStatus.EXIT)

    def info(self):
        self.manager_window.set_status(ManagerWindowsStatus.INFO)

    def from_end_game(self):
        self.current_position = 1
        self.inactive_resume_game = True

    def menu_from_pause(self):
        self.current_position = 0
        self.inactive_resume_game = False

    def pointer_up(self):
        self.current_position -= 1
        if self.current_position <= 0 and self.inactive_resume_game is True:
            self.current_position = 4
        elif self.current_position <= -1 and self.inactive_resume_game is False:
            self.current_position = 4

    def pointer_down(self):
        self.current_position += 1
        if self.current_position >= len(self.menu_list):
            if self.inactive_resume_game is False:
                self.current_position = 0
            else:
                self.current_position = 1

    def draw(self):
        self.window.clear()
        c = self.manager_window.get_char()
        if c == curses.KEY_UP:
            self.pointer_up()
        elif c == curses.KEY_DOWN:
            self.pointer_down()
        elif c == curses.KEY_ENTER or c == 10 or c == 13:
            match self.current_position:
                case 0:
                    self.resume_game()
                case 1:
                    self.start_new_game()
                case 2:
                    self.score()
                case 3:
                    self.info()
                case 4:
                    self.exit()

        self.window.addstr(1, 7, "menu:", curses.color_pair(11))
        for index in range(len(self.menu_list)):
            y, x, str_val = self.menu_list[index]
            if index == self.current_position:
                temp_color = self.current_color
                x = 1
                str_val = self.pointer + " " + str_val
            elif index == 0 and self.inactive_resume_game is True:
                temp_color = self.disable_color
            else:
                temp_color = self.normal_color
            self.window.addstr(y, x, str_val, curses.color_pair(temp_color))
        self.window.border()
        self.window.refresh()
Ejemplo n.º 11
0
class TopPlayers:
    def __init__(self):
        self.manager_window = ManagerWindows()
        self.window = self.manager_window.window_top_players
        self.window.keypad(True)
        self.name = str()
        self.score = 0
        self.time = 0
        self.current_color = 10
        self.normal_color = 12
        self.actual_sorted = False
        self.top_dict = {}
        self.sorted_list = []

    @staticmethod
    def convert_to_format(sec):
        hour = sec // 3600
        sec %= 3600
        min = sec // 60
        sec %= 60
        return "%d:%02d:%02d" % (hour, min, sec)

    def exit_to_menu(self):
        self.manager_window.set_status(ManagerWindowsStatus.MENU)

    def exit_to_top(self):
        self.manager_window.set_status(ManagerWindowsStatus.TOP_PLAYERS)

    def set_score_time(self, score, time):
        self.score = score
        self.time = time

    def load_from_file(self):
        try:
            with open("top_players") as filename:
                for line in filename:
                    read_str = line.split(";")
                    if read_str[2][-1] == "\n":
                        value = read_str[2][0:-1]
                    else:
                        value = read_str[2]
                    self.top_dict[KeyScore(int(read_str[0]), int(read_str[1]))] = value
        except FileNotFoundError:
            return None

    def save_to_file(self):
        with open("top_players", "w") as filename:
            for key, value in self.top_dict.items():
                write_str = str(key.score) + ";" + str(key.time) + ";" + value
                filename.write(write_str)
                filename.write("\n")

    def load_from_json(self):
        try:
            with open("top_players.json") as filename:
                file_json = json.load(filename)
                x_file = [line for line in file_json]
                for i in x_file:
                    self.top_dict[KeyScore(file_json[i]["score"], file_json[i]["time"])] = i
        except FileNotFoundError:
            return None

    def save_to_json(self):
        with open("top_players.json", "w") as write_file:
            json.dump(to_json(self.top_dict), write_file, default=default, indent=4)

    def compare_result(self):
        if self.top_dict == {}:
            self.top_dict[KeyScore(self.score, self.time)] = self.name
            self.actual_sorted = False
        else:
            result_in_top = False
            sort_key = sorted(self.top_dict.keys())
            true_index = -1
            for data in sort_key:
                true_index += 1
                if true_index >= 10:
                    break
            if sort_key[true_index].score < self.score or true_index < 10:
                result_in_top = True
            elif sort_key[true_index].score == self.score and sort_key[true_index].time >= self.time:
                result_in_top = True
            if result_in_top is True:
                self.top_dict[KeyScore(self.score, self.time)] = self.name
                self.actual_sorted = False
        self.name = str()
        self.score = 0
        self.time = 0

    def draw(self):
        self.window.addstr(1, 10, "top players:", curses.color_pair(11))
        self.window.addstr(2, 1, "№  score   time      name        ", curses.COLOR_YELLOW)
        if self.actual_sorted is False:
            self.sorted_list = sorted(self.top_dict.items())
            self.actual_sorted = True
        n: int = 3
        for key, name in self.sorted_list:
            str_time = TopPlayers.convert_to_format(key.time)
            top_str = str(n - 2).ljust(3) + str(key.score).ljust(8) + str(str_time).ljust(10) + str(name).ljust(12)
            self.window.addstr(n, 1, top_str, curses.color_pair(10))
            n += 1
            if n > 12:
                break
        x_name: int = 22
        if self.manager_window.get_status() == ManagerWindowsStatus.END_GAME:
            str_time = TopPlayers.convert_to_format(self.time)
            self.window.border()
            self.window.refresh()
            self.window.addstr(n + 2, 1, str("Enter your name. Do not use ';'"), curses.color_pair(12))
            self.window.addstr(n + 3, 1, str("and no more than 12 characters."), curses.color_pair(12))
            self.window.addstr(n + 4, 1, str("And then press 'Enter'"), curses.color_pair(12))
            self.window.addstr(n + 1, 4, str(self.score), curses.color_pair(14))
            self.window.addstr(n + 1, 12, str_time, curses.color_pair(14))
            self.window.addstr(n + 1, x_name, str("____________"), curses.color_pair(14))
            self.name = str(self.window.getstr(n + 1, x_name, 12))
            while self.name.find(";") != -1:
                self.window.addstr(n + 1, x_name, str("____________"), curses.color_pair(14))
                self.window.border()
                self.window.refresh()
                self.name = str(self.window.getstr(n + 1, x_name, 12))
            self.name = self.name[2:-1]
            self.compare_result()
            self.exit_to_top()
            self.window.border()
            self.window.refresh()
        elif self.manager_window.get_status() == ManagerWindowsStatus.TOP_PLAYERS:
            self.window.addstr(15, 2, str("Press 'Enter' to exi the menu"), curses.color_pair(14))
            c = self.manager_window.get_char()
            if c == curses.KEY_ENTER or c == 10 or c == 13:
                self.exit_to_menu()
            self.window.border()
            self.window.refresh()
Ejemplo n.º 12
0
class MagicCrearter:
    manager_window: ManagerWindows
    start_x: int
    start_y: int
    current_object: None | Figura1 | Figura2 | Figura3 | Figura4 | Figura5 | Figura6 | Figura7 = None
    window: curses

    def __init__(self):
        """
        window_magic_creater
        :param manager_window: ManagerWindows
        """
        self.window = ManagerWindows().window_magic_creater
        self.start_x = 5
        self.start_y = 2
        self.current_object = None
        self.create()

    def create(self) -> Union[Figura1, Figura2, Figura3, Figura4, Figura5, Figura6, Figura7]:
        prev_obj = self.current_object
        rd = random.randint(1, 20)
        if rd == 1:
            self.current_object = Figura3(self.start_x, self.start_y, self.window)
        elif rd == 2:
            self.current_object = Figura3(self.start_x, self.start_y, self.window, 1)
        elif rd == 3:
            self.current_object = Figura3(self.start_x, self.start_y, self.window, 2)
        elif rd == 4:
            self.current_object = Figura3(self.start_x, self.start_y, self.window, 3)
        elif rd == 5:
            self.current_object = Figura1(self.start_x, self.start_y, self.window)
        elif rd == 6:
            self.current_object = Figura1(self.start_x, self.start_y, self.window, 1)
        elif rd == 7:
            self.current_object = Figura2(self.start_x, self.start_y, self.window)
        elif rd == 8:
            self.current_object = Figura2(self.start_x, self.start_y, self.window, 1)
        elif rd == 9:
            self.current_object = Figura2(self.start_x, self.start_y, self.window, 2)
        elif rd == 10:
            self.current_object = Figura2(self.start_x, self.start_y, self.window, 3)
        elif rd == 11:
            self.current_object = Figura4(self.start_x, self.start_y, self.window)
        elif rd == 12:
            self.current_object = Figura4(self.start_x, self.start_y, self.window, 1)
        elif rd == 13:
            self.current_object = Figura4(self.start_x, self.start_y, self.window, 2)
        elif rd == 14:
            self.current_object = Figura4(self.start_x, self.start_y, self.window, 3)
        elif rd == 15:
            self.current_object = Figura5(self.start_x, self.start_y, self.window)
        elif rd == 16:
            self.current_object = Figura5(self.start_x, self.start_y, self.window, 1)
        elif rd == 17:
            self.current_object = Figura6(self.start_x, self.start_y, self.window)
        elif rd == 18:
            self.current_object = Figura6(self.start_x, self.start_y, self.window, 1)
        elif rd == 19 or 20:
            self.current_object = Figura7(self.start_x, self.start_y, self.window)

        return prev_obj

    def draw(self):
        self.window.clear()
        self.current_object.draw()
        self.window.border(0, 0, 0, 0)
        self.window.refresh()
Ejemplo n.º 13
0
class GameField:
    magic_creater: MagicCrearter
    score_object: ScoreTime
    manager_window: ManagerWindows
    window: curses
    max_x: int
    max_y: int
    start_x: int
    start_y: int
    arr: list
    cur_figura: Union[Figura1, Figura2, Figura3, Figura4, Figura5, Figura6,
                      Figura7]
    last_time: float

    def __init__(self, magic_creater: MagicCrearter, score_object: ScoreTime):
        self.magic_creater = magic_creater
        self.score_object = score_object
        self.manager_window = ManagerWindows()
        """
        window_field
        :param window: window
        """
        self.window = self.manager_window.window_field
        self.max_x = self.window.getmaxyx()[1] - 2
        self.max_y = self.window.getmaxyx()[0] - 2
        self.start_x = 5
        self.start_y = 2
        self.arr = [0 for v in range(self.max_x * self.max_y)]
        self.cur_figura = self.magic_creater.create()
        self.cur_figura.re_init_window(self.window, self.start_x, self.start_y,
                                       self.arr)
        self.window.keypad(True)  # режим клавивиатуры
        self.window.nodelay(True)  # getch() будет неблокирующим.
        self.last_time = time.time()
        self.pause_timer = 0
        self.start_pause_timer = 0
        self.pause_down = 0.5

    def reset(self):
        self.window = self.manager_window.window_field
        self.arr = [0 for v in range(self.max_x * self.max_y)]
        self.cur_figura = self.magic_creater.create()
        self.cur_figura.re_init_window(self.window, self.start_x, self.start_y,
                                       self.arr)
        self.last_time = time.time()
        self.pause_timer = 0
        self.start_pause_timer = 0

    def pause_start(self):
        self.start_pause_timer = time.time()

    def pause_stop(self):
        self.pause_timer = time.time() - self.start_pause_timer

    def _work_down(self):
        """
        условие выполнение кода в блоке if, если фигура опустилась до конца, то exist is False
        """
        if self.cur_figura.exist is False:
            """
            вызов метода score_from_figure() для подсчёта очков, к-рому отдали количество очков из
            метода get_score() объекта фигуры
            """
            self.score_object.score_from_figure(self.cur_figura.get_score())
            """
            передача созданной ранее фигуры в окно game_field и создание нового объекта фигуры
            """
            self.cur_figura = self.magic_creater.create()
            """
            передача параметров полей нового объекта в window_magic_creater, window_field
            """
            self.cur_figura.re_init_window(self.window, self.start_x,
                                           self.start_y, self.arr)
            if self.cur_figura.exist is False:
                """
                Стакан полный. Игра и время игры остановились.
                """
                self.arr = [0 for v in range(self.max_x * self.max_y)]
                self.manager_window.set_status(ManagerWindowsStatus.END_GAME)

    def draw(self):
        """
        очистка изображения предыдущих клеток
        """
        self.window.clear()
        """
        условие выполнение кода в блоке if через время задержки после вызова метода draw() объекта класса GameField
        """
        if time.time() - self.pause_timer - self.last_time > self.pause_down:
            self.pause_timer = 0
            """
            фиксация last_time для нового отсчёта времени изменения положения по оси y
            """
            self.last_time = time.time()
            """
            вызов метода down() у текущего объекта фигуры, перемещение вниз по оси y, или остановка движения по оси y и
            изменение элементов списка self.arr с 0 на 1 соответственно фиксации положения фигуры
            """
            self.cur_figura.down()
            self._work_down()
        c = self.manager_window.get_char()
        if c == curses.KEY_LEFT:
            self.cur_figura.left()
        elif c == curses.KEY_RIGHT:
            self.cur_figura.right()
        elif c == curses.KEY_UP:
            self.cur_figura.rotate()
        elif c == curses.KEY_DOWN:
            while self.cur_figura.exist is True:
                self.cur_figura.down()
        self._work_down()
        """
        проверка и подсчёт целых строк
        """
        n = 0
        index_in = 0
        for i in range(0, len(self.arr), self.max_x):
            if sum(self.arr[i:i + self.max_x]) == self.max_x:
                n += 1
                index_in = i
                self.arr[i:i + self.max_x] = [0] * self.max_x
        """
        стирание целых строк и сдвиг вниз остальных строк
        """
        for index_out in range(index_in - self.max_x, 0, -self.max_x):
            if sum(self.arr[index_out:index_out + self.max_x]) > 0:
                self.arr[index_in:index_in +
                         self.max_x] = self.arr[index_out:index_out +
                                                self.max_x]
                self.arr[index_out:index_out + self.max_x] = [0] * self.max_x
                index_in = index_in - self.max_x
        """
        передача (n) стёртых строк в self.score_object.score_destroy_line(), для подсчёте очков за стёртые строк
        """
        self.score_object.score_destroy_line(n)
        """
        вывод на экран игрового поля 
        """
        for i in range(len(self.arr)):
            if self.arr[i] == 1:
                self.window.addstr(i // self.max_x + 1, i % self.max_x + 1,
                                   "#", curses.color_pair(1))
        """
        вызов метода draw() у текущего объекта фигуры по коорд x и y
        """
        self.cur_figura.draw()
        self.window.border()
        """
        Обновлние отображения (синхронизизация фактического экрана с предыдущими методами рисования / удаления)
        """
        self.window.refresh()
Ejemplo n.º 14
0
class ScoreTime:
    manager_window: ManagerWindows
    window: curses
    score: int
    time: int
    last_time: float
    _status: bool

    def __init__(self, score: int = 0, time: int = 0) -> None:
        self.window = ManagerWindows().window_score_timer
        self.score = score
        self.time = time
        self.last_time = lib_time.time()
        self.start_pause_timer = 0
        self.pause_timer = 0

    def score_destroy_line(
            self, n: int):  # К-во убираемых строк, подсчёт очков по линиям
        if n == 1:
            self.score += 5
        elif n == 2:
            self.score += 15
        elif n == 3:
            self.score += 35
        elif n == 4:
            self.score += 75

    def score_from_figure(self, count: int):  # подсчёт очков за фигуру
        self.score += count

    def get_score(self):
        return self.score

    def get_time(self):
        return self.time

    def pause_start(self):
        self.start_pause_timer = lib_time.time()

    def pause_stop(self):
        self.pause_timer += lib_time.time() - self.start_pause_timer

    def reset(self):
        self.last_time = lib_time.time()
        self.pause_timer = 0
        self.score = 0

    def draw(self):  # Отображение очков и времени
        self.window.clear()
        str_time = convert_to_format(self.time)
        self.time = int(lib_time.time() - self.pause_timer - self.last_time)
        self.window.addstr(1, 1, "Time play:", curses.color_pair(1))
        self.window.addstr(2, 1, str_time, curses.color_pair(1))
        self.window.addstr(4, 1, "Score:", curses.color_pair(3))
        self.window.addstr(5, 1, str(self.score), curses.color_pair(3))
        self.window.border()
        self.window.refresh()