def _get_raw_shadow(self): target_img = self.target.get_image(self.capture_state) r = target_img.get_rect() #the shadow will be larger in order to make free space for fadeout. r.inflate_ip(2*self.shadow_radius, 2*self.shadow_radius) img = Surface(r.size) img.fill((255, 255, 255, 255)) img.blit(target_img, (self.shadow_radius, self.shadow_radius)) if self.sun_angle <= 0.: raise Exception("Sun angle must be greater than zero.") elif self.sun_angle != 45. and self.vertical: w, h = img.get_size() new_h = h / tan(self.sun_angle * pi / 180.) screen_size = functions.get_screen().get_size() new_h = abs(int(min(new_h, max(screen_size)))) img = scale(img, (w, new_h)) if self.angle_mode == "flip": img = flip(img, self.mode_value[0], self.mode_value[1]) elif self.angle_mode == "rotate": img = rotate(img, self.mode_value) else: raise Exception("angle_mode not available: " + str(self.angle_mode)) shadow = pilgraphics.get_shadow(img, radius=self.shadow_radius, black=self.black, alpha_factor=self.alpha_factor, decay_mode=self.decay_mode, color=self.color) return shadow
def _blit_to_block(self, text_array, text_color=(255, 255, 255), block_color=(0, 0, 0)): """ Takes an array of strings with optional text and background colors, creates a Surface to house them, blits the text and returns the Surface. """ rendered_text = [] font_width = [] font_height = [] for text in text_array: ren = self.__font.render(text, True, text_color) rendered_text.append(ren) fw, fh = ren.get_size() font_width.append(fw) font_height.append(fh) block = Surface((max(font_width) + 20, sum(font_height) + 20)) block.fill(block_color) h = 10 for text in rendered_text: block.blit(text, (10, h)) h += font_height[0] return block
def draw_equipment_item(self, pane): equip_item_pane = Surface((EQUIPMENT_ITEM_WIDTH, EQUIPMENT_ITEM_HEIGHT)) self.draw_border(equip_item_pane) items = [] equipment = self.player.inventory.items_of_type(Equipment) current_equipment = self.selected_party_member.equipment_set.equipment for e in equipment: if not e.equippable_in_slot(self.selected_equip_slot): continue if self.selected_party_member.party_class not in e.compatible_classes: continue if e.equipped and not e in current_equipment.values(): continue if self.selected_equip_slot == "left_hand" and e.equipped and e.equip_slot != self.selected_equip_slot and not e.left_equipped: continue if self.selected_equip_slot == "right_hand" and e.equipped and e.left_equipped: continue items.append(e) self.current_equip_items = items page_index = self.equipment_item_index/EQUIPMENT_PAGE_SIZE start = page_index*EQUIPMENT_PAGE_SIZE end = min(len(items), start + EQUIPMENT_PAGE_SIZE) for i in range(start, end): item = items[i] text = item.name if item.equipped: text += item.equip_tag() text_image = self.ui_font.render(text, True, WHITE) equip_item_pane.blit(text_image, (28, 8 + 40*(i%EQUIPMENT_PAGE_SIZE))) index = self.equipment_item_index%EQUIPMENT_PAGE_SIZE self.draw_pane_pointer(equip_item_pane, index) # TODO: multiple pages of equipment. Navigate w/ left and right arrow keys self.draw_equipment_page_numbers(equip_item_pane) pane.blit(equip_item_pane, (EQUIPMENT_ITEM_X, EQUIPMENT_ITEM_Y))
def join_files(target, sources, images_per_line): lines = len(sources) / images_per_line if len(sources) % images_per_line != 0: lines += 1 first = pygame.image.load(sources[0]) w, h = first.get_width(), first.get_height() result = Surface((w * images_per_line, h * lines)).convert_alpha() result.fill((255, 255, 255, 0)) for i, source in enumerate(sources): im = pygame.image.load(source) im.convert_alpha() if im.get_width() != w or im.get_height() != h: print 'Image %s is not of the same size as the first' exit() x = w * (i % images_per_line) y = h * (i / images_per_line) result.blit(im, (x, y)) # bg = Surface((640, 480), depth=32) # bg.convert_alpha() # bg.fill((255, 0, 0)) # bg.blit(result, (0, 0)) # d.blit(bg, (0, 0)) # pygame.display.flip() # raw_input() pygame.image.save(result, target)
def render(self, text, color): words = text.split() lines = [] h = 0 i = 0 j = 1 while i < len(words): found = False if j == len(words): found = True elif self._font.size(' '.join(words[i:j]))[0] >= self._width: j = max(1, j-1) found = True if found: line = self._font.render(' '.join(words[i:j]), True, color) lines.append(line) h += line.get_height() i = j else: j += 1 image = Surface((self._width, h), flags=SRCALPHA) h = 0 for line in lines: image.blit(line, (0, h)) h += line.get_height() return image
def draw_grid(self, tileset): """Returns an image of a tile-based grid""" img = Surface((self.xsize * SIZE, self.ysize * SIZE)) for pos, char in self: rect = get_tile_rect(pos) img.blit(tileset.image, rect, tileset.positions[char]) return img
def main(self, screen): clock = pygame.time.Clock() background = Surface(screen.get_size()) background.blit(construct_nightmare(background.get_size()), (0, 0)) self.matris = Matris() matris_border = Surface((MATRIX_WIDTH * BLOCKSIZE + BORDERWIDTH * 2, VISIBLE_MATRIX_HEIGHT * BLOCKSIZE + BORDERWIDTH * 2)) matris_border.fill(BORDERCOLOR) while 1: dt = clock.tick(45) self.matris.update((dt / 1000.) if not self.matris.paused else 0) if self.matris.gameover: return tricky_centerx = WIDTH - (WIDTH - (MATRIS_OFFSET + BLOCKSIZE * MATRIX_WIDTH + BORDERWIDTH * 2)) / 2 background.blit(matris_border, (MATRIS_OFFSET, MATRIS_OFFSET)) background.blit(self.matris.surface, (MATRIS_OFFSET + BORDERWIDTH, MATRIS_OFFSET + BORDERWIDTH)) nextts = self.next_tetromino_surf(self.matris.surface_of_next_tetromino) background.blit(nextts, nextts.get_rect(top = MATRIS_OFFSET, centerx = tricky_centerx)) infos = self.info_surf() background.blit(infos, infos.get_rect(bottom = HEIGHT - MATRIS_OFFSET, centerx = tricky_centerx)) screen.blit(background, (0, 0)) pygame.display.flip()
def reset_screen(img_file=None, color=BACKGROUND_COLOR): # Test display if not pyg.display.get_init(): pyg.init() # Init screen flag = pyg.FULLSCREEN #| pyg.DOUBLEBUF | pyg.HWSURFACE flag *= Constants.FULLSCREEN flag |= pyg.NOFRAME * NOFRAME screen = pyg.display.set_mode(WINDOW_SIZE, flag) ico = load_image(ICON_FILE).convert_alpha() pyg.display.set_icon(ico) pyg.display.set_caption(WINDOW_TITLE) # Build background background = Surface(WINDOW_SIZE) background.fill(color) # Get background if isinstance(img_file, basestring): image = load_image(img_file).convert_alpha() width = int(WINDOW_WIDTH * REDUCE_FACTOR) height = int(WINDOW_HEIGHT *REDUCE_FACTOR) image = pyg.transform.smoothscale(image, (width,height)) center = WINDOW_WIDTH/2, WINDOW_HEIGHT/2 background.blit(image, image.get_rect(center=center)) # Apply background screen.blit(background, background.get_rect()) pyg.display.flip() # Return screen return screen, background
def render(self, text): """ Renders the text using the options first used. """ lines = text.splitlines() img = Surface(self._calculate_image_size(self.font, self.text, self.size, self.line_spacer, self.layers)) if self.bg_transparent: img.set_colorkey(self.background) full_rect = img.get_rect() y = 0 for l in lines: r = self.font.render(l, self.size, self.background, self.bg_transparent, self.layers) r_rect = r.get_rect() if self.bg_transparent: r.set_colorkey(self.background) if self.align == self.A_CENTER: x = self._center_rect_inside_rect(r_rect, full_rect) elif self.align == self.A_LEFT: x = 0 elif self.align == self.A_RIGHT: x = full_rect[3] - r_rect[3] img.blit(r, (x, y)) y += self.line_spacer + r_rect[3] return img
def create_tag_image( tags, output, size=(500,500), background=(255, 255, 255), layout=LAYOUT_MIX, fontname=DEFAULT_FONT, rectangular=False): """ Create a png tag cloud image """ if not len(tags): return sizeRect, tag_store = _draw_cloud(tags, layout, size=size, fontname=fontname, rectangular=rectangular) if type(output) == pygame.Surface: image_surface = output else: image_surface = Surface((sizeRect.w + 2*TAG_CLOUD_PADDING, sizeRect.h + 2*TAG_CLOUD_PADDING), SRCALPHA, 32) image_surface.fill(background) for tag in tag_store: image_surface.blit(tag.image, (tag.rect.x - sizeRect.x + TAG_CLOUD_PADDING, tag.rect.y - sizeRect.y + TAG_CLOUD_PADDING)) pygame.image.save(image_surface, output)
def __init__(self, tag, initial_position, rotation=0, fontname=DEFAULT_FONT, fontzoom=5): Sprite.__init__(self) self.tag = copy(tag) self.rotation = rotation font_spec = load_font(fontname) #fonter = font.Font(os.path.join(FONT_DIR, font_spec['ttf']), int(tag['size'] * fontzoom)).render(tag['tag'], True, tag['color']) # changing to allow for arbitrary local fonts fonter = font.Font(font_spec['ttf'], int(tag['size'] * fontzoom)).render(tag['tag'], True, tag['color']) self.tag['size'] *= fontzoom fonter = transform.rotate(fonter, rotation) frect = fonter.get_bounding_rect() frect.x = -frect.x frect.y = -frect.y self.fontoffset = (-frect.x, -frect.y) font_sf = Surface((frect.width, frect.height), pygame.SRCALPHA, 32) font_sf.blit(fonter, frect) self.image = font_sf self.rect = font_sf.get_rect() self.rect.width += TAG_PADDING self.rect.height += TAG_PADDING self.rect.x = initial_position[0] self.rect.y = initial_position[1] self.mask = mask.from_surface(self.image) self.mask = self.mask.convolve(CONVMASK, None, (TAG_PADDING, TAG_PADDING))
def make_background(self,img_file,desktop_size): in_img = image.load(img_file) out_img = Surface(desktop_size) for x in range((out_img.get_width() // in_img.get_width()) + 1): for y in range((out_img.get_height() // in_img.get_height()) + 1): out_img.blit(in_img, (in_img.get_width() * x, in_img.get_height() * y)) return out_img
def set_alpha_from_intensity(surface, alpha_factor, decay_mode, color): if not HAS_PIL: raise Exception("PIL was not found on this machine.") if not HAS_NUMPY: raise Exception("NumPy was not found on this machine.") rect = surface.get_rect() newsurf = Surface(rect.size, SRCALPHA, depth=surface.get_bitsize()) newsurf = newsurf.convert_alpha() newsurf.blit(surface, (0, 0)) arrayrgb = surfarray.pixels3d(newsurf) arraya = surfarray.pixels_alpha(newsurf) bulk_color = tuple(color) for x in range(rect.left, rect.right): for y in range(rect.top, rect.bottom): color = tuple(arrayrgb[x][y]) light = square_color_norm(color) alpha = float(light)/MAX_NORM * 255 arrayrgb[x][y][0] = bulk_color[0] arrayrgb[x][y][1] = bulk_color[1] arrayrgb[x][y][2] = bulk_color[2] if decay_mode == "linear": actual_alpha = int(255 - alpha) elif decay_mode == "exponential": tuning_factor = 1.03 actual_alpha = int(255*tuning_factor**-alpha) ## elif decay_mode == "quadratic": ## pass else: raise Exception("decay_mode not recognized: " + decay_mode) actual_alpha *= alpha_factor arraya[x][y] = actual_alpha return newsurf
def create_dialog(self): f = font.Font(font.get_default_font(), 30) text = f.render(self.text, True, (255, 255, 255)) dialog = Surface((text.get_width() + 20, text.get_height() + 20)) self.stroke(dialog, (255, 0, 0)) dialog.blit(text, ((dialog.get_width() - text.get_width()) / 2, (dialog.get_height() - text.get_height()) / 2)) return dialog
def highlight(self): if not self.highlighted: (x, y) = self.pos() (w, h) = self.rect.size (lw, lh) = (round(w * 1.5), round(h * 1.5)) img = Surface((lw, lh), pygame.SRCALPHA) img.fill(COLOR_WHITE) a = surfa.pixels_alpha(img) d = max(lw, lh) / 2 (cx, cy) = (lw // 2, lh // 2) for i in range(len(a)): for j in range(len(a[i])): k = math.sqrt(sqr(100.0 * (i - cx) / cx) + sqr(100.0 * (j - cy) / cy)) if k > 100: a[i][j] = 0 else: a[i][j] = 255 - round(k / 100.0 * 255.0) a = None img.blit(self.image, ((lw - w) // 2, (lh - h) // 2)) self.image = img self.set_pos(x - (lw - w) // 2, y - (lh - h) // 2) self.highlighted = True
class Track(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.equation = test_equation self.color = Color("#C98C57") self.generate_track_image() self.rect = Rect(0, 0, WIN_WIDTH, WIN_HEIGHT) self.mask = pygame.mask.from_surface(self.image) def generate_track_image(self): self.image = Surface((WIN_WIDTH, WIN_HEIGHT)) self.image.fill(DEFAULT_COLORKEY) self.image.set_colorkey(DEFAULT_COLORKEY) track_painter = Surface((32, 32)) track_painter.fill(self.color) x, y = self.coordinates(0) for i in xrange(1000): dest_x, dest_y = self.coordinates(i) while(abs(x - dest_x) > 1 or abs(y - dest_y) > 1): vec_x, vec_y = dest_x - x, dest_y - y length = math.pow( math.pow(vec_x, 2) + math.pow(vec_y, 2), 0.5) add_x, add_y = vec_x/length, vec_y/length x += add_x y += add_y self.image.blit(track_painter, (x, y)) if x < -1*MAX_OUTSIDE_DISTANCE or x > WIN_WIDTH + MAX_OUTSIDE_DISTANCE or y < -1*MAX_OUTSIDE_DISTANCE or y > WIN_HEIGHT + MAX_OUTSIDE_DISTANCE: break def coordinates(self, t): return self.equation(t)
def create_tag_image( tags, file, size=(800, 600), background=(255, 255, 255), layout=LAYOUT_MIX, crop=True, fontname=DEFAULT_FONT, palette=DEFAULT_PALETTE, fontzoom=2, rectangular=False): """ Create a png tag cloud image """ image_surface = Surface(size, SRCALPHA, 32) image_surface.fill(background) tag_store = _draw_cloud(tags, image_surface, layout, fontname=fontname, palette=palette, fontzoom=fontzoom, rectangular=rectangular) if crop: boundingRect = _get_group_bounding(tag_store, size) crop_surface = Surface((boundingRect.width, boundingRect.height), pygame.SRCALPHA, 32) crop_surface.blit(image_surface, (0, 0), area=boundingRect) pygame.image.save(crop_surface, file) else: pygame.image.save(image_surface, file)
def rotated_bolt_image(self, angle): image = Surface((32, 32)) image.set_colorkey(DEFAULT_COLORKEY) image.fill(DEFAULT_COLORKEY) image.blit(self.projectile_image, (0, 0)) image = pygame.transform.rotate(image, angle) return image
class Coche(Rect): coche0 = image.load(os.path.join(imagesrep,'button0.png')) coche1 = image.load(os.path.join(imagesrep,'button1.png')) font = font.Font(os.path.join(thisrep,'MonospaceTypewriter.ttf'),8) def __init__(self,label='',fgcolor=(255,255,255),font=None): if not font: font = Coche.font Rect.__init__(self,Coche.coche0.get_rect()) self.scr = display.get_surface() self.status = False label = Coche.font.render(label,1,fgcolor) Rlabel = label.get_rect() Rlabel.midleft = self.midright self.label = Surface(self.union(Rlabel).size,SRCALPHA) self.label.blit(label,Rlabel) def update(self,ev): if ev.type == MOUSEBUTTONUP and self.collidepoint(ev.pos): self.status ^= 1 return True def screen(self): self.scr.blit(Coche.coche1 if self.status else Coche.coche0,self) self.scr.blit(self.label,self)
def load_transparent_image(self): image = Surface((32, 32)) image.fill(DEFAULT_COLORKEY) image.set_colorkey(DEFAULT_COLORKEY) image.blit(self.image, (0, 0)) image.set_alpha(120) self.transparent_image = image
def block(self, color, shadow = False): colors = {'blue': (27, 34, 224), 'yellow': (225, 242, 41), 'pink': (242, 41, 195), 'green': (22, 181, 64), 'red': (204, 22, 22), 'orange': (245, 144, 12), 'cyan': (10, 255, 226)} if shadow: end = [40] # end is the alpha value else: end = [] # Adding this to the end will not change the array, thus no alpha value border = Surface((self.blocksize, self.blocksize), pygame.SRCALPHA, 32) border.fill(map(lambda c: c*0.5, colors[color]) + end) borderwidth = 2 box = Surface((self.blocksize-borderwidth*2, self.blocksize-borderwidth*2), pygame.SRCALPHA, 32) boxarr = pygame.PixelArray(box) for x in range(len(boxarr)): for y in range(len(boxarr)): boxarr[x][y] = tuple(map(lambda c: min(255, int(c*random.uniform(0.8, 1.2))), colors[color]) + end) del boxarr # deleting boxarr or else the box surface will be 'locked' or something like that and won't blit border.blit(box, Rect(borderwidth, borderwidth, 0, 0)) return border
def get_surface(self): W, H = functions.get_screen_size() if isinstance(self.img_path, str): # load image surface = load_image(self.img_path) else: # take image surface = self.img_path if 0 < self.alpha < 255: surface.set_alpha(self.alpha, RLEACCEL) if self.mode == "scale to screen": surface = scale(surface, (W, H)) self.size = (W, H) elif self.mode == "cut to screen": new_surface = Surface((W, H)) new_surface.blit(surface, (0, 0)) self.size = (W, H) elif self._resized: surface = scale(surface, self._resized) elif self.mode: functions.debug_msg("Unrecognized mode : ", self.mode) ## elif self._resized: ## surface = scale(surface, self._resized) if self.colorkey: surface.set_colorkey(self.colorkey, RLEACCEL) surface.set_clip(self.clip) if self.alpha < 255: return surface.convert_alpha() else: return surface.convert()
def combine_imgs(img_list, list_size): combined_img = Surface((list_size[0], list_size[1])) y = 0 for img in img_list: combined_img.blit(img, (0, y)) y += img.get_size()[1] return combined_img
def create_tag_image( tags, output, size=(500,500), background=(255, 255, 255), layout=LAYOUT_MIX, fontname=DEFAULT_FONT, rectangular=False): """ Create a png tag cloud image """ if not len(tags): return sizeRect, tag_store = _draw_cloud(tags, layout, size=size, fontname=fontname, rectangular=rectangular) image_surface = Surface((sizeRect.w, sizeRect.h), SRCALPHA, 32) image_surface.fill(background) for tag in tag_store: image_surface.blit(tag.image, tag.rect) pygame.image.save(image_surface, output)
class RiverOptionButton(): def __init__(self, option, size, hover, pos): self.option = option self.size = size self.hover = hover self.size = size self.surface = Surface(self.size).convert() self.pos = pos if self.hover: self.surface.fill((200, 200, 200)) else: self.surface.fill((255, 255, 255)) self.rect = Rect(self.pos, self.size) self.button_font = font.Font(None, 25) self.surface.blit(self.button_font.render(self.option, 1, (0, 0, 0)), (5, self.size[1]/2 - self.button_font.size("Lorem Ipsum")[1]/2)) def update(self, hover): if hover: self.surface.fill((200, 200, 200)) else: self.surface.fill((255, 255, 255)) self.rect = Rect(self.pos, self.size) self.button_font = font.Font(None, 25) self.surface.blit(self.button_font.render(self.option, 1, (0, 0, 0)), (5, self.size[1]/2 - self.button_font.size("Lorem Ipsum")[1]/2))
def make_background(self, img_file, desktop_size): in_img = image.load(img_file) out_img = Surface(desktop_size) out_img.fill((0, 0, 0)) left = (out_img.get_width() - in_img.get_width()) / 2 top = (out_img.get_height() - in_img.get_height()) / 2 out_img.blit(in_img, (left, top)) return out_img
def draw_grid(self, tile_img, tiles): """Returns an image of a tile-based grid""" #debug_print("drawing level", data) img = Surface((self.xsize * SIZE, self.ysize * SIZE)) for pos, char in self: rect = get_tile_rect(pos) img.blit(tile_img, rect, tiles[char]) return img
def draw_action_options(self, pane): data_pane = Surface((ACTION_OPTIONS_WIDTH, ACTION_OPTIONS_HEIGHT)) for i in xrange(len(ACTION_OPTION_LIST)): text = ACTION_OPTION_LIST[i].capitalize() text_image = self.ui_font.render(text, True, WHITE) data_pane.blit(text_image, (28, 8 + 40*i)) pygame.draw.lines(data_pane, WHITE, True, [(0, 0), (ACTION_OPTIONS_WIDTH - 2, 0), (ACTION_OPTIONS_WIDTH - 2, ACTION_OPTIONS_HEIGHT - 2), (0, ACTION_OPTIONS_HEIGHT - 2)], 2) if not self.mode == EXECUTE_ACTIONS: self.draw_action_pointer(data_pane) pane.blit(data_pane, (PARTY_DATA_WIDTH, 0))
def _drawboxes(self, branch, key, a, b, aval, bval): boxes = Surface((a.get_width() + b.get_width(), self._emp.get_height()), flags=SRCALPHA) locs = (0,0), (a.get_width(), 0) boxes.blit(a, locs[0]) boxes.blit(b, locs[1]) return [(Rect(locs[i], self._emp.get_size()), 1, self._boxhandler(branch, key, (aval,bval)[i])) for i in range(len(locs))], boxes
def draw_map(data, img, tiles): """Returns an image of a tile-based map""" xs = len(data[0]) * SIZE ys = len(data) * SIZE map_img = Surface((xs, ys)) for y, row in enumerate(data): for x, char in enumerate(row): map_img.blit(img, Rect((x*SIZE, y*SIZE, 0, 0)), tiles[char]) return map_img
def render(self, surface: pygame.Surface): surface.blit(self.__renderedText, self.getTopLeftPixelCoordinates(surface))
square_list = [] done = True timer = Clock() while done: for e in event.get(): if e.type == KEYDOWN: if e.key == K_ESCAPE: done = False screen.fill((30, 30, 50)) # draw lables for lable in lable_x_positions: screen.blit(ff.render(lable[0], 1, (40, 40, 70)), (lable[1], lable_start_y * (lable_x_positions.index(lable) + 1))) if len(square_list) < 500: for i in range(randint(1, 5)): square_list.append(Round_square(randint(0, W), randint(0, H))) for sq in square_list: if sq.radius >= 50: square_list.remove(sq) else: sq.blit(screen) window.blit(screen, (0, 0)) display.flip() timer.tick(60)
def draw(self, surface: pg.Surface): surface.blit( self.image, self.rect, pg.Rect(self.ani_frame * self.rect.w, self.ani * self.rect.h, *self.rect.size))
def render_textrect(string, font, width, text_color, background_color, justification=0): """Returns a surface containing the passed text string, reformatted to fit within the given rect, word-wrapping as necessary. The text will be anti-aliased. Takes the following arguments: string - the text you wish to render. \n begins a new line. font - a Font object rect - a rectstyle giving the size of the surface requested. text_color - a three-byte tuple of the rgb value of the text color. ex (0, 0, 0) = BLACK background_color - a three-byte tuple of the rgb value of the surface. justification - 0 (default) left-justified 1 horizontally centered 2 right-justified Returns the following values: Success - a surface object with the text rendered onto it. Failure - raises a TextRectException if the text won't fit onto the surface. """ from pygame import Surface final_lines = [] requested_lines = string.splitlines() # Create a series of lines that will fit on the provided # rectangle. for requested_line in requested_lines: if font.size(requested_line)[0] > width: words = requested_line.split(' ') # if any of our words are too long to fit, return. for word in words: if font.size(word)[0] >= width: raise TextRectException( "The word " + word + " is too long to fit in the rect passed.") # Start a new line accumulated_line = "" for word in words: test_line = accumulated_line + word + " " # Build the line while the words fit. if font.size(test_line)[0] < width: accumulated_line = test_line else: final_lines.append(accumulated_line) accumulated_line = word + " " final_lines.append(accumulated_line) else: final_lines.append(requested_line) # Let's try to write the text out on the surface. accumulated_height = 0 for line in final_lines: accumulated_height += font.size(line)[1] surface = Surface((width, accumulated_height)) surface.fill(background_color) accumulated_height = 0 for line in final_lines: if line != "": tempsurface = font.render(line, 1, text_color) if justification == 0: surface.blit(tempsurface, (0, accumulated_height)) elif justification == 1: surface.blit(tempsurface, ((width - tempsurface.get_width()) / 2, accumulated_height)) elif justification == 2: surface.blit( tempsurface, (width - tempsurface.get_width(), accumulated_height)) else: raise TextRectException("Invalid justification argument: " + str(justification)) accumulated_height += font.size(line)[1] return surface
def drawNote(self, screen: pygame.Surface): img = pygame.image.load(self.img).convert() rect = img.get_rect() rect.center = screen.get_width() // 2, screen.get_height() // 2 screen.blit(img, rect) self.display_currently_played_notes(screen)
def draw_ui(screen: pygame.Surface, state: dict) -> None: """Draw the score and indicate whose turn it is. Keyword arguments: screen -- the reference to the screen that will print the game UI elements (trapper's icon, mouse's icon, medal, score text and endgame text) state -- a dictionary containing the current state of the game (see 'initialize_board()') """ # Draw the trapper icon in the lower left of the window cell_p1 = compute_hexagon(PADDING_X / 2 - SIZE, HEIGHT - 2.5 * SIZE) if state["turn"] == P1: draw_hexagon(screen, COLOR_OBSTACLE, cell_p1) elif state["winner"] == "PLAYING": draw_hexagon(screen, WHITE, cell_p1) # Draw the mouse icon in the lower right of the window cell_p2 = compute_hexagon(WIDTH - SIZE - PADDING_X / 2, HEIGHT - 2.5 * SIZE) if state["turn"] == P2: draw_hexagon(screen, COLOR_MOUSE, cell_p2) elif state["winner"] == "PLAYING": draw_hexagon(screen, WHITE, cell_p2) try: font = pygame.font.Font("roboto-regular.ttf", 48) except FileNotFoundError: font = pygame.font.SysFont("calibri", 48) # Draw the score on the upper center of the window score = str(state["score"] + PENALTY) score_text = font.render(score, True, WHITE) score_rect = score_text.get_rect() score = str(state["score"]) score_text = font.render(score, True, WHITE) rect = pygame.rect.Rect(WIDTH / 2 - score_rect.w / 2, PADDING_Y / 2 - score_rect.h / 2, score_rect.w, score_rect.h) pygame.draw.rect(screen, COLOR_BACKGROUND, rect) score_rect = score_text.get_rect() screen.blit( score_text, (WIDTH / 2 - score_rect.w / 2, PADDING_Y / 2 - score_rect.h / 2)) pygame.display.update(score_rect) if state["winner"] == "PLAYING": return try: font = pygame.font.Font("roboto-bold.ttf", 28) except FileNotFoundError: font = pygame.font.SysFont("arial", 28) # Draw the end game message on the lower center of the window message = { "DRAW": ("It's a draw!- Press R for a rematch...", WHITE), P1: ("The Trapper- won with " + score + " points! Press R for a rematch...", COLOR_OBSTACLE), P2: ("The Mouse- won with " + score + " points! Press R for a rematch...", COLOR_MOUSE), } message_winner = message[state["winner"]][0].split("-")[0] message_rematch = message[state["winner"]][0].split("-")[1] message_winner_text = font.render(message_winner, True, message[state["winner"]][1]) message_rematch_text = font.render(message_rematch, True, WHITE) message_winner_rect = message_winner_text.get_rect() message_rematch_rect = message_rematch_text.get_rect() message_rect = pygame.rect.Rect( 0, 0, message_winner_rect.w + message_rematch_rect.w, max(message_winner_rect.h, message_rematch_rect.h)) screen.blit(message_winner_text, (WIDTH / 2 - message_rect.w / 2, HEIGHT - PADDING_Y / 2 - message_rect.h / 2)) screen.blit(message_rematch_text, (WIDTH / 2 - message_rect.w / 2 + message_winner_rect.w, HEIGHT - PADDING_Y / 2 - message_rect.h / 2)) pygame.display.update(message_rect) if state["winner"] == "DRAW": return try: winner = pygame.image.load("medal.png") except FileNotFoundError: return # Draw a medal on top of the winner's icon winner_rect = winner.get_rect() if state["winner"] == P1: winner_rect.x = cell_p1[0] winner_rect.y = cell_p1[3] elif state["winner"] == P2: winner_rect.x = cell_p2[0] winner_rect.y = cell_p2[3] screen.blit(winner, winner_rect) pygame.display.update(winner_rect)
def display(self, screen: pygame.Surface): if not self.intro_shown: screen.fill(CONFIG.BG_COLOR) level_str = 'LEVEL ' + str(int(CONFIG.CURRENT_LEVEL) + 1) screen.blit( CONFIG.readable_font.render(level_str, 1, ( 240, 249, 255, )), ( CONFIG.WINDOW_WIDTH / 2 - (len(level_str) * CONFIG.CHARACTER_SIZE / 4), CONFIG.WINDOW_HEIGHT / 2, )) screen.blit( CONFIG.readable_font.render(self.level.game_time, 1, ( 240, 249, 255, )), ( CONFIG.WINDOW_WIDTH / 2 - (len(level_str) * CONFIG.CHARACTER_SIZE / 4), CONFIG.WINDOW_HEIGHT / 2 + 2 * CONFIG.CHARACTER_SIZE, )) if time.time() - self.intro_timer >= self.intro_time: self.intro_shown = True else: self.level.display(screen) # Display HUD if self.can_show_hud: screen.blit(self.hud_elements[0], ( 0, CONFIG.WINDOW_HEIGHT - self.hud_height, )) screen.blit(self.hud_elements[1], ( self.hud_width, CONFIG.WINDOW_HEIGHT - self.hud_height, )) screen.blit(self.hud_elements[2], ( CONFIG.WINDOW_WIDTH - self.hud_width, CONFIG.WINDOW_HEIGHT - self.hud_height, )) screen.blit(self.hud_game_time_sprite, ( CONFIG.WINDOW_WIDTH - len(self.level.game_time) * 13 + 32, CONFIG.WINDOW_HEIGHT - 32, ))
def draw(self, surf: pygame.Surface): surf.blit(self.anim.current_image, (self.x, self.y))
def _run_ai_simulation(game_surface: pygame.Surface, size: int, player1: Union[MobilityTreePlayer, PositionalTreePlayer, RandomPlayer, ReversiGame, MCTSTimeSavingPlayer], player2: Union[MobilityTreePlayer, PositionalTreePlayer, RandomPlayer, ReversiGame, MCTSTimeSavingPlayer]) -> None: if size == 8: background = pygame.image.load('assets/gameboard8.png') elif size == 6: background = pygame.image.load('assets/gameboard6.png') else: raise ValueError("invalid size.") game_surface.blit(background, (0, 0)) pygame.display.flip() game = ReversiGame(size) previous_move = '*' board = game.get_game_board() _draw_game_state(game_surface, background, size, board) pass_move = pygame.image.load('assets/pass.png') player1_side = BLACK while game.get_winner() is None: if previous_move == '*' or game.get_current_player() == player1_side: move = player1.make_move(game, previous_move) else: move = player2.make_move(game, previous_move) previous_move = move game.make_move(move) if move == 'pass': surface = game_surface game_surface.blit(pass_move, (300, 300)) pygame.display.flip() pygame.time.wait(500) game_surface.blit(surface, (0, 0)) pygame.display.flip() else: board = game.get_game_board() _draw_game_state(game_surface, background, size, board) pygame.time.wait(500) winner = game.get_winner() if winner == BLACK: victory = pygame.image.load('assets/player1_victory.png') game_surface.blit(victory, (300, 300)) pygame.display.flip() pygame.time.wait(3000) return elif winner == WHITE: defeat = pygame.image.load('assets/player2_victory.png') game_surface.blit(defeat, (300, 300)) pygame.display.flip() pygame.time.wait(3000) return else: draw = pygame.image.load('assets/draw.png') game_surface.blit(draw, (300, 300)) pygame.display.flip() pygame.time.wait(3000) return
def _run_ai_game(game_surface: pygame.Surface, size: int, ai_player: Union[MobilityTreePlayer, PositionalTreePlayer, RandomPlayer, ReversiGame, MCTSTimeSavingPlayer], user_side: str = BLACK) -> None: if size == 8: background = pygame.image.load('assets/gameboard8.png') elif size == 6: background = pygame.image.load('assets/gameboard6.png') else: raise ValueError("invalid size.") game_surface.blit(background, (0, 0)) pygame.display.flip() game = ReversiGame(size) previous_move = '*' if user_side == BLACK: ai_side: str = WHITE else: ai_side: str = BLACK board = game.get_game_board() _draw_game_state(game_surface, background, size, board) pass_move = pygame.image.load('assets/pass.png') while game.get_winner() is None: if (previous_move == '*' and user_side == WHITE) or game.get_current_player() == user_side: if game.get_valid_moves() == ['pass']: game.make_move('pass') previous_move = 'pass' surface = game_surface game_surface.blit(pass_move, (300, 300)) pygame.display.flip() pygame.time.wait(1000) game_surface.blit(surface, (0, 0)) pygame.display.flip() continue while True: event = pygame.event.wait() if event.type == pygame.MOUSEBUTTONDOWN: mouse_pos = pygame.mouse.get_pos() if 585 <= mouse_pos[0] <= 795 and 10 <= mouse_pos[1] <= 41: return else: move = _search_for_move(mouse_pos, size) print(move) if move == '' or move not in game.get_valid_moves(): continue else: previous_move = move game.make_move(move) board = game.get_game_board() _draw_game_state(game_surface, background, size, board) pygame.time.wait(1000) break if event.type == pygame.QUIT: return else: move = ai_player.make_move(game, previous_move) previous_move = move game.make_move(move) if move == 'pass': surface = game_surface game_surface.blit(pass_move, (300, 300)) pygame.display.flip() pygame.time.wait(1000) game_surface.blit(surface, (0, 0)) pygame.display.flip() else: board = game.get_game_board() _draw_game_state(game_surface, background, size, board) winner = game.get_winner() if winner == user_side: victory = pygame.image.load('assets/victory.png') game_surface.blit(victory, (300, 300)) pygame.display.flip() pygame.time.wait(3000) return elif winner == ai_side: defeat = pygame.image.load('assets/defeat.png') game_surface.blit(defeat, (300, 300)) pygame.display.flip() pygame.time.wait(3000) return else: draw = pygame.image.load('assets/draw.png') game_surface.blit(draw, (300, 300)) pygame.display.flip() pygame.time.wait(3000) return
def draw(self, surface: pygame.Surface) -> None: """Draw the image on the surface.""" surface.blit(self._image, (self._x, self._y))
def render(self, display: pygame.Surface): display.fill("#ecdcdf") pygame.draw.polygon(display, "#f4523b", PokeDexInfo.poly_1) pygame.draw.polygon(display, "#fa7248", PokeDexInfo.poly_2) pygame.draw.polygon(display, "#f4523b", PokeDexInfo.poly_3) utils.draw_button_info(display, **self.keys) poke = pokemon.get_pokemon(self.selected + 1) # big big_im = displayer.get_poke(PokeDex.PATH(str(poke.id_)), 3) s_x, s_y = big_im.get_size() display.blit(big_im, (250 - s_x // 2, 300 - s_y // 2)) utils.draw_split_rectangle(display, (477, 60, 530, 50), 0.4, 0.35, "#f0501e", "#000000") utils.draw_arrow(display, True, 742, 56, (255, 255, 255), size=2) utils.draw_arrow(display, False, 742, 114, (255, 255, 255), size=2) y = 62 im = displayer.get_poke(PokeDex.PATH(str(poke.id_)), 0.7) delta_x, delta_y = utils.get_first_color(im) x = 480 display.blit(im, (x, y + 30 - delta_y)) status = game.get_game_instance().get_pokedex_status(self.selected + 1) display.blit(game.FONT_24.render(f"N° {pokemon.to_3_digit(self.selected + 1)}", True, (255, 255, 255)), (x + 50, y + 10)) display.blit(game.FONT_24.render(poke.get_name(True) if poke.id_ != 0 else "???", True, (255, 255, 255)), (689, y + 10)) if status != game.POKEDEX_NEVER_SEEN: display.blit( self.white_pokeball if status == game.POKEDEX_CATCH else utils.POINT_POKEBALL, (950, y + 8) ) x, y = 530, 150 l = 424 h = 40 s = 3 pygame.draw.rect(display, "#dbdbd9", (x, y, l, h,)) display.blit(tx := game.FONT_24.render(poke.get_japan_name(), True, (0, 0, 0)), (x + (l - tx.get_size()[0]) // 2, y + (h - tx.get_size()[1]) // 2)) y += h + s tx = ("type", "size", "weight", "view") tx2 = (None, f'{poke.size} m', f'{poke.weight} Kg', str(game.get_game_instance().get_nb_view(self.selected + 1))) for i in range(4): pygame.draw.rect(display, "#dbdbd9", (x, y, l // 2, h)) pygame.draw.rect(display, "#ffffff", (x + l // 2, y, l // 2, h)) display.blit(sur := game.FONT_24.render(game.get_game_instance().get_message(tx[i]), True, (0, 0, 0)), utils.get_center(sur, (x, y, l // 2, h))) if i != 0: display.blit(sur := game.FONT_24.render(tx2[i], True, (0, 0, 0)), utils.get_center(sur, (x + l // 2 + 5, y, l // 2, h), center_x=False)) else: _x_ = x + l // 2 + 10 for ii in range(len(poke.types)): utils.draw_type(display, _x_, y + h // 2 - 8, poke.types[ii]) _x_ += 106 y += h if i != 3: pygame.draw.rect(display, "#d2d2d2", (x, y, l // 2, s)) pygame.draw.rect(display, "#f3f3f3", (x + l // 2, y, l // 2, h)) y += s pygame.draw.rect(display, "#ffffff", (x, y, l, int(h * 4.5))) x += 5 y += 10 for p_l in hud.Dialog.split(poke.get_pokedex(), 40): display.blit(game.FONT_20.render(p_l, True, (0, 0, 0)), (x, y)) y += game.FONT_SIZE_20[1] + 5
def draw(self, surface: pygame.Surface): surface.blit(self.image, self.rect)
class PygameGraphics: def __init__(self, environment, game_width, game_height, cell_width, cell_height, has_window=True): self.environment = environment self.game_width = game_width self.game_height = game_height self.cell_width = cell_width self.cell_height = cell_height self.canvas_shape = (self.game_height * self.cell_height, self.game_width * self.cell_width, 3) self.changes_cells = [] self.changes_rects = [] self.has_window = has_window self.rectangles = [] for x in range(self.game_width): for y in range(self.game_height): self.rectangles.append( pygame.Rect((x * cell_height, y * cell_width), (cell_width, cell_height))) self.environment.grid.cb_on_cell_change.append(self.on_cell_change) if self.has_window: pygame.display.init() self.canvas = pygame.display.set_mode( (self.canvas_shape[1], self.canvas_shape[0]), 0 # TODO NOFRAME OPENGL, HWSURFACE? DOUBLEBUF? ) else: self.canvas = Surface((self.canvas_shape[1], self.canvas_shape[0])) self.SPRITE_CELL = self._init_sprite(self.bgr2rgb( cell_types.Empty.COLOR), borders=True) self.SPRITE_DELIVERY_POINT = self._init_sprite(self.bgr2rgb( cell_types.OrderDelivery.COLOR), borders=True) self.SPRITE_DELIVERY_POINT_ACTIVE = self._init_sprite(self.bgr2rgb( cell_types.OrderDeliveryActive.COLOR), borders=True) self.SPRITE_PICKUP_POINT = self._init_sprite(self.bgr2rgb( cell_types.OrderPickup.COLOR), borders=True) self.SPRITE_SPAWN_POINT = self._init_sprite(self.bgr2rgb( cell_types.SpawnPoint.COLOR), borders=True) self.SPRITE_AGENT = self._init_sprite(self.bgr2rgb( cell_types.Agent.COLOR), borders=True) self._init_canvas() def bgr2rgb(self, bgr): return bgr[2], bgr[1], bgr[0] def _init_canvas(self): """Construct grid.""" for x in range(self.game_width): for y in range(self.game_height): cell = self.environment.grid.cell(x, y) if cell.type == cell_types.Empty: self.draw_sprite(self.SPRITE_CELL, x, y, setup=True) elif cell.type == cell_types.SpawnPoint: self.draw_sprite(self.SPRITE_SPAWN_POINT, x=x, y=y, setup=True) elif cell.type == cell_types.OrderDelivery: self.draw_sprite(self.SPRITE_DELIVERY_POINT, x=x, y=y, setup=True) #if self.has_window: # pygame.display.flip() def draw_sprite(self, sprite, x, y, setup=False): i = x * self.game_height + y self.canvas.blit(sprite, self.rectangles[i]) def _init_sprite(self, color, borders=False, border_width=1, border_color=(0, 0, 0)): rect = pygame.Rect((0, 0, self.cell_width, self.cell_height)) surf = pygame.Surface((self.cell_width, self.cell_height)) if borders: surf.fill(border_color, rect) surf.fill(color, rect.inflate(-border_width * 2, -border_width * 2)) else: surf.fill(color, rect) return surf def on_cell_change(self, cell): self.changes_cells.append(cell) self.changes_rects.append(self.rectangles[cell.i]) def blit(self): for cell in self.changes_cells: rect = self.rectangles[cell.i] # TODO automate this if clause... if cell.occupant: self.canvas.blit(self.SPRITE_AGENT, rect) elif cell.type == cell_types.Empty: self.canvas.blit(self.SPRITE_CELL, rect) elif cell.type == cell_types.SpawnPoint: self.canvas.blit(self.SPRITE_SPAWN_POINT, rect) elif cell.type == cell_types.OrderDelivery: self.canvas.blit(self.SPRITE_DELIVERY_POINT, rect) elif cell.type == cell_types.OrderDeliveryActive: self.canvas.blit(self.SPRITE_DELIVERY_POINT_ACTIVE, rect) elif cell.type == cell_types.OrderPickup: self.canvas.blit(self.SPRITE_PICKUP_POINT, rect) if self.has_window: pygame.display.update(self.changes_rects) self.changes_rects.clear() self.changes_cells.clear() def reset(self): if self.has_window: pygame.display.flip() def draw_agent(self, agent): pass def draw_pickup_point(self, x, y): pass def draw_delivery_point(self, x, y): pass
def invert_color(surface, mask = None, rel_pos = (0, 0), color = (255, 255, 255)): if mask == None: new_surf = Surface(surface.get_size()) new_surf.fill(color) new_surf.blit(surface, (0, 0), special_flags = flag['sub']) return new_surf mask = mask.copy() surf_size = surface.get_size() black_surf = Surface(surf_size) not_inverted_surf = Surface(surf_size) not_inverted_surf.fill((255, 255, 255)) not_inverted_surf.blit(mask, rel_pos, special_flags = flag['sub']) if color != (255, 255, 255): colored_surf = Surface(mask.get_size()) colored_surf.fill(color) mask.blit(colored_surf, (0, 0), special_flags = flag['min']) black_surf.blit(mask, rel_pos) not_inverted_surf.blit(surface, (0, 0), special_flags = flag['min']) black_surf.blit(surface, (0, 0), special_flags = flag['sub']) black_surf.blit(not_inverted_surf, (0, 0), special_flags = flag['max']) return black_surf
def render_onto(self, surf: pygame.Surface, region: pygame.Rect = None, render_children=True, render_border=True): region = super().render_onto(surf, region, render_children=False, render_border=False) # create canvas surface (cached) if self.canvas_cache is None or region.size != surf.get_size(): canvas = pygame.Surface(( region.width * self.canvas_size_factors[0], region.height * self.canvas_size_factors[1], ), pygame.SRCALPHA) canvas.fill((0, 0, 0, 0)) self.canvas_cache = canvas else: canvas = self.canvas_cache super().render_children_onto(canvas) canvas_rect = canvas.get_rect() blit_area = pygame.Rect( canvas_rect.width * self.scroll_area[0], canvas_rect.height * self.scroll_area[1], canvas_rect.width * self.scroll_area[2], canvas_rect.height * self.scroll_area[3], ) # update collision offset value self.collision_offset[0] += blit_area.left self.collision_offset[1] += blit_area.top surf.blit(canvas, region, area=blit_area) # draw scroll bars scroll_bar_rects = [] if self.scroll_bar_x: scroll_bar_rects.append( pygame.Rect( self.scroll_bar_padding + region.width * self.scroll_area[0], region.height - (self.scroll_bar_width + self.scroll_bar_padding), region.width * self.scroll_area[2] - self.scroll_bar_padding * 2, self.scroll_bar_width)) if self.scroll_bar_y: scroll_bar_rects.append( pygame.Rect( region.width - (self.scroll_bar_width + self.scroll_bar_padding), self.scroll_bar_padding + region.height * self.scroll_area[1], self.scroll_bar_width, region.height * self.scroll_area[3] - self.scroll_bar_padding * 2)) for rect in scroll_bar_rects: temp_surf = pygame.Surface(region.size) temp_surf.fill(WHITE) temp_surf.set_colorkey(WHITE) temp_surf.set_alpha(int(255 * self.scroll_bar_opacity)) pygame.draw.rect(temp_surf, self.scroll_bar_color, rect, border_radius=self.scroll_bar_width) surf.blit(temp_surf, region) super().render_border_onto(surf, region)
def draw(self, screen: pygame.Surface) -> None: screen.blit(self._bg_image, self._rect) self.__text_label.draw(screen)
def update_board(self, display: pygame.Surface) -> None: """ This continously updates the board after every move in the Connect 2^2 game. """ # Adding the board background to the game board_background = pygame.image.load('./Assets/BOARD2.png').convert() display.blit(board_background, (0, 0)) """ Grid coordinates of the Board in BOARD2.png: topLeft = (138, 75) bottomLeft = (138, 525) topRight = (663, 75) bottomRight = (663, 525) """ # The size of each slot of the board SLOT_SIZE = 75 HOLE_SIZE = 25 NUMBEROFCOLUMNS = self.board.get_grid_size()[1] NUMBEROFROWS = self.board.get_grid_size()[0] # The matrix representation of the grid grid = self.board.get_grid() # If there is a winner, switch to the end screen if self.board.get_winner() != '-': self._game.set_winner(self.board.get_winner()) self.reset_board() self._game.gamestate = STATE.End # Creates the slots and holes on the board, # then updates the board from the matrix board representation. # This strategy for creating the board was inspired by a tutorial on freeCodeCamp.org. # Video URL: https://www.youtube.com/watch?v=XpYz-q1lxu8 for column in range(NUMBEROFCOLUMNS): for row in range(NUMBEROFROWS): if grid[row][column] == 'X': pygame.draw.circle( display, DARKGREY, (138 + (SLOT_SIZE // 2) + column * (SLOT_SIZE), 75 + (SLOT_SIZE // 2) + row * (SLOT_SIZE)), HOLE_SIZE) elif grid[row][column] == 'O': pygame.draw.circle( display, NAVY, (138 + (SLOT_SIZE // 2) + column * (SLOT_SIZE), 75 + (SLOT_SIZE // 2) + row * (SLOT_SIZE)), HOLE_SIZE) else: pygame.draw.circle( display, LIGHTBLUE, (138 + (SLOT_SIZE // 2) + column * (SLOT_SIZE), 75 + (SLOT_SIZE // 2) + row * (SLOT_SIZE)), HOLE_SIZE) #Displays who's turn it is in the game font = pygame.font.Font("./Assets/joystix_monospace.ttf", 20) if self.turn == 0: text = font.render("Player 1's Turn. Pick Where to Drop Disc.", True, WHITE, BLACK) elif self.turn == 1: text = font.render("Player 2's Turn. Pick Where to Drop Disc.", True, WHITE, BLACK) goal = font.render("Connect 2^2 Discs in a Row.", True, WHITE, BLACK) goalBox = goal.get_rect(center=(400, 35)) textBox = text.get_rect(center=(400, 560)) display.blit(text, textBox) display.blit(goal, goalBox) self.backbtn.draw(display) pygame.display.flip()
def _config_board_graphics(self, board): # quadrants qx, qy, qw, qh = board.quadrant.rect qsurf = Surface([qw, qh]) qsurf.fill(Color('white')) qleft = qsurf.copy() qmid = qsurf.copy() qright = qsurf.copy() qleft.fill(Color('#a66767'), (qx, qy, qw-qx-qx, qh-qy-qy)) qmid.fill(Color('#ddbf95'), (qx, qy, qw-qx-qx, qh-qy-qy)) qright.fill(Color('#8d9360'), (qx, qy, qw-qx-qx, qh-qy-qy)) board.quadrant.left = qleft.convert() board.quadrant.mid = qmid.convert() board.quadrant.right = qright.convert() # pieces b = border = 4 px, py, pw, ph = board.piece.rect psurf = Surface([pw, ph]) psurfs = {} psurf_in = Surface([pw-b-b, ph-b-b]) psurf_in.fill(Color('white')) ROOT_PATH = '/'.join(__file__.replace('\\', '/').split('/')[:-1]) + '/' chinese_font = pygame.font.Font(ROOT_PATH + 'MFSongHe_Noncommercial-Regular.ttf', 48) Piece = self.game.Piece ptexts = { Piece.KING: '王', Piece.GENERAL: '将', Piece.MINISTER: '相', Piece.MAN: '子', Piece.FEUDAL_LORD: '侯', } def draw_triangles(surf, directions, color, radius=8, offset=4): off = offset rx = ry = radius w, h = surf.get_size() for direction in directions: is_corner = direction in Compass.ordinals() vx, vy = (0+off if 'W' in direction.name else (w-1-off if 'E' in direction.name else w//2-1), 0+off if 'N' in direction.name else (h-1-off if 'S' in direction.name else h//2-1)) rx = ry = radius * 75//100 if not is_corner else radius dx, dy = Compass.xy(Compass.flip(direction)) dx, dy = int(dx), int(dy) if is_corner: vx += dx * rx vy += dy * ry Ax, Ay = None, None Bx, By = None, None if not dx: # north, south Ax = vx - rx Bx = vx + rx Ay = By = vy + dy * ry elif not dy: # east, west Ay = vy - ry By = vy + ry Ax = Bx = vx + dx * rx else: # diagonals Ax = vx + dx * rx By = vy + dy * ry Ay = vy Bx = vx tri = [(vx, vy), (Ax, Ay), (Bx, By)] pygame.draw.polygon(surf, color, tri) for piece, directions in self.game.movement_patterns.items(): srf = psurf_in.copy() piece_type = Piece(abs(int(piece))) if piece_type == Piece.KING: srf.fill(Color('#1a602e') if piece > 0 else Color('#a7041f')) draw_triangles(srf, directions, Color('white')) else: draw_triangles(srf, directions, Color('black')) piece_text = ptexts[piece_type] ptext_srf = chinese_font.render(piece_text, True, (0,0,0)) ptext_srf = pygame.transform.rotate(ptext_srf, 90 if piece > 0 else 270) srf.blit(ptext_srf, ptext_srf.get_rect(center=srf.get_rect().center)) pouter = psurf.copy() pouter.fill(Color('#244f21') if piece > 0 else Color('#75131c')) pouter.blit(srf, (b, b)) psurfs[piece] = pouter.convert() board.piece.by_id = psurfs # board static bw, bh = board.rect.size bsurf = Surface([bw, bh]) for i in range(self.game.rows): for j in range(self.game.cols): x, y = j * qw, i * qh if j == self.game.min_x: bsurf.blit(qleft, (x, y)) elif j == self.game.max_x: bsurf.blit(qright, (x, y)) else: bsurf.blit(qmid, (x, y)) board.static_surf = bsurf.convert()
def draw_ground_object_info(self, ground_object: TheaterGroundObject, pos, color, surface: pygame.Surface): lb = self.font.render(str(ground_object), ANTIALIASING, color, BLACK) surface.blit(lb, (pos[0] + 18, pos[1]))
def draw(self, surface: pygame.Surface) -> None: """Draw the star on the surface.""" if self._selected: surface.blit(self._star_selected, (self._x, self._y)) else: surface.blit(self._star, (self._x, self._y))
def draw_events(self, surface: pygame.Surface, mouse_pos, mouse_down): occupied_rects = [] for cp in self.game.theater.controlpoints: point = self._transform_point(cp.position) occupied_rects.append( pygame.Rect(point[0] - 16, point[1] - 16, 32, 48)) def _location_to_rect(location: Point) -> pygame.Rect: nonlocal occupied_rects point = self._transform_point(location) rect = pygame.Rect(point[0] - 16, point[1] - 16, 32, 32) i = 0 while True: result = True for occupied_rect in occupied_rects: if rect.colliderect(occupied_rect): i += 1 if i % 2: rect.y += occupied_rect.height else: rect.x += occupied_rect.width result = False break if result: break occupied_rects.append(rect) return rect def _events_priority_key(event: Event) -> int: priority_list = [ InfantryTransportEvent, StrikeEvent, BaseAttackEvent, UnitsDeliveryEvent ] if type(event) not in priority_list: return 0 else: return priority_list.index(type(event)) + 1 events = self.game.events events.sort(key=_events_priority_key, reverse=True) label_to_draw = None for event in self.game.events: location = event.location if type(event) in [ FrontlineAttackEvent, FrontlinePatrolEvent, ConvoyStrikeEvent ]: location = self._frontline_center(event.from_cp, event.to_cp) rect = _location_to_rect(location) pygame.draw.rect( surface, EVENT_COLOR_ATTACK if event.is_player_attacking else EVENT_COLOR_DEFENSE, rect) self.surface.blit(self.event_icons[event.__class__], rect.topleft) if rect.collidepoint(*mouse_pos) or self.selected_event_info == ( event, rect.center): if not label_to_draw: label_to_draw = self.font.render(str(event), ANTIALIASING, WHITE, BLACK), rect.center if rect.collidepoint(*mouse_pos): if mouse_down[0]: self.selected_event_info = event, rect.center mouse_down[0] = False if label_to_draw: surface.blit(*label_to_draw) if self.selected_event_info: self.draw_selected_event_info() return mouse_down
def draw(self, screen: pygame.Surface): # print('drawing with visible=%s (%s)' % (self.visible, str(self._get_final_position()))) screen.blit(self._image, self._get_final_position())
def render(self, screen: pygame.Surface) -> None: screen.blit(self.img, (self.x - self.size[0] // 2, self.y - self.size[1] // 2)) for bullet in self.bullets: bullet.render(screen)
def draw_to_surface(self, surface: pygame.Surface, x_offset, y_offset): surface.blit(self.image, (self.x + x_offset, self.y + y_offset))
class ScoreBoard(ImmovableObject): ''' Informative and decorative object displaying current game score ''' image_path = 'scoreboard' size = 200, 600 def __init__(self, background_surface, pos): super(ScoreBoard, self).__init__( background_surface, pos ) self.score = None self.numbers_dest = (self.rect.x+DIGIT_OFFSET[X], self.rect.y+DIGIT_OFFSET[Y]) numbers_panel_size = self.rect.width - DIGIT_OFFSET[X], DIGIT_SIZE[Y]*2 self.numbers_rect = Rect( (DIGIT_OFFSET[X], DIGIT_OFFSET[Y]), numbers_panel_size ) self.surface_copy = Surface(numbers_panel_size, SRCALPHA, 32) self.surface_copy.blit(self.surface, ((0,0), numbers_panel_size)) self.l_number = {} self.r_number = {} def set_score(self, score): self.clear_numbers() self.score = score self.create_numbers() self.redraw() def clear_numbers(self): ''' Clear numbers from scoreboard ''' if self.l_number: self.del_number(self.l_number) self.l_number.clear() if self.r_number: self.del_number(self.r_number) self.r_number.clear() self.surface.blit(self.surface_copy, (0, 0)) def del_number(self, number): ''' Clear number by digits ''' for d in number: digit = number[d] digit.clear(self.surface) def create_numbers(self): ''' Create numbers of score and decompose on digits ''' l_num = str(self.score[0]) r_num = str(self.score[1]) l_digits_count = len(l_num) r_digits_count = len(r_num) scale = max(l_digits_count, r_digits_count) digit_width = DIGIT_SIZE[X]*(l_digits_count-1)/(l_digits_count**2+1) x = self.rect.width/2 - DIGIT_OFFSET[X] - digit_width y = self.rect.top + DIGIT_OFFSET[Y] + DIGIT_SIZE[Y] / 2 for digit in l_num: size = (DIGIT_SIZE[X]/scale, int(DIGIT_SIZE[Y]/scale)) self.l_number[digit] = Digit( self.surface, (x, y), size, digit, 'red' ) x += DIGIT_OFFSET[X]/l_digits_count digit_width = DIGIT_SIZE[X]*(r_digits_count-1)/(r_digits_count**2+2) x = self.rect.width/2 + DIGIT_OFFSET[X] - digit_width for digit in r_num: size = (DIGIT_SIZE[X] / scale, DIGIT_SIZE[Y] / scale) self.r_number[digit] = Digit( self.surface, (x, y), size, digit, 'blue' ) x += DIGIT_OFFSET[X]/r_digits_count def redraw(self): self.background_surface.blit( self.surface, self.numbers_dest, self.numbers_rect )
def draw(self, surface: pygame.Surface) -> None: """Draw the ContentItem to the Surface passed.""" surface.blit(self._image, (self._x, self._y))
def draw(self, on_surface: pygame.Surface): if self.selected: on_surface.blit(self.image_selected, self.rect) else: on_surface.blit(self.image, self.rect)
# Artillery from random import randint from pygame import Surface, image from pygame.locals import * import math landSurface = Surface((800, 600), SRCALPHA) landSurface.blit(image.load('images/landscape.png'), (0, 0)) gun1 = { "name": "Player 1", "actor": Actor('gunbody1', center=(700, 300)), "turret": Actor('gunbarrel1', center=(695, 280)), "angle": 30, "multiplier": 1, "color": (255, 0, 0) } gun2 = { "name": "Player 2", "actor": Actor('gunbody2', center=(200, 400)), "turret": Actor('gunbarrel2', center=(210, 380)), "angle": 30, "multiplier": -1, "color": (0, 0, 255) } bullet = { "active": False, "actor": Actor('bullet', center=(0, 0)), "angle": 0, "speed": 0, "count": 0 }
def blit_ui(player: Player, update_all: bool = True, update_lives: bool = False, update_score: bool = False, update_p_speed: bool = False, update_p_spread: bool = False, update_p_firerate: bool = False, update_p_count: bool = False, update_invuln: bool = False, update_level: bool = False, update_bomb: bool = False, bg: pygame.Surface = settings.wn) -> list: gap = 20 right_offset = 20 + 50 + 20 update_rects = [] # background of the settings pygame.draw.rect(bg, (55, 55, 55), (settings.RIGHT_BOUND, 0, settings.WIDTH - settings.RIGHT_BOUND, settings.HEIGHT)) pygame.draw.rect(bg, (155, 155, 155), (settings.RIGHT_BOUND + 50, 50, settings.WIDTH - settings.RIGHT_BOUND - 100, settings.HEIGHT - 100)) font = pygame.font.SysFont("Arial", 28) # Preliminary when blitting the UI for the first time if update_all: lives_text = font.render("Lives", True, (255, 255, 255)) score_text = font.render("Score", True, (255, 255, 255)) powerup_text = pygame.font.SysFont("Arial", 32).render("Powerup Levels", True, (255, 255, 255)) speed_im = pygame.transform.scale2x(powerup_ims["speed"]) firerate_im = pygame.transform.scale2x(powerup_ims["firerate"]) count_im = pygame.transform.scale2x(powerup_ims["count"]) spread_im = pygame.transform.scale2x(powerup_ims["spread"]) invuln_im = pygame.transform.scale2x(powerup_ims["invuln"]) level_text = font.render("Level", True, (255, 255, 255)) bomb_text = font.render("Bomb", True, (255, 255, 255)) bg.blit(lives_text, (settings.RIGHT_BOUND + right_offset, 20 + 50)) bg.blit(score_text, (settings.RIGHT_BOUND + right_offset, 20 + 50 + 50)) bg.blit(powerup_text, (settings.RIGHT_BOUND + right_offset, 20 + 50 + 50 + 50)) bg.blit(speed_im, (settings.RIGHT_BOUND + right_offset, 20 + 50 + 50 + 50 + 50)) bg.blit(firerate_im, (settings.RIGHT_BOUND + right_offset, 20 + 50 + 50 + 50 + 50 + 68 + 20)) bg.blit(count_im, (settings.RIGHT_BOUND + right_offset, 20 + 50 + 50 + 50 + 50 + 2 * 68 + 2 * 20)) bg.blit(spread_im, (settings.RIGHT_BOUND + right_offset, 20 + 50 + 50 + 50 + 50 + 3 * 68 + 3 * 20)) bg.blit(invuln_im, (settings.RIGHT_BOUND + right_offset, 20 + 50 + 50 + 50 + 50 + 4 * 68 + 4 * 20)) bg.blit(level_text, (settings.RIGHT_BOUND + right_offset, 20 + 50 + 50 + 50 + 50 + 5 * 68 + 5 * 20)) bg.blit(bomb_text, (settings.RIGHT_BOUND + right_offset, 20 + 50 + 50 + 50 + 50 + 50 + 5 * 68 + 5 * 20)) update_rects += [ pygame.Rect(settings.RIGHT_BOUND, 0, settings.WIDTH - settings.RIGHT_BOUND, settings.HEIGHT), pygame.Rect(settings.RIGHT_BOUND + 50, 50, settings.WIDTH - settings.RIGHT_BOUND - 100, settings.HEIGHT - 100) ] heart = powerup_ims["heart"] # Lives and hearts if update_lives or update_all: for i in range(player.health): bg.blit(heart, (settings.RIGHT_BOUND + 32 + (2 + i) * gap + right_offset, 20 + 50)) update_rects += [ pygame.Rect(settings.RIGHT_BOUND + 32 + 2 * gap + right_offset, 20 + 50, 32 + settings.LIVES * 20, 32) ] # Score if update_score or update_all: score = font.render(str(min(player.score, 999999999)), True, (255, 255, 255)) bg.blit(score, (settings.RIGHT_BOUND + right_offset + gap + font.size("Score")[0], 20 + 50 + 50)) update_rects += [ pygame.Rect( settings.RIGHT_BOUND + right_offset + gap + font.size("Score")[0], 20 + 50 + 50, font.size(str(min(player.score, 999999999)))[0], font.size(str(1234567890))[1]) ] # Level if update_level or update_all: print("upd", settings.LEVEL) level_number_text = font.render(str(settings.LEVEL), True, (255, 255, 255)) bg.blit(level_number_text, (settings.RIGHT_BOUND + right_offset + font.size("Level")[0] + gap, 20 + 50 + 50 + 50 + 50 + 5 * 68 + 5 * 20)) update_rects += [ pygame.Rect( (settings.RIGHT_BOUND + right_offset + font.size("Level")[0] + gap, 20 + 50 + 50 + 50 + 50 + 5 * 68 + 5 * 20), font.size(str(settings.LEVEL))) ] # Powerups # Subroutine to blit the levels def blit_levels(level, x, y): width = 5 rect_width = 25 for i in range(level): # outer rect pygame.draw.rect(bg, (55, 55, 55), (x + i * (rect_width - width), y + 9, rect_width, 50)) # inner rect pygame.draw.rect(bg, (0, 199, 0), (x + i * (rect_width - width) + width, y + 9 + width, rect_width - 2 * width, 50 - 2 * width)) for i in range(level, 5): # outer rect pygame.draw.rect(bg, (55, 55, 55), (x + i * (rect_width - width), y + 9, rect_width, 50)) # inner rect pygame.draw.rect(bg, (199, 199, 199), (x + i * (rect_width - width) + width, y + 9 + width, rect_width - 2 * width, 50 - 2 * width)) return [pygame.Rect(x, y, rect_width * 5, 50)] # Powerups - Speed if update_p_speed or update_all: update_rects += blit_levels( player.p_speed_count, settings.RIGHT_BOUND + right_offset + 68 + gap, 20 + 50 + 50 + 50 + 50) # Fire rate if update_p_firerate or update_all: update_rects += blit_levels( player.p_firerate_count, settings.RIGHT_BOUND + right_offset + 68 + gap, 20 + 50 + 50 + 50 + 50 + 68 + 20) # Count if update_p_count or update_all: update_rects += blit_levels( player.p_count_count, settings.RIGHT_BOUND + right_offset + 68 + gap, 20 + 50 + 50 + 50 + 50 + 2 * 68 + 2 * 20) # Spread if update_p_spread or update_all: update_rects += blit_levels( player.p_spread_count, settings.RIGHT_BOUND + right_offset + 68 + gap, 20 + 50 + 50 + 50 + 50 + 3 * 68 + 3 * 20) # Invuln if update_invuln or update_all: update_rects += blit_levels( player.invuln_count, settings.RIGHT_BOUND + right_offset + 68 + gap, 20 + 50 + 50 + 50 + 50 + 4 * 68 + 4 * 20) if update_bomb or update_all: cooldown_text = font.render( f"CD: {'Ready!' if player.bomb_timer < 0 else max(0, int(player.bomb_timer/1000))}", True, (255, 255, 255)) bg.blit(cooldown_text, (settings.RIGHT_BOUND + right_offset + font.size("Bombs")[0], 20 + 50 + 50 + 50 + 50 + 50 + 5 * 68 + 5 * 20)) update_rects += [ pygame.Rect( (settings.RIGHT_BOUND + right_offset + font.size("Bomb")[0] + gap, 20 + 50 + 50 + 50 + 50 + 50 + 5 * 68 + 5 * 20), font.size(f"Cooldown: {max(0, int(player.bomb_timer/1000))}")) ] return update_rects