def __call__(self): # Відображення значення spinner при включенні кнопки if self.button_on: pg.time.wait(250) color_text = colors['berry'] color_text_act = color_effect.modify_color(colors['purple'], l=-50) rect_spinner = pg.Rect( self.button_x, self.button_y, self.w, self.h * len(self.vals) ) # Цінність класу полягає у властивостях і методах, що дозволяють управляти розміщенням поверхонь, виконувати перевірку їх перекриття cx = self.button_x + self.w / 2 cy = self.button_y running = True while running: pg.event.pump() #дозволити pygame обробляти внутрішні дії pos = pg.mouse.get_pos() #отримати позицію курсора миші click = pg.mouse.get_pressed() #отримати стан кнопок миші color_rect = color_effect.change_color() pg.draw.rect(self.screen, color_rect, rect_spinner) for i in range(len(self.vals)): surface, rect = config.text_objects( f'{self.vals[i]}', x_center=cx, y_center=cy + self.h / 2 + i * self.h, color=color_text, font_size=self.vals_font_size) rect_button = rect.copy() rect_button.left = self.button_x rect_button.width = self.w if rect_button.collidepoint(pos): if click[0] == 1: self.function(self.vals[i]) self.current_val = f'{self.vals[i]}' self.text = f'{self.key} {self.current_val}' self.draw_params['text'] = self.text running = False surface, rect = config.text_objects( f'{self.vals[i]}', x_center=cx, y_center=cy + self.h / 2 + i * self.h, color=color_text_act, font_size=self.vals_font_size * 2) self.screen.blit(surface, rect) else: self.screen.blit(surface, rect) pg.display.update() if not rect_spinner.collidepoint(pos): running = False self.button_on = False pg.time.wait(250)
def __call__(self): # Display the values of the spinner when the button is turn on if self.button_on: pg.time.wait(250) color_text = colors['berry'] color_text_act = color_effect.modify_color(colors['purple'], l=-50) rect_spinner = pg.Rect(self.button_x, self.button_y, self.w, self.h * len(self.vals)) cx = self.button_x + self.w / 2 cy = self.button_y running = True while running: pg.event.pump() pos = pg.mouse.get_pos() click = pg.mouse.get_pressed() color_rect = color_effect.change_color() pg.draw.rect(self.screen, color_rect, rect_spinner) for i in range(len(self.vals)): surface, rect = config.text_objects( f'{self.vals[i]}', x_center=cx, y_center=cy + self.h / 2 + i * self.h, color=color_text, font_size=self.vals_font_size) rect_button = rect.copy() rect_button.left = self.button_x rect_button.width = self.w if rect_button.collidepoint(pos): if click[0] == 1: self.function(self.vals[i]) self.current_val = f'{self.vals[i]}' self.text = f'{self.key} {self.current_val}' self.draw_params['text'] = self.text running = False surface, rect = config.text_objects( f'{self.vals[i]}', x_center=cx, y_center=cy + self.h / 2 + i * self.h, color=color_text_act, font_size=self.vals_font_size * 2) self.screen.blit(surface, rect) else: self.screen.blit(surface, rect) pg.display.update() if not rect_spinner.collidepoint(pos): running = False self.button_on = False pg.time.wait(250)
def __call__(self): # Відображення значення spinner при включенні кнопки if self.button_on: pg.time.wait(250)#модуль pygame для управління часом і частотою кадрів color_text = colors['berry'] color_text_act = color_effect.modify_color(colors['purple'], l=-50) rect_spinner = pg.Rect(self.button_x, self.button_y, self.w, self.h * len(self.vals))# Цінність класу полягає у властивостях і методах, що дозволяють управляти розміщенням поверхонь, виконувати перевірку їх перекриття cx = self.button_x + self.w / 2 cy = self.button_y running = True while running: pg.event.pump()#дозволити pygame обробляти внутрішні дії pos = pg.mouse.get_pos()#отримати позицію курсора миші click = pg.mouse.get_pressed()#отримати стан кнопок миші color_rect = color_effect.change_color() pg.draw.rect(self.screen, color_rect, rect_spinner)#намалювати прямокутну форму for i in range(len(self.vals)): surface, rect = config.text_objects(f'{self.vals[i]}', x_center=cx, y_center=cy + self.h / 2 + i * self.h, color=color_text, font_size=self.vals_font_size) rect_button = rect.copy() rect_button.left = self.button_x rect_button.width = self.w if rect_button.collidepoint(pos):#Метод collidepoint () об'єкта Rect перевіряє, чи знаходиться точка, #координати якої були передані в якості аргументу, в межах прямокутника, до якого застосовується метод if click[0] == 1: self.function(self.vals[i]) self.current_val = f'{self.vals[i]}' self.text = f'{self.key} {self.current_val}' self.draw_params['text'] = self.text running = False surface, rect = config.text_objects(f'{self.vals[i]}',# Представлення значень на поверхності, її розміщення і колір x_center=cx, y_center=cy + self.h / 2 + i * self.h, color=color_text_act, font_size=self.vals_font_size * 2) self.screen.blit(surface, rect)#метод blit () застосовується до батьківської Surface, в той час як дочірня приймає в якості аргументу. else: self.screen.blit(surface, rect) pg.display.update()#модуль pygame для оновлення if not rect_spinner.collidepoint(pos):#Метод collidepoint () об'єкта Rect перевіряє, чи знаходиться точка, #координати якої були передані в якості аргументу, в межах прямокутника, до якого застосовується метод running = False self.button_on = False pg.time.wait(250)#модуль pygame для управління часом і частотою кадрів
def draw_records(self, names, records, color): text = 'TOP FIVE' x = config.texts['top five']['x'] y = config.texts['top five']['y'] # Представлення тексту на поверхності, її розміщення і колір surface, rect = config.text_objects(text, left=x, top=y, color=color) self.screen.blit(surface, rect) for i in range(len(records)): text = f'{names[i]} ......... {records[i]:2}' x = config.texts['records']['x'] y = config.texts['records']['y'] + i * config.texts['records']['y_space'] surface, rect = config.text_objects(text, left=x, top=y, color=color)# Представлення тексту на поверхності, її розміщення і колір self.screen.blit(surface, rect)#метод blit () застосовується до батьківської Surface, в той час як дочірня приймає в якості аргументу.
def draw_records(self, names, records, color): text = 'TOP FIVE' x = config.texts['top five']['x'] y = config.texts['top five']['y'] surface, rect = config.text_objects(text, left=x, top=y, color=color) self.screen.blit(surface, rect) for i in range(len(records)): text = f'{names[i]} ......... {records[i]:2}' x = config.texts['records']['x'] y = config.texts['records']['y'] + i * config.texts['records']['y_space'] surface, rect = config.text_objects(text, left=x, top=y, color=color) self.screen.blit(surface, rect)
def __init__(self, key, function, draw_on): Button.__init__(self, key, function, draw_on) # Цінності, які слід поставити на spinner self.text = f'{self.key} {self.current_val}' # рядки покращують читабельність коду, а також працюють швидше ніж інші способи форматування surface, rect = config.text_objects(self.text, left=self.x, top=self.y, font_size=config.medium_text) self.button_x, self.button_y = rect.bottomright self.button = pg.Rect(self.button_x, self.button_y, self.w, self.h) self.triangle = [[self.button_x, self.button_y], [self.button_x + self.w, self.button_y], [self.button_x + self.w / 2, self.button_y + self.h]] self.draw_params = { 'button': self.triangle, 'text': self.text, 'left': self.x, 'top': self.y, 'font_size': config.medium_text }
def draw_speed(self, color): text = f'Speed : {config.speed}' surface, rect = config.text_objects(text, x_center=config.texts['speed']['x'], y_center=config.texts['speed']['y'], color=color) self.screen.blit(surface, rect)
def draw_score(self, color): text = f'Score : {score.score}' surface, rect = config.text_objects(text, x_center=config.texts['score']['x'], y_center=config.texts['score']['y'], color=color) self.screen.blit(surface, rect)
def draw_score(self, color): #Вивід рахунку text = f'Score : {score.score}' # Представлення рахунку на поверхності, її розміщення і колір surface, rect = config.text_objects(text, x_center=config.texts['score']['x'], y_center=config.texts['score']['y'], color=color) self.screen.blit(surface, rect)#метод blit () застосовується до батьківської Surface, в той час як дочірня приймає в якості аргументу.
def __init__(self, key, function, draw_on): Button.__init__(self, key, function, draw_on) # Values to put on the spinner if self.key == 'speed': self.current_val = f'{config.speed}' self.vals = list(range(1, 11)) self.vals_font_size = config.small_text elif self.key == 'ncols': self.current_val = f'{config.ncols}' self.vals = sorted(list(set([i[1] for i in config.grid_sizes]))) self.vals_font_size = config.small_text elif self.key == 'next shape': self.key = f'Enable next shape' if config.see_next_shape: self.current_val = ' On' else: self.current_val = ' Off' self.vals = ['On', 'Off'] self.vals_font_size = int(config.small_text - config.small_text * 0.3) elif self.key == 'big shapes': self.key = f'Enable big shapes' if config.big_shapes: self.current_val = ' On' else: self.current_val = ' Off' self.vals = ['On', 'Off'] self.vals_font_size = int(config.small_text - config.small_text * 0.3) self.text = f'{self.key} {self.current_val}' surface, rect = config.text_objects(self.text, left=self.x, top=self.y, font_size=config.medium_text) self.button_x, self.button_y = rect.bottomright self.button = pg.Rect(self.button_x, self.button_y, self.w, self.h) self.triangle = [[self.button_x, self.button_y], [self.button_x + self.w, self.button_y], [self.button_x + self.w / 2, self.button_y + self.h]] self.draw_params = { 'button': self.triangle, 'text': self.text, 'left': self.x, 'top': self.y, 'font_size': config.medium_text }
def draw_game_over(self): text = 'GAME OVER' surface, rect = config.text_objects(text, x_center=config.texts['game_over']['x'], y_center=config.texts['game_over']['y'], rotation_angle=45, font_size=config.huge_text, color=colors['berry']) self.screen.blit(surface, rect) pg.display.update() pg.time.wait(2000)
def draw_next_shape(self, color):#Вивід наступної фігури на екран if config.see_next_shape: cx, cy = config.rects['next_shape'].center next_shape.draw_next_shape(cx, cy, self.screen) pg.draw.rect(self.screen, color, config.rects['next_shape'], 5) # Представлення фігури на поверхності, її розміщення і колір surface, rect = config.text_objects('Next Shape', x_center=config.texts['next_shape']['x'], y_center=config.texts['next_shape']['y'], color=color) self.screen.blit(surface, rect)#метод blit () застосовується до батьківської Surface, в той час як дочірня приймає в якості аргументу.
def draw_next_shape(self, color): if config.see_next_shape: cx, cy = config.rects['next_shape'].center next_shape.draw_next_shape(cx, cy, self.screen) pg.draw.rect(self.screen, color, config.rects['next_shape'], 5) surface, rect = config.text_objects( 'Next Shape', x_center=config.texts['next_shape']['x'], y_center=config.texts['next_shape']['y'], color=color) self.screen.blit(surface, rect)
def draw_game_over(self): text = 'GAME OVER' # Представлення тексту на поверхності, її розміщення і колір surface, rect = config.text_objects(text, x_center=config.texts['game_over']['x'], y_center=config.texts['game_over']['y'], rotation_angle=45, font_size=config.huge_text, color=colors['berry']) self.screen.blit(surface, rect)#метод blit () застосовується до батьківської Surface, в той час як дочірня приймає в якості аргументу. pg.display.update()#модуль pygame для оновлення pg.time.wait(1000)#модуль pygame для управління часом і частотою кадрів
def draw_button(self, color_active=False): color = color_effect.change_color() if color_active: color = color_effect.modify_color(color, l=-20) draw_params = self.draw_params.copy() if isinstance(draw_params['button'], list): pg.draw.polygon(self.screen, color, draw_params['button']) else: pg.draw.rect(self.screen, color, draw_params['button'], 5) draw_params.pop('button') surface, rect = config.text_objects(**draw_params, color=color) self.screen.blit(surface, rect)
def start_count(self): texts = ['3', '2', '1', 'GO!'] for text in texts: color = color_effect.change_color() surface, rect = config.text_objects(text, x_center=config.texts['start']['x'], y_center=config.texts['start']['y'], font_size=config.huge_text, color=color) self.draw_background() self.screen.blit(surface, rect) pg.display.update() pg.time.wait(1000)
def draw_button(self, color_active=False): color = color_effect.change_color() if color_active: color = color_effect.modify_color(color, l=-20) draw_params = self.draw_params.copy() if isinstance(draw_params['button'], list):#Повертає прапор, який вказує на те, чи є зазначений об'єкт екземпляром зазначеного класу pg.draw.polygon(self.screen, color, draw_params['button']) else: pg.draw.rect(self.screen, color, draw_params['button'], 5) draw_params.pop('button') surface, rect = config.text_objects(**draw_params, color=color)#для прийняття тільки іменованих аргументів self.screen.blit(surface, rect)#метод blit () застосовується до батьківської Surface, в той час як дочірня приймає в якості аргументу.
def start_count(self): texts = ['3', '2', '1', 'GO!'] for text in texts: color = color_effect.change_color() surface, rect = config.text_objects(text,# Представлення рахунку на поверхності, її розміщення і колір x_center=config.texts['start']['x'], y_center=config.texts['start']['y'], font_size=config.huge_text, color=color) self.draw_background() self.screen.blit(surface, rect)#метод blit () застосовується до батьківської Surface, в той час як дочірня приймає в якості аргументу. pg.display.update() pg.time.wait(1000)#модуль pygame для управління часом і частотою кадрів
def menu(self): key_buttons = ['START', 'RANKING', 'EXIT'] buttons = [ Button(key, self.functions[key], self.screen) for key in key_buttons ] text = 'Press F1 to see keyboard instructions' cx = config.texts['instructions']['x'] cy = config.texts['instructions']['y'] self.running = True while self.running: for event in pg.event.get(): if event.type == pg.QUIT: self.exit() elif event.type == pg.KEYDOWN: if event.key == pg.K_F1: button = self.see_instructions buttons.append(button) self.running = False self.screen.blit(config.images['MENU BACKGROUND'], (0, 0)) surface, rect = config.text_objects( text, x_center=cx, y_center=cy, font_size=config.medium_text, color=color_effect.change_color()) self.screen.blit(surface, rect) for button in buttons: if isinstance(button, Button): button.status() if button.button_on: self.running = False pg.display.update() config.clock.tick(config.fps) pg.time.wait(250) for button in buttons: button()
def write_record(self): #функція для запису рахунку chars = string.ascii_uppercase chars += string.digits name = list(f'{chars[-1]} ') chars_index = 0 name_index = 0 count = 0 self.running = True while self.running: for event in pg.event.get(): if event.type == pg.QUIT: self.exit() if event.type == pg.KEYDOWN: if event.key == pg.K_RETURN: count += 1 if count < 4: name_index += 1 chars_index = 0 if event.key == pg.K_BACKSPACE: if name_index > 0: chars_index = -1 name_index -= 2 count -= 1 else: if event.key == pg.K_DOWN: chars_index -= 1 if chars_index < ~(len(chars) - 1): chars_index = -1 elif event.key == pg.K_UP: chars_index += 1 if chars_index > len(chars) - 1: chars_index = 0 if event.type == pg.KEYUP: if event.key == pg.K_DOWN or event.key == pg.K_UP: chars_index += 0 name[name_index] = chars[chars_index] text = ''.join(name) color = color_effect.change_color() # розміщення тексту на поверхні surface, rect = config.text_objects( text, x_center=config.texts['write_record']['x'], y_center=config.texts['write_record']['y'], color=color) # Малювання фону pg.draw.rect(self.screen, colors['gray'], rect) self.screen.blit( surface, rect ) #метод blit () застосовується до батьківської Surface, в той час як дочірня приймає в якості аргументу. pg.display.update() #модуль pygame для оновлення config.clock.tick(config.fps) #частота картинок за хвилину if count == 4: self.running = False name = ''.join(name) name = name.replace(' ', '') score.save_record(name) pg.time.wait( 1000) #модуль pygame для управління часом і частотою кадрів
def write_record(self): chars = string.ascii_uppercase chars += string.digits name = list(f'{chars[-1]} ') chars_index = 0 name_index = 0 count = 0 self.running = True while self.running: for event in pg.event.get(): if event.type == pg.QUIT: self.exit() if event.type == pg.KEYDOWN: if event.key == pg.K_RETURN: count += 1 if count < 4: name_index += 1 chars_index = 0 if event.key == pg.K_BACKSPACE: if name_index > 0: chars_index = -1 name_index -= 2 count -= 1 else: if event.key == pg.K_DOWN: chars_index -= 1 if chars_index < ~(len(chars) - 1): chars_index = -1 elif event.key == pg.K_UP: chars_index += 1 if chars_index > len(chars) - 1: chars_index = 0 if event.type == pg.KEYUP: if event.key == pg.K_DOWN or event.key == pg.K_UP: chars_index += 0 name[name_index] = chars[chars_index] text = ''.join(name) color = color_effect.change_color() surface, rect = config.text_objects( text, x_center=config.texts['write_record']['x'], y_center=config.texts['write_record']['y'], color=color) # Draw background pg.draw.rect(self.screen, colors['gray'], rect) self.screen.blit(surface, rect) pg.display.update() config.clock.tick(config.fps) if count == 4: self.running = False name = ''.join(name) name = name.replace(' ', '') score.save_record(name) pg.time.wait(1000)