def create_start_menu_displays(self): display = ClockDisplay(c.start_menu_display_x, c.start_menu_down_display_y, c.start_menu_display_x_size, c.start_menu_display_y_size, c.start_menu_display_color) display_text = TextObject(display.centerx, display.centery, lambda: 'Set color mode...', c.start_menu_display_text_color, c.start_menu_display_font_name, c.start_menu_display_font_size, True) self.objects.append(display) self.objects.append(display_text) self.start_menu_objects.append(display) self.start_menu_objects.append(display_text) display = ClockDisplay(c.start_menu_display_x, c.start_menu_up_display_y, c.start_menu_display_x_size, c.start_menu_display_y_size, c.start_menu_display_color) display_text = TextObject(display.centerx, display.centery, lambda: 'Set cycles number...', c.start_menu_display_text_color, c.start_menu_display_font_name, c.start_menu_display_font_size, True) self.objects.append(display) self.objects.append(display_text) self.start_menu_objects.append(display) self.start_menu_objects.append(display_text)
def __init__(self, x, y, w, h, text, on_click=lambda x: None, padding=0): super().__init__(x, y, w, h) self.state = 'normal' self.on_click = on_click self.text = TextObject(x + padding, y + padding, lambda: text, c.button_text_color, c.font_name, c.menu_font_size)
def open_records(button): self.objects = [] self.menu_buttons = [] self.mouse_handlers = [] back = Button(cfg.menu_offset_x, cfg.menu_offset_y + 100, cfg.start_menu_w, cfg.start_menu_h, "Back", get_back, padding=5) self.objects.append(back) self.menu_buttons.append(back) self.mouse_handlers.append(back.handle_mouse_event) f = open("saves.txt", 'r') lines = f.readlines() f.close() example = TextObject(28, 5, "Order Colors Nick Score", font_size=30, color=cfg.cubes['BLUE']['normal']) self.objects.append(example) for i, line in enumerate(lines): tmp = line.split(";") string = "{0} {1} {2} {3}".format(*tmp) record = TextObject(30, 45 * (i + 1), string, 25) self.objects.append(record)
def create_labels(self): self.score_label = TextObject(c.score_offset, c.status_offset_y, lambda: 'SCORE: {0}'.format(self.score), c.text_color, c.font_name, c.font_size) self.objects.append(self.score_label) self.lives_label = TextObject(c.lives_offset, c.status_offset_y, lambda: 'LIVES: {0}'.format(self.lives), c.text_color, c.font_name, c.font_size) self.objects.append(self.lives_label)
class Button(GeneralObject): def __init__(self, x, y, w, h, button_color_dict, text, text_color, on_click=lambda x: None, key=None): GeneralObject.__init__(self, x, y, w, h) self.state = 'normal' self.button_color_dict = button_color_dict self.on_click = on_click self.text_color = text_color self.key = key self.text = TextObject(self.centerx, self.centery, lambda: text, self.text_color, c.button_font_name, c.button_font_size, True) def draw(self, surface): pygame.draw.rect(surface, self.back_color, self.rect) self.text.draw(surface) def handle_mouse_event(self, type, pos): if type == pygame.MOUSEMOTION: self.handle_mouse_move(pos) elif type == pygame.MOUSEBUTTONDOWN: self.handle_mouse_down(pos) elif type == pygame.MOUSEBUTTONUP: self.handle_mouse_up(pos) def handle_mouse_move(self, pos): if self.rect.collidepoint(pos): if self.state != 'pressed': self.state = 'hover' else: self.state = 'normal' def handle_mouse_down(self, pos): if self.rect.collidepoint(pos): self.state = 'pressed' def handle_mouse_up(self, pos): if self.state == 'pressed': if self.key is not None: self.on_click(self, self.key) else: self.on_click(self) self.state = 'hover' @property def back_color(self): return self.button_color_dict[self.state]
class Button(GameObject): def __init__(self, x, y, w, h, text, on_click=lambda x: None, padding=0, size=cfg.font_size): super().__init__(x, y, w, h) self.state = 'normal' self.on_click = on_click self.text = TextObject(x + padding, y + padding, text, color=cfg.button_text_color, font_size=size) self.text_easy = text @property def back_color(self): return dict(normal=cfg.button_normal_back_color, hover=cfg.button_hover_back_color, pressed=cfg.button_pressed_back_color)[self.state] def draw(self, surface): pygame.draw.rect(surface, self.back_color, self.bound) pygame.draw.rect(surface, cfg.BLACK, self.bound, 1) self.text.draw(surface) def handle_mouse_event(self, type, pos): if type == pygame.MOUSEMOTION: self.handle_mouse_move(pos) elif type == pygame.MOUSEBUTTONDOWN: self.handle_mouse_down(pos) elif type == pygame.MOUSEBUTTONUP: self.handle_mouse_up(pos) def handle_mouse_move(self, pos): if self.bound.collidepoint(pos): if self.state != 'pressed': self.state = 'hover' else: self.state = 'normal' def handle_mouse_down(self, pos): if self.bound.collidepoint(pos): self.state = 'pressed' def handle_mouse_up(self, pos): if self.state == 'pressed': self.on_click(self) self.state = 'hover'
class Button(GameObject): def __init__(self, x, y, w, h, text, button_type): super().__init__(x, y, w, h) self.type = button_type self.text = TextObject(x + 1, y + 10, lambda: text, config.BUTTON_TEXT_COLOR, config.BUTTON_FONT, config.BUTTON_SIZE) def draw(self, surface): draw.rect(surface, config.BUTTON_COLOR, self.bounds) self.text.draw(surface)
def __init__(self, x, y, w, h, text, on_click=lambda x: None, padding=0): self.bounds = pygame.Rect(x, y, w, h) # прямоугольный объект self.x = x self.y = y self.w = w self.h = h self.padding = padding self.state = 'normal' self.on_click = on_click self.text = TextObject(x + padding, y + padding, lambda: text, c.button_text_color, c.font_name, c.font_size)
def show_message(self, text, color=colors.GRAY24, font_name='Century', font_size=20, centralized=False): message = TextObject(c.w_x_size // 2, c.w_y_size // 2, lambda: text, color, font_name, font_size, True) self.draw() message.draw(self.surface) pygame.display.update() time.sleep(c.message_duration)
def show_message(self, text, color=colors.WHITE, font_name='Arial', font_size=20, centralized=False): message = TextObject(c.screen_width // 2, c.screen_height // 2, lambda: text, color, font_name, font_size) self.draw() message.draw(self.surface, centralized) pygame.display.update() time.sleep(c.message_duration)
def show_message(self, text, color=cfg.text_color, font_name=cfg.font_name, font_size=cfg.font_size): message = TextObject(cfg.screen_width // 2 - 40, (cfg.screen_height // 2) - 40, text, font_size, color, font_name) self.draw() message.draw(self.surface) pygame.display.update() time.sleep(3)
def create_labels(self): score_label = TextObject(c.offset_score, c.offset_status_y, lambda: f'SCORE: {self.score}', c.text_color, c.font_name, c.font_size) self.objects.append(score_label) level_label = TextObject(c.offset_level, c.offset_status_y, lambda: f'LEVEL: {self.game_level}', c.text_color, c.font_name, c.font_size) self.objects.append(level_label) lives_label = TextObject(c.offset_lives, c.offset_status_y, lambda: f'LIVES: {self.lives}', c.text_color, c.font_name, c.font_size) self.objects.append(lives_label)
def create_labels(self): self.score_label = TextObject(c.score_offset, c.status_offset_y, lambda: f'SCORE: {self.score}', c.text_color, c.font_name, c.font_size) self.objects.append(self.score_label) self.lives_label = TextObject(c.lives_offset, c.status_offset_y, lambda: f'LIVES: {self.lives}', c.text_color, c.font_name, c.font_size) self.objects.append(self.lives_label) self.level_label = TextObject(c.level_offset, c.status_offset_y, lambda: f'LEVEL: {self.level}', c.text_color, c.font_name, c.font_size) self.objects.append(self.level_label)
def create_labels(self): self.score_label = TextObject( cfg.score_offset, cfg.score_offset_y, "", text_func=lambda: 'SCORE: {}'.format(self.score['score'])) self.objects.append(self.score_label) self.pre_score_label = TextObject( cfg.score_offset, cfg.score_offset_y + 100, "", text_func=lambda: 'PLUS: {}'.format(self.pre_score['pre_score'])) self.objects.append(self.pre_score_label)
def create_labels(self): self.score_label_left = TextObject(c.lives_left_offset_x, c.lives_left_offset_y, lambda: f'SCORE: {self.score_left}', c.text_color, c.font_name, c.font_size) self.objects.append(self.score_label_left) self.score_label_right = TextObject( c.lives_right_offset_x, c.lives_right_offset_y, lambda: f'SCORE: {self.score_right}', c.text_color, c.font_name, c.font_size) self.objects.append(self.score_label_right)
def create_colors(self): choose_text = TextObject(cfg.screen_width / 2 - 100, 30, 'Choose count of colors') def colors(button): cfg.count_colors = int(button.text_easy) for b in self.color_buttons: self.objects.remove(b) self.objects.remove(choose_text) self.color_buttons = [] self.mouse_handlers = [] self.create_game() self.objects.append(choose_text) for i, (text, handler) in enumerate( (('3', colors), ('4', colors), ('5', colors))): width = cfg.screen_width / 3.5 + 2 * i * (cfg.menu_button_w + 3) b = Button(width, cfg.screen_height / 3 + (cfg.menu_button_h + 3), cfg.menu_button_w, cfg.menu_button_h, text, handler, padding=5) self.objects.append(b) self.color_buttons.append(b) self.mouse_handlers.append(b.handle_mouse_event)
def create_orders(self): choose_text = TextObject(cfg.screen_width / 2 - 70, 30, 'Select field sizes') def orders(button): cfg.map_width = int(button.text_easy[0:2]) cfg.map_height = int(button.text_easy[3:]) for b in self.order_buttons: self.objects.remove(b) self.objects.remove(choose_text) self.order_buttons = [] self.mouse_handlers = [] self.create_colors() self.objects.append(choose_text) for i, (text, handler) in enumerate( (('09x12', orders), ('12x15', orders), ('15x18', orders), ('18x21', orders))): width = cfg.screen_width / 4.5 + 2 * i * (cfg.menu_button_w + 3) b = Button(width, cfg.screen_height / 3 + (cfg.menu_button_h + 3), cfg.menu_button_w, cfg.menu_button_h, text, handler, padding=5) self.objects.append(b) self.order_buttons.append(b) self.mouse_handlers.append(b.handle_mouse_event)
def __init__(self, x, y, contents, font_name, font_size): self.text = contents['text'].item() self.label = contents['label'].item() self.color = literal_eval(contents['color'].item()) self.stimulus = TextObject( x, y, lambda: self.text, self.color, font_name, font_size )
def __init__(self, x, y, w, h, text, on_click=lambda x: None, padding=0, size=cfg.font_size): super().__init__(x, y, w, h) self.state = 'normal' self.on_click = on_click self.text = TextObject(x + padding, y + padding, text, color=cfg.button_text_color, font_size=size) self.text_easy = text
def create_remain_repeate_display(self): rr_display = ClockDisplay(c.rr_x, c.rr_y, c.rr_x_size, c.rr_y_size, c.rr_color[self.style_mode]) rr_text = TextObject(rr_display.centerx, rr_display.centery, self.text_for_rr, c.rr_text_color[self.style_mode], c.rr_font_name, c.rr_font_size, True) self.objects.append(rr_display) self.objects.append(rr_text)
def create_mode_display(self): mode_display = ClockDisplay(c.mode_x, c.mode_y, c.mode_x_size, c.mode_y_size, c.mode_color[self.style_mode]) mode_text = TextObject(mode_display.centerx, mode_display.centery, self.text_for_mode, c.mode_text_color[self.style_mode], c.mode_font_name, c.mode_font_size, True) self.objects.append(mode_display) self.objects.append(mode_text)
def __init__(self, x, y, w, h, button_color_dict, text, text_color, on_click=lambda x: None, key=None): GeneralObject.__init__(self, x, y, w, h) self.state = 'normal' self.button_color_dict = button_color_dict self.on_click = on_click self.text_color = text_color self.key = key self.text = TextObject(self.centerx, self.centery, lambda: text, self.text_color, c.button_font_name, c.button_font_size, True)
def create_clock_display(self): clock_display = ClockDisplay(c.clock_x, c.clock_y, c.clock_x_size, c.clock_y_size, c.clock_color[self.style_mode]) #text = time.strftime("%H : %M", clock_text = TextObject(clock_display.centerx, clock_display.centery, self.text_for_time, c.clock_text_color[self.style_mode], c.clock_font_name, c.clock_font_size, True) self.objects.append(clock_display) self.objects.append(clock_text)
def __init__(self): Game.__init__(self, 'Stimulus control competition task', c.background_image, c.frame_rate) # Loads experimental setup self.df = pandas.read_csv(c._thisDir + os.sep + 'stimuli' + os.sep + c.setup, encoding="utf-8" ) # Creates iterator to loop over phases self.phases = itertools.cycle(self.df['phase'].unique()) self.phase = self.phases.next() # Constructs counters self.score = 0 self.counters = [] self.counters.append(TextObject( 0.06*w, 0.06*h, lambda: u'Счет: %i' %self.score, colors.WHITE, c.font_name, int(c.font_size*h) ) ) # Constructs stimuli self.stimuli = [] self.stimuli.append(TextStimulus( 0.35*w, 0.45*h, self.df.loc[self.df['phase'] == self.phase].sample(1), c.font_name, int(c.font_size*h) ) ) self.stimuli.append(TextStimulus( 0.65*w, 0.45*h, self.df.loc[self.df['phase'] == self.phase].sample(1), c.font_name, int(c.font_size*h) ) ) # Initializes event to change stimuli every n seconds self.rate = 1 self.CHANGE_STIMULI = pygame.USEREVENT + 1 # Constructs necessary buttons self.buttons = [] self.buttons.append(Button( 0.5*w - 0.15*w // 2, 0.85*h - 0.15*h // 2, 0.15*w, 0.15*h, on_click=lambda x: self.handle_reinforcement(are_stimuli_equal(iter(self.stimuli), attr='label'), reinforcement=1) ) ) pygame.time.set_timer(self.CHANGE_STIMULI, int(1000 / self.rate)) # Finishes initialization self.screen.fill(self.bg) self.clock = pygame.time.Clock() print 'Session started!'
def __init__(self, width, height): ''' @param width: text box width in pixel @type width: int @param height: text box height in pixel @type height: int ''' TextObject.font_name = self.font_name self._width = width self._height = height self._txt_obj = TextObject() self._font_size = 1 self._txt_obj.set_font_size(self._font_size) self._txt_obj.text_str('')
def __init__(self, start_pos_x: int, start_pos_y: int, char_count: int, font_name: str, font_size: int, bold=False, like_column=False): velocity_y = 0.5 + random() * 2 self.charset = [ TextObject( pos_x=start_pos_x, pos_y=start_pos_y - (i * font_size), text_func=get_random_char, color=(224 if i == 1 else 10, 255 + randint(-100, 0), 20), font_name=font_name, font_size=font_size, velocity_y=velocity_y if like_column else random() * 2, bold=bold, ) for i in range(1, char_count) ]
def update(self): if not self.game_running: return if self.finded['finded'] is False: if (self.check_saves()): if (not self.flag_for_textbox): self.show_message('NEW RECORD!') for y in range(cfg.map_height): for x in range(cfg.map_width): self.objects.remove(self.cubes[y][x]) label = TextObject(30, 10, 'INPUT YOUR NICKNAME:') self.objects.append(label) self.make_input() self.flag_for_textbox = True if (self.textbox.final == True): nickname = self.textbox.text records = self.remake_saves(nickname) self.rewrite_saves(records) self.game_running = False self.restart() else: self.show_message('GAME OVER') self.restart() return
class Button: def __init__(self, x, y, w, h, text, on_click=lambda x: None, padding=0): self.bounds = pygame.Rect(x, y, w, h) # прямоугольный объект self.x = x self.y = y self.w = w self.h = h self.padding = padding self.state = 'normal' self.on_click = on_click self.text = TextObject(x + padding, y + padding, lambda: text, c.button_text_color, c.font_name, c.font_size) @property def back_color(self): return dict(normal=c.button_normal_back_color, hover=c.button_hover_back_color, pressed=c.button_pressed_back_color)[self.state] def draw(self, surface): pygame.draw.rect(surface, self.back_color, self.bounds) self.text.draw(surface) def update(self): pass def handle_mouse_event(self, type, pos): if type == pygame.MOUSEMOTION: self.handle_mouse_move(pos) elif type == pygame.MOUSEBUTTONDOWN: self.handle_mouse_down(pos) elif type == pygame.MOUSEBUTTONUP: self.handle_mouse_up(pos) def handle_mouse_move(self, pos): if self.bounds.collidepoint(pos): if self.state != 'pressed': self.size_button(self.state) self.state = 'hover' else: self.size_button(self.state) self.state = 'normal' def handle_mouse_down(self, pos): if self.bounds.collidepoint(pos): self.size_button(self.state) self.state = 'pressed' def handle_mouse_up(self, pos): if self.state == 'pressed': self.size_button(self.state) self.on_click(self) self.state = 'hover' def size_button(self, state): if self.state != 'normal': self.bounds.height = self.h + c.button_loop_h self.bounds.width = self.w + c.button_loop_w self.bounds.x = self.x - c.button_loop_w // 2 self.bounds.y = self.y - c.button_loop_h // 2 self.text.change_font( c.font_size_loop, (self.bounds.x + self.padding, self.bounds.y + self.padding)) else: self.bounds.height = self.h self.bounds.width = self.w self.bounds.x = self.x self.bounds.y = self.y self.text.change_font( c.font_size, (self.bounds.x + self.padding, self.bounds.y + self.padding))
class TextBox(object): font_name = TextObject.font_name def __init__(self, width, height): ''' @param width: text box width in pixel @type width: int @param height: text box height in pixel @type height: int ''' TextObject.font_name = self.font_name self._width = width self._height = height self._txt_obj = TextObject() self._font_size = 1 self._txt_obj.set_font_size(self._font_size) self._txt_obj.text_str('') def set_text(self, text): ''' @param text: input text to fit into box @type text: str or unicode ''' self._txt_obj.text_str(text) def set_font(self, font_name): ''' @param font_name: valid font name @type font_name: str ''' self.font_name = font_name TextObject.font_name = font_name def get_max_font_size(self): ''' @return: best fitting font size in points @rtype: int @note: font size to use so that the text is as large as it can be but still fit in the box with dimensions box_x,box_y. ''' new_size = best_size = 1 while self._fitting(new_size): best_size = new_size new_size += 1 self._txt_obj.set_font_size(self._font_size) return best_size def _fitting(self, font_size): ''' @return: given text with given size fit into given boundaries @rtype: bool ''' self._txt_obj.set_font_size(font_size) txt_width, txt_height = self._txt_obj.check_text_dimensions() return txt_height <= self._height and txt_width <= self._width def get_scaling(self): ''' @return: width and height scaling to fit given box dimensions @rtype: tuple of float @note: Write the code that will figure out and implement the scaling necessary for the text to fit in the box best. ''' if not str(self._txt_obj): print 'text is missing' return 1.0, 1.0 txt_width, txt_height = self._txt_obj.check_text_dimensions() width_scale = 1.0 * self._width / txt_width height_scale = 1.0 * self._height / txt_height return width_scale, height_scale def get_scaling_advanced(self): ''' @return: font scaling details @rtype: dict @note: Write the code that will figure out and implement the scaling necessary for the text to fit in the box best. @note: additionally font size will be adjusted ''' self._font_size = self.get_max_font_size() self._txt_obj.set_font_size(self._font_size) txt_width, txt_height = self._txt_obj.check_text_dimensions() width_scale = 1.0 * self._width / txt_width height_scale = 1.0 * self._height / txt_height return {'font_size' : self._font_size, 'width_scale' : width_scale, 'height_scale' : height_scale} def get_min_lines(self): ''' @return: min line count needed to present text @rtype: float ''' width_scale, _ = self.get_scaling() return math.ceil(1.0 / width_scale) def get_max_lines(self): ''' @return: max line count possible present text @rtype: float ''' _, height_scale = self.get_scaling() text = str(self._txt_obj) return min(math.floor(height_scale), len(text.split()))
def create_score_label(self): self.score_label = TextObject(c.score_offset, c.status_offset_y, lambda: f'СЧЕТ: {self.score}', c.text_color, c.font_name, c.font_size) self.objects.append(self.score_label)
def __init__(self, x, y, w, h, text, button_type): super().__init__(x, y, w, h) self.type = button_type self.text = TextObject(x + 1, y + 10, lambda: text, config.BUTTON_TEXT_COLOR, config.BUTTON_FONT, config.BUTTON_SIZE)
def task_2(): ''' @note: text_object.setfontsize(12) - Fontsize has been set to 12 text_object.scale(a,b) - A method which takes two arguments, one for scaling the width value, one for scaling the height value of text_object.text_str. ''' print '>>> task 2 -\tscale text_object\n' text_object = TextObject() text_object.text_str('foobar') text_object.set_font_size(12) print 'original size:\t{0}'.format(text_object.check_text_dimensions()) text_object.scale(2,1) print 'scaled size:\t{0}'.format(text_object.check_text_dimensions()) text_object.scale(2,4) #scaling handle absolute values, currently values entered before will be overwritten print 'rescaled size:\t{0}'.format(text_object.check_text_dimensions()) print 50*'-'
def draw_menu(self): w, h = pygame.display.get_surface().get_size() exit_button = TextObject(610, 630, "Exit(Esc)", c.font_color, c.font_name, c.font_size) help_button = TextObject(380, 630, "Help(H)", c.font_color, c.font_name, c.font_size) reset_button = TextObject(510, 710, "New Game(N)", c.font_color, c.font_name, c.font_size) exit_button.draw(self.surface) help_button.draw(self.surface) reset_button.draw(self.surface) if self.help_opened: self.draw_help() if self.game_over: self.draw_victory()
def task_1(): ''' @note: text_object - an object for text data and several methods text_object.text_str - Some arbitrary text. It can be any length of characters. text_object.setfontsize(fontsize) - A method with one parameter to set the fontsize in points of the text_str. text_object.check_text_dimensions() - A method which returns the height and width in pixels of the text_str using the current font size ''' print '>>> task 1 -text_object basics\n' text_object = TextObject() text_object.text_str('foobar') text_object.set_font_size(11) print 'text size with 11pt:\t{0}'.format(text_object.check_text_dimensions()) text_object.set_font_size(18) print 'text size with 18pt:\t{0}'.format(text_object.check_text_dimensions()) text_object.scale(0.5, 0.5) print 'shrinked text:\t{0}'.format(text_object.check_text_dimensions()) text_object.scale(2, 1.5) print 'bloated text:\t{0}'.format(text_object.check_text_dimensions()) print 50*'-'