class Grid: surface = None def __init__(self, width, height, spacing=20): self.width = width self.height = height self.spacing = spacing self.initializeSurface() def initializeSurface(self): self.surface = Surface((self.width, self.height), flags=HWSURFACE | SRCALPHA) self.surface.fill(Color(0, 0, 0, 0)) for i in range(0, self.width, self.spacing): pygame.draw.line(self.surface, Color(0, 0, 0, 255), (i, 0), (i, self.height)) for i in range(0, self.height, self.spacing): pygame.draw.line(self.surface, Color(0, 0, 0, 255), (0, i), (self.width, i)) pygame.draw.line(self.surface, Color(0, 0, 0, 255), (self.width - 1, 0), (self.width - 1, self.height)) pygame.draw.line(self.surface, Color(0, 0, 0, 255), (0, self.height - 1), (self.width, self.height - 1)) def render(self, screen): screen.blit(self.surface, (0, 0)) pass
def pygame_loop(surface_: surface.Surface, clock: time.Clock, update: bool = True) -> None: global num_of_iterations clock.tick(FPS) if update: num_of_iterations += 1 display.set_caption( f"Diffusion Limited Aggregation - {BETA} - {num_of_iterations}") for event in events.get(): if event.type == pygame.QUIT: at_end() keys = pygame.key.get_pressed() if keys[pygame.K_ESCAPE]: at_end() if update: p.update() surface_.fill(BLACK) render(surface_) display.flip()
class Panel(Clickable): def __init__(self, x, y, w, h, color=0x000000): self.items = [] self.clickables = [] self.surface = Surface((w, h)) self.visible = True self.x = x self.y = y self.color = color def draw(self, screen): if self.visible: self.surface.fill(self.color) for item in self.items: item.draw(self.surface) screen.blit(self.surface, (self.x, self.y)) def add(self, item): self.items.append(item) if isinstance(item, Clickable): self.clickables.append(item) def is_pressed(self, wx, wy, button): if not self.visible: return False x = wx - self.x y = wy - self.y res = False for item in self.clickables: res = res or item.is_pressed(x, y, button) return res
def tile(image_name, surface): # PYGAME CHOKE POINT if image_name not in Graphics.PRE_RENDERS: bg_image = load_resource(image_name) sx, sy = Settings.SCREEN_SIZE # pre render the tiled background sx *= 2 # to the size of a full screen sy *= 2 pr_surface = Surface((sx, sy), SRCALPHA, 32) w, h = pr_surface.get_size() img_w, img_h = bg_image.get_size() for x in range(0, w + img_w, img_w): for y in range(0, h + img_h, img_h): pr_surface.blit(bg_image, (x, y)) Graphics.PRE_RENDERS[image_name] = pr_surface full_bg = Graphics.PRE_RENDERS[ image_name] # return a subsection of the full # # pre rendered background r = surface.get_rect().clip(full_bg.get_rect()) blit_region = full_bg.subsurface(r) surface.blit(blit_region, (0, 0)) return surface
def __init__( self, parent: Player, speed: int, x: int, y: int, width: int, height: int, color: tuple[int, int, int], facing: bool, damage: int, lifespan: int, ) -> None: # region DocString """ Creates a `Attack` object ### Arguments `parent {Player}`: `summary`: the player who attacked `speed {int}`: `summary`: the speed at which the attacks move `x {int}`: `summary`: the x coordinate relative to the player `y {int}`: `summary`: the y coordinate relative to the player `width {int}`: `summary`: the width of the attack hitbox `height {int}`: `summary`: the height of the attack hitbox `color {(int, int, int)}`: `summary`: the color of the attack sprite `facing {bool}`: `summary`: true if the player is facing to the right, false otherwise `damage {int}`: `summary`: the damage dealt by the attack `lifespan {int}`: `summary`: for how much the attack can exist without hitting another player """ # endregion super(Attack, self).__init__() # region Sprite variables self.image = Surface((width, height)) self.image.fill(color) self.rect = self.image.get_rect() self.rect.move_ip( parent.rect.right if facing else (parent.rect.x - width), parent.rect.y) self.rect.move_ip(x, y) # endregion self.parent = parent self.speed = speed self.damage = damage self.lifespan = lifespan self.current_life_frame = 0
def makeMap(tiles, tileSz): R, C = tiles.shape surf = Surface((int(R * tileSz), int(C * tileSz))) for r in range(R): for c in range(C): surf.blit(tiles[r, c], (int(r * tileSz), int(c * tileSz))) return surf
def build(self, disp): self.surface = Surface((WIDTH, HEIGHT), HWSURFACE) draw.rect(self.surface, WHITE, Rect(0, 0, WIDTH - WALLWIDTH, HEIGHT - WALLWIDTH), WALLWIDTH) for wall in self.cells_draw: draw.line(self.surface, WHITE, wall[0], wall[1], WALLWIDTH) # if cell.matrix_index == (0, 0): # self.surface.fill( # RED, # Rect( # cell.pos[0]+int(CELLSIZE*0.1), # cell.pos[1]+int(CELLSIZE*0.1), # int(CELLSIZE*0.8), # int(CELLSIZE*0.8) # ) # ) # elif cell.matrix_index == (WIDTH/CELLSIZE-1, HEIGHT/CELLSIZE-1): # self.surface.fill( # BLUE, # Rect( # cell.pos[0]+int(CELLSIZE*0.1), # cell.pos[1]+int(CELLSIZE*0.1), # int(CELLSIZE*0.8), # int(CELLSIZE*0.8) # ) # ) self.surface.convert(disp)
def __init__(self, size, game): Surface.__init__(self, size) self.width, self.height = size self.game = game self._load_images() self.font = pygame.font.SysFont("Comic Sans MS", int(0.09 * self.width)) self.hsfont = pygame.font.SysFont("Comic Sans MS", int(0.09 * self.width))
def _prepare_buttons(self): """ Prepares the buttons. This method pre-renders the plus and minus buttons. """ # draw plus button self._plus_button = Surface((self._font_height, self._font_height), pygame.SRCALPHA, 32) self._plus_button.convert_alpha() pygame.draw.rect(self._plus_button, SettingsScreen.COLOR, Rect(0, self._font_height/3, self._font_height, self._font_height/3)) pygame.draw.rect(self._plus_button, SettingsScreen.COLOR, Rect(self._font_height/3, 0, self._font_height/3, self._font_height)) # draw minus button self._minus_button = Surface((self._font_height, self._font_height), pygame.SRCALPHA, 32) self._minus_button.convert_alpha() pygame.draw.rect(self._minus_button, SettingsScreen.COLOR, Rect(0, self._font_height/3, self._font_height, self._font_height/3)) # draw unchecked bool button self._unchecked_bool = Surface((self._font_height, self._font_height), pygame.SRCALPHA, 32) self._unchecked_bool.convert_alpha() pygame.draw.rect(self._unchecked_bool, SettingsScreen.COLOR, Rect(0, 0, self._font_height, self._font_height), 3) # draw checked bool button self._checked_bool = Surface((self._font_height, self._font_height), pygame.SRCALPHA, 32) self._checked_bool.convert_alpha() pygame.draw.rect(self._checked_bool, SettingsScreen.COLOR, Rect(0, 0, self._font_height, self._font_height), 3) pygame.draw.line(self._checked_bool, SettingsScreen.COLOR, (0, 0), (self._font_height, self._font_height), 3) pygame.draw.line(self._checked_bool, SettingsScreen.COLOR, (0, self._font_height), (self._font_height, 0), 3)
def prepare_paragraph(text, width, size="normal", colour=(0,0,0)): font = FONTS[size] lines = [] words = text.split() if words: lastline = None line = words[0] for i in range(1,len(words)): lastline = line line = line+" "+words[i] w,h = font.size(line) if w > width: lines.append(lastline) line = words[i] else: line = "" lines.append(line) parawidth = max(font.size(each)[0] for each in lines) lineheight = font.get_height() paraheight = lineheight*len(lines) paragraph = Surface((parawidth,paraheight),pygame.SRCALPHA) paragraph.fill((255,255,255,0)) for y,line in enumerate(lines): text = prepare(line,size,colour) paragraph.blit(text,(0,y*lineheight)) return paragraph
def _createSurfaceImage(self, surfaceHeight): """ Make the ground surface image. IDEA: Try changing the color of the ground, or maybe even add a texture to it. """ LunarSurface.image = pygame.Surface([screen_width_pixels, surfaceHeight + self._groundElevation], pygame.SRCALPHA, 32).convert_alpha() initialY = y = Surface.get_height(LunarSurface.image) - self._pointsY[0] + self._drop_amount - self._groundElevation polyCoords = [(0, y)] for i in range(1, len(self._pointsX)): y -= self._pointsY[i] polyCoords.append((self._pointsX[i], y)) surfaceCoords = list(polyCoords) polyCoords.append([screen_width_pixels, Surface.get_height(LunarSurface.image)]) polyCoords.append([0, Surface.get_height(LunarSurface.image)]) polyCoords.append([0, initialY]) pygame.draw.polygon(LunarSurface.image, (64, 64, 64), polyCoords, 0) for i in range(0, len(surfaceCoords) - 1): if self._flatCoordinates.count(i) or self._flatEasyCoordinates.count(i): color = 0, 255, 255 width = 2 else: color = 128, 128, 128 width = 1 pygame.draw.line(LunarSurface.image, color, surfaceCoords[i], surfaceCoords[i + 1], width) self._plotlandingScores(surfaceCoords)
def prepare_table(rows, alignment="lr", size="normal", colour=(0,0,0), padding=0): f = FONTS[size] numcolumns = len(rows[0]) numrows = len(rows) def u(n): return n if isinstance(n, unicode) else unicode(n) shapes = [[f.size(u(col)) for col in row] for row in rows] maxheight = max(max(shape[1] for shape in shaperow) for shaperow in shapes) widths = [max(shaperow[i][0] for shaperow in shapes) for i in range(numcolumns)] table = Surface((sum(widths) + padding * (numcolumns - 1), maxheight * numrows + padding * (numrows - 1)), pygame.SRCALPHA) table.fill((255,255,255,0)) y = 0 for r, row in enumerate(rows): x = 0 for c, col in enumerate(row): w, h = shapes[r][c] text = prepare(u(col), size=size, colour=colour) align = alignment[c] if align == "r": adjustx = widths[c] - w elif align == "c": adjustx = (widths[c] - w) // 2 else: adjustx = 0 table.blit(text, (x + adjustx, y)) x += widths[c] + padding y += maxheight + padding return table
class GameUI: def __init__(self, mainchar): self.bg = Surface((600, 1600)) self.statusbar = Surface((200, 600)) self.mainchar = mainchar self.widget = [] self.create_bg() def create_bg(self): rbg = self.bg.get_rect() bgimg = media.load_image('bg.png').convert() rbgimg = bgimg.get_rect() columns = int(rbg.width / rbgimg.width) + 1 rows = int(rbg.height / rbgimg.height) + 1 for y in xrange(rows): for x in xrange(columns): if x == 0 and y > 0: rbgimg = rbgimg.move([-(columns -1 ) * rbgimg.width, rbgimg.height]) if x > 0: rbgimg = rbgimg.move([rbgimg.width, 0]) self.bg.blit(bgimg, rbgimg) def update(self): r = pygame.rect.Rect(0, 0, 200, 100) for w in self.widget: w.update() self.statusbar.blit(w.image, r) r = r.move((0, 100))
def __init__(self, width, height, runnable_stack, x=0, y=0): self.controls = [] self.x = x self.y = y self.surface = Surface((width, height)) self.runnable_stack = runnable_stack self.events = []
def __init__(self, initialFuel): self._pandaFrame = [] self._pandaFrame.append(pygame.image.load("Resources/panda0.png").convert_alpha()) self._pandaFrame.append(pygame.image.load("Resources/panda1.png").convert_alpha()) self._pandaFrame.append(pygame.image.load("Resources/panda2.png").convert_alpha()) self._pandaFrame.append(pygame.image.load("Resources/pandaLand0.png").convert_alpha()) self._pandaFrame.append(pygame.image.load("Resources/pandaLand1.png").convert_alpha()) self._pandaFrame.append(pygame.image.load("Resources/pandaLand2.png").convert_alpha()) self.pandaHeight = Surface.get_height(self._pandaFrame[0]) * self._imageResample self.pandaWidth = Surface.get_width(self._pandaFrame[0]) * self._imageResample self.altitude = screen_height_pixels - self.pandaHeight * 2 self._landingStickLength = max(self.pandaHeight, self.pandaWidth) self.x = 50 self.angle = 0 self.angleDelta = 0 self.velocityX = 0.1 self.velocityY = 0 self.thrusting = False self.image = pygame.transform.rotozoom(self._pandaFrame[0], 0, self._imageResample) self.rotate(45) self.thrustSound = pygame.mixer.Sound('Resources/thrust.ogg') self.thrustSound.set_volume(0.25) self.fuel = initialFuel pygame.sprite.Sprite.__init__(self) self.rect = Rect(self.x, 0, self.pandaWidth, self.pandaWidth) self.maxHeight = math.sqrt(self.pandaHeight * self.pandaHeight + self.pandaWidth * self.pandaWidth) self.rotationsPerSec = 0.2 self.recalculateRect()
def __init__(self, evManager, numlines=3, rect=(0, 0, 100, 20), txtcolor=(255, 0, 0), bgcolor=None): Widget.__init__(self, evManager) # When receiving an event containing text, # add or remove that text to the widget's set of text lines to display. # addevents_attrs maps event classes to the text attr of events # that add text to display. self.addevents_attrs = {MdAddPlayerEvt: "pname", MNameChangedEvt: "newname", MMyNameChangedEvent: "newname"} for evtClass in self.addevents_attrs: self._em.reg_cb(evtClass, self.on_addtextevent) # rmevents_attrs maps event classes to the text attributes of events # that remove text to display. self.rmevents_attrs = {MPlayerLeftEvt: "pname", MNameChangedEvt: "oldname", MMyNameChangedEvent: "oldname"} for evtClass in self.rmevents_attrs: self._em.reg_cb(evtClass, self.on_rmtextevent) self.texts = [] # Each text is a player name. # gfx self.font = Font(None, config_get_fontsize()) self.rect = rect self.txtcolor = txtcolor self.bgcolor = bgcolor img = Surface(rect.size) if bgcolor: img.fill(bgcolor) else: img.set_alpha(0, RLEACCEL) # fully transparent self.image = img self.maxnumlines = numlines self.linewidgets = deque(maxlen=numlines) # deque of TextLabelWidgets
def update(self, duration): """ update all the contained linewidgets TODO: check that it works with transparent bg """ if self.dirty == 0: return # make the box size = self.rect.size bgcol = self.bgcolor if bgcol: # only display a bg img if bgcolor specified img = Surface(size) img.fill(bgcol) img = img.convert() else: # more or less transparent img = Surface(size, SRCALPHA) # handles transparency transparency = 50 # 0 = transparent, 255 = opaque img.fill((0, 0, 0, transparency)) img = img.convert_alpha() # blit each line numelemts = min(len(self.texts), self.maxnumlines) for i in range(numelemts): wid = self.linewidgets[i] wid.set_text(self.texts[-i - 1]) wid.update(duration) img.blit(wid.image, wid.rect) self.image = img
class Star(pygame.sprite.Sprite, Drawable): height = 1 width = 1 move_step = 2 def __init__(self, direction: Directon = Directon.DOWN): super().__init__() self.direction = direction self.rect = Rect(random.randint(0, SCREEN_WITH), random.randint(0, SCREEN_HEIGHT), self.width, self.height) self.image = Surface((self.width, self.height)) self.image.fill(WHITE) def handle(self, event: pygame.event.Event): pass def draw(self, surface: pygame.Surface): pygame.draw.rect(surface, WHITE, self.rect) def update(self, *args, **kwargs): self.rect.move_ip(0, self.move_step) if self.rect.y < 0 or self.rect.y > SCREEN_HEIGHT: self.rect.y = 0 self.rect.x = random.randint(0, SCREEN_WITH)
def __init__(self, color, pos): Sprite.__init__(self) self.rect = Rect(*pos, CELLS_SIZE, CELLS_SIZE) self.image = Surface((self.rect.width, self.rect.height)) self.image.fill(color) self.state = 'normal' self.color = color
def __init__(self, game_env): Text.__init__(self, game_env, size=20) self.__game_env = game_env seperator = self.font.render(' ', 1, self.color) header = self.font.render('=== HELP ===', 1, self.color) footer = self.font.render('=== GOOD LUCK ===', 1, self.color) all_surfaces = [] all_surfaces.append(seperator) all_surfaces.append(self.font.render('Your objective should you choose to accept is to navigate your jet without getting hit by', 1, self.color)) all_surfaces.append(self.font.render('the incoming missiles. For self-defence you can shoot down the enemy missiles. You are', 1, self.color)) all_surfaces.append(self.font.render('armed with 100 special missiles. Level-up awards you another 50 special missiles and a', 1, self.color)) all_surfaces.append(self.font.render('power-up star which will instantly deactivate all the enemy missiles.', 1, self.color)) all_surfaces.append(self.font.render('Your jet can carry maximum 999 special missiles.', 1, self.color)) all_surfaces.append(seperator) all_surfaces.append(self.font.render('With keyboard input, you should use your keyboard arrow keys to navigate and spacebar', 1, self.color)) all_surfaces.append(self.font.render('to shoot. With mouse as input, you should use your mouse to navigate your jet and', 1, self.color)) all_surfaces.append(self.font.render('mouse click to shoot', 1, self.color)) all_surfaces.append(self.font.render(' ', 1, self.color)) all_surfaces.append(self.font.render('POINTS: Destroy Missle -> 10 pts. Power-up Star -> 100 pts. Level-up -> 10 pts.', 1, self.color)) all_surfaces.append(seperator) self.surf = Surface((all_surfaces[1].get_width(), all_surfaces[0].get_height() * (len(all_surfaces) + 2)), self.__game_env.SRCALPHA) self.surf.blit(header, (self.surf.get_width()/2 - header.get_width()/2, 0)) for index, temp_surf in enumerate(all_surfaces): self.surf.blit(temp_surf, (0, header.get_height() + index * temp_surf.get_height())) self.surf.blit(footer, (self.surf.get_width()/2 - footer.get_width()/2, self.surf.get_height() - footer.get_height())) self.rect = self.surf.get_rect(center=(self.__game_env.static.screen_width/2, self.__game_env.static.screen_height/2))
class Bullet(pygame.sprite.Sprite, Drawable, EventHandler): height = 5 width = 5 def __init__(self, x, y, direction: Directon = Directon.UP, velocity=5): super().__init__() self.velocity = velocity self.direction = direction self.rect = Rect(int(x - self.width / 2), y - self.height, self.width, self.height) self.image = Surface((self.width, self.height)) self.image.fill(WHITE) def handle(self, event: pygame.event.Event): pass def draw(self, surface: pygame.Surface): pygame.draw.rect(surface, WHITE, self.rect) def update(self, *args, **kwargs): # noinspection PyTypeChecker self.rect.move_ip(0, self.velocity * self.direction.value) if self.rect.y < 0 or self.rect.y > SCREEN_HEIGHT: self.kill()
def __init__(self, x, y): Sprite.__init__(self) self.image = Surface((73, 211)) self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y self.image.set_colorkey(Color(BACKGROUND_COLOR)) self.is_Give = False self.is_Has = False self.is_Fall = False def make_boltAnim(anim_list, delay): boltAnim = [] for anim in anim_list: boltAnim.append((anim, delay)) Anim = pyganim.PygAnimation(boltAnim) return Anim self.boltAnimStay = make_boltAnim(ANIMATION_STAY, ANIMATION_DELAY) self.boltAnimStay.play() self.boltAnimCall = make_boltAnim(ANIMATION_CALL, ANIMATION_DELAY * 3) self.boltAnimCall.play() self.boltAnimJump = make_boltAnim(ANIMATION_JUMP, ANIMATION_DELAY * 3) self.boltAnimJump.play()
def _createSurfaceImage(self, surfaceHeight): """ Make the ground surface image. IDEA: Try changing the color of the ground, or maybe even add a texture to it. """ LunarSurface.image = pygame.Surface( [screen_width_pixels, surfaceHeight + self._groundElevation], pygame.SRCALPHA, 32 ).convert_alpha() initialY = y = ( Surface.get_height(LunarSurface.image) - self._pointsY[0] + self._drop_amount - self._groundElevation ) polyCoords = [(0, y)] for i in range(1, len(self._pointsX)): y -= self._pointsY[i] polyCoords.append((self._pointsX[i], y)) surfaceCoords = list(polyCoords) polyCoords.append([screen_width_pixels, Surface.get_height(LunarSurface.image)]) polyCoords.append([0, Surface.get_height(LunarSurface.image)]) polyCoords.append([0, initialY]) pygame.draw.polygon(LunarSurface.image, (64, 64, 64, 128), polyCoords, 0) for i in range(0, len(surfaceCoords) - 1): if self._flatCoordinates.count(i) or self._flatEasyCoordinates.count(i): # NAM change color: color = 0, 255, 255 color = 255, 0, 0 width = 3 else: color = 128, 128, 128 width = 1 pygame.draw.line(LunarSurface.image, color, surfaceCoords[i], surfaceCoords[i + 1], width) self._plotlandingScores(surfaceCoords)
def __init__(self, initialFuel): self._tardisFrame = [] self._tardisFrame.append(pygame.image.load("Resources/tardis0.png").convert_alpha()) self._tardisFrame.append(pygame.image.load("Resources/tardis1.png").convert_alpha()) self._tardisFrame.append(pygame.image.load("Resources/tardis2.png").convert_alpha()) self._tardisFrame.append(pygame.image.load("Resources/tardisLand0.png").convert_alpha()) self._tardisFrame.append(pygame.image.load("Resources/tardisLand1.png").convert_alpha()) self._tardisFrame.append(pygame.image.load("Resources/tardisLand2.png").convert_alpha()) self.tardisHeight = Surface.get_height(self._tardisFrame[0]) * self._imageResample self.tardisWidth = Surface.get_width(self._tardisFrame[0]) * self._imageResample self.altitude = screen_height_pixels - self.tardisHeight * 1 # NAM: Adjust start height self._landingStickLength = max(self.tardisHeight, self.tardisWidth) self.x = 50 self.angle = 0 self.angleDelta = 0 self.velocityX = 0.1 self.velocityY = 0 self.thrusting = False self.image = pygame.transform.rotozoom(self._tardisFrame[0], 0, self._imageResample) self.rotate(45) self.thrustSound = pygame.mixer.Sound("Resources/tardisthrust.ogg") self.thrustSound.set_volume(0.5) self.fuel = initialFuel pygame.sprite.Sprite.__init__(self) self.rect = Rect(self.x, 0, self.tardisWidth, self.tardisWidth) self.maxHeight = math.sqrt(self.tardisHeight * self.tardisHeight + self.tardisWidth * self.tardisWidth) self.rotationsPerSec = 0.2 self.recalculateRect()
class menu(object): def __init__(self, rect, width): self.surface = Surface((width, rect.height)) self.surface.fill((100,100,250)) self.buttonDict = dict() self.addButton(10, 10, 40, 40, "House") self.updateAll() def addButton(self, x, y, width, height, text): self.buttonDict[(x, y, width, height)] = (button.button(width, height, text)) def getButton(self, x, y): for myRect in self.buttonDict.keys(): if Rect(myRect[0], myRect[1], myRect[2], myRect[3]).collidepoint(x, y): return self.buttonDict[(myRect[0], myRect[1], myRect[2], myRect[3])].text return None def updateAll(self): for myRect, button in self.buttonDict.items(): self.surface.blit(button.surface, (myRect[0], myRect[1])) def getSurface(self): return self.surface
def update(self, duration): """ update all the contained linewidgets. Return right away if no text has changed. """ if self.dirty == 0: # no new text has been added return # make the box size = self.rect.size bgcolor = self.bgcolor if bgcolor: # completely opaque bg img = Surface(size) img.fill(self.bgcolor) img = img.convert() else: # more or less transparent img = Surface(size, SRCALPHA) # handles transparency transparency = 50 # 0 = transparent, 255 = opaque img.fill((0, 0, 0, transparency)) # black img = img.convert_alpha() # blit each line for wid in self.linewidgets: wid.update(duration) img.blit(wid.image, wid.rect) self.image = img self.dirty = 0
def __init__(self, side, speed, engine: ControlEngine): super().__init__() self.speed = speed self.engine = engine self.engine.bind_pad(self) self.top_region_pct = 10 self.middle_region_pct = 15 self.width = 25 self.height = 75 self.dy = 0 self.image = Surface((self.width, self.height)) self.image.fill(white) self.rect = self.image.get_rect() if side == 'left': self.margin = 25 else: self.margin = 775 - self.width self.rect.y = 300 self.rect.x = self.margin self.borders = None
def __init__(self, location): sprite.Sprite.__init__(self) self.image = Surface((20, 20)) self.image = image.load(location) self.rect = self.image.get_rect() self._x = None self._y = None
def __init__(self, title, name, x, y, width, height, button_color, font_color, func, background_image=None): self.title = title self.name = name self.id = ControlButton.button_id ControlButton.button_id += 1 self.x = x self.y = y self.abs_x = x self.abs_y = y self.width = width self.height = height self.func = func self.button_color = button_color self.font_color = font_color self.__selected_color = color.white self.background_image = background_image if background_image: img_surf = pygame.image.load(background_image) self.surface = pygame.transform.scale(img_surf, (width, height)) else: self.surface = Surface((self.width, self.height)) self.draw()
def draw(self, surface: Surface, dest_rect: Rect, critter_location: Union[Rect, None]): """ Render a window into the maze into the main surface while making sure the critter at critter_location is visible :param surface: Main window's surface :param dest_rect: The rectangle of where in the window's that the viewable maze section is rendered into :param critter_location: Rectangle of critter to scroll maze around """ rect = self.rect.copy() if critter_location is not None: if RIGHT_SCROLL_LIM > critter_location.left > LEFT_SCROLL_LIM: rect.left = critter_location.left - LEFT_SCROLL_LIM elif critter_location.left < MID_PLAY_WIDTH: rect.left = 0 else: rect.left = RIGHT_SCROLL_LIM - MID_PLAY_WIDTH if BOT_SCROLL_LIM > critter_location.top > TOP_SCROLL_LIM: rect.top = critter_location.top - TOP_SCROLL_LIM elif critter_location.top < MID_PLAY_HEIGHT: rect.top = 0 else: rect.top = BOT_SCROLL_LIM - MID_PLAY_HEIGHT surface.blit(self.surface, dest_rect, rect)
class Wall(Platform): def __init__(self, surf, area, coords, height): super().__init__(surf, coords, 50, height) self.sprite = Surface((50, height)) for i in range(0, height // 50): img = 'imgs/' + area + '-wall-right-' + str(randint(1, 3)) + '.png' self.sprite.blit(pg.image.load(img), (0, i * 50))
def create_turn_marker(board, parent_rect, group): MARKER_OFFSET = 20 MARKER_WIDTH = 5 current_turn = board.current_board.current_turn if current_turn % 2 == 0: marker_size = (parent_rect.width - MARKER_OFFSET, MARKER_WIDTH) else: marker_size = (MARKER_WIDTH, parent_rect.width - MARKER_OFFSET) marker_size_half = (marker_size[0] / 2, marker_size[1] / 2) parent_half_width = parent_rect.width / 2 parent_half_height = parent_rect.height / 2 SEAT_OFFSETS = [ (0, parent_half_height - marker_size_half[1]), (parent_half_width - marker_size_half[0], 0), (0, -parent_half_height + marker_size_half[1]), (-parent_half_width + marker_size_half[0], 0), ] turn_marker_surface = Surface(marker_size) turn_marker_surface.fill((255, 255, 255)) sprite = Sprite() sprite.rect = turn_marker_surface.get_rect() sprite.image = turn_marker_surface sprite.rect.center = parent_rect.center sprite.rect.x += SEAT_OFFSETS[current_turn][0] sprite.rect.y += SEAT_OFFSETS[current_turn][1] sprite.layer = 2 group.add(sprite)
class Ground(Platform): def __init__(self, surf, area, coords, width): super().__init__(surf, coords, width, 50) self.sprite = Surface((width, 50)) for i in range(0, width // 50): img = 'imgs/' + area + '-ground-' + str(randint(1, 3)) + '.png' self.sprite.blit(pg.image.load(img), (i * 50, 0))
def __init__(self, size, images): Surface.__init__(self, images[0].get_size(), pygame.SRCALPHA) self.location = (0, 34) self.blit(images[0], (0, 0)) self.xChange = 100 self.rotationX = 45 self.rotationY = 33 self.surfaces = [ CubeSide(images[x], images[0].get_size(), x) for x in range(6) ] self.surfaces[0].blit(images[0], (0, 0)) self.surfaces[1].blit(images[1], (0, 0)) self.ORIGINAL_SURFACES = [ pygame.Surface((100, 100), pygame.SRCALPHA) for _ in range(6) ] self.ORIGINAL_SURFACES[0].blit(images[0], (0, 0)) self.testingSurf = Transform.skew_surface( pygame.transform.scale(self.surfaces[0], (self.xChange, 100)), 0, 33) self.testingSurf2 = Transform.skew_surface( pygame.transform.scale(self.surfaces[4], (self.xChange, 100)), 0, -33)
def __init__(self, background_color, font: Font, keyboard_manager: KeyboardManager, state_manager: StateManager, root_object_manager: RootObjectManager, handler_manager: HandlerManager, shutdown): self.background_color = background_color self.font: Font = font self.keyboard_manager: KeyboardManager = keyboard_manager self.state_manager: StateManager = state_manager self.root_object_manager = root_object_manager self.handler_manager = handler_manager self.shutdown = shutdown self.line = '' self.surface = Surface([0, 0]) self.surface_background_width = 0 self.x = 0 self.y = 100 self.backspace_pressed_time = 0 self.backspace_sleep_duration = 0.5 self.backspace_repress_cycle = 0.05 self.backspace_cycle_elapsed = 0 self.last_loop_time = 0
def _getTexture(self, textureName): """ Return a texture surface from the texture name. """ surface = Surface(TEXTURE_SIZE) self.divisor = 32 for v in range(0, TEXTURE_SIZE[0]): for h in range(0, TEXTURE_SIZE[1]): x = float(h) / self.divisor y = float(v) / self.divisor # Render the correct Texture if (textureName == 'clouds'): colorPoint = self._renderClouds(x, y) elif (textureName == 'marble'): colorPoint = self._randerMarble(x, y) elif (textureName == 'spruce'): colorPoint = self._randerSpruce(x, y) elif (textureName == 'radiation'): colorPoint = self._renderRadiation(x, y) elif (textureName == 'stucco'): colorPoint = self._renderStucco(x, y) elif (textureName == 'water'): colorPoint = self._renderCrappyWater(x, y) elif (textureName == 'leaves'): colorPoint = self._renderLeaves(x, y) else: raise Exception("Unknown texture: %s" % textureName) # Paint the Canvas surface.set_at((h, v), colorPoint) return surface
def draw_snake(self, head_img, color, screen: Surface, blocksize: int): for part in self.body[:-1]: pygame.draw.rect(screen, color, \ [part.x * blocksize, part.y * blocksize,\ blocksize - 1, blocksize - 1]) screen.blit(head_img, (self.head.x * blocksize, self.head.y * blocksize))
def prepare_map(self): map_surface = Surface(self.map_rect.size) # print(self.resource_manager.maps) tile_map = self.resource_manager.maps[self.level_name] tile_size = self.textures["tile0"].get_rect().w tile_list = [] for row_idx, row in enumerate(tile_map): for column_idx, tile in enumerate(row): tile_rect = self.textures["tile" + str(tile)].get_rect().copy() tile_rect.topleft = (column_idx * tile_size, row_idx * tile_size) map_surface.blit(self.textures["tile" + str(tile)], tile_rect) if tile in [2]: tile_list.append([tile_rect, True]) elif tile == 1: spawn_point = tile_rect.topleft spawn_tile = (column_idx, row_idx) elif tile == 4: end_tile = (column_idx, row_idx) paths = self.prepare_paths(tile_map, spawn_tile, end_tile) return map_surface, tile_list, paths, spawn_point
class WelcomeScreen(object): def __init__(self, mouse): self.mouse = mouse self.surface_size = (CONFIG['screen']['width']/2, CONFIG['screen']['height']/2) self.surface = Surface(self.surface_size) def draw(self, screen): text_box = TextBox(self.surface, align="center") self.surface.fill((0,175,75)) text_box.text_color = (32, 32, 32) text_box.background_color = ((0, 175, 75)) text_box.font_size = 35 text_box.draw_new_line("Welcome to the", margin_top=-20) text_box.draw_new_line("City Manager Game!") text_box.font_size = 25 text_box.draw_new_line("Here you can create new buildings, roads", margin_top=20) text_box.draw_new_line("and earn money from the things you have built.") text_box.draw_new_line(f"Every {CONFIG['income_period']/1000} seconds you will earn money", margin_top=5) text_box.draw_new_line("from your belongings.") text_box.draw_new_line("You can build new things using the ") text_box.draw_new_line("money you have as well.") text_box.draw_new_line("Have fun!") text_box.draw_new_line("Press enter to continue", margin_top=10) screen.blit(self.surface, (self.surface_size[0]/2, self.surface_size[1]/2))
def __init__( self, evManager, text, rect=None, onDownClickEvent=None, onUpClickEvent=None, onMouseMoveOutEvent=None ): Widget.__init__(self, evManager) # Widget init sets dirty to true, hence the actual text rendering # will be done in ButtonWidget.update(), called by the view renderer. self._em.reg_cb(DownClickEvent, self.on_downclick) self._em.reg_cb(UpClickEvent, self.on_upclick) self._em.reg_cb(MoveMouseEvent, self.on_mousemove) # the events to be triggered when the button is clicked or mouse moved self.onDownClickEvent = onDownClickEvent self.onUpClickEvent = onUpClickEvent self.onMouseMoveOutEvent = onMouseMoveOutEvent self.text = text self.font = Font(None, config_get_fontsize()) # default font, 40 pixels high if rect: self.rect = rect self.image = Surface(self.rect.size) # container size from specified rect # if txtimg does not fit in rect, it'll get cut (good thing) else: txtimg = self.font.render(self.text, True, (0, 0, 0)) self.rect = txtimg.get_rect() self.image = Surface(self.rect.size) # container size from rendered text
def get_surface(room): surface = Surface((800, 600)) room["scrap"] = [] for wall in room["walls"]: pygame.draw.polygon(surface, dark_green, wall) if "ellipses" in room: for ellipse in room["ellipses"]: transparent_beige = (beige[0], beige[1], beige[2], 0) pygame.draw.ellipse(surface, transparent_beige, ellipse) for scrap_center in room["scrap_pile_coords"]: if scrap_center[2] is not None and scrap_center[2] == 1: scrap = pygame.image.load(f"resources/mutter/mutter_{scrap_i}.png") else: scrap = pygame.image.load(f"resources/screw/screw_{scrap_i}.png") scrap.set_colorkey(beige) scrap_rect = scrap.get_rect() scrap_rect.center = (scrap_center[0], scrap_center[1]) room["scrap"].append(scrap_rect) surface.blit(scrap, scrap_rect) return surface
def draw(self): """Draw battle field time. Returns: Surface: Drawn surface """ surface = Surface((self._width, self._height)) _minute, _second = divmod(math.ceil(self._jhclient.bf.time), 60) text = f"{_minute:02d}:{_second:02d}" # change text color by remaining time if _minute >= 1 and _second > 0: text = self.font.render(text, True, config.COLORS["white"]) elif _second > 30: text = self.font.render(text, True, config.COLORS["blue"]) elif _second > 10: text = self.font.render(text, True, config.COLORS["orange"]) else: text = self.font.render(text, True, config.COLORS["red"]) self.text_width, self.text_height = text.get_rect()[2:] _left = (self._width - self.text_width) // 2 _top = (self._height - self.text_height) // 2 surface.blit(text, (_left, _top)) return surface
def order_reversed_spritesheet(self, flipped_sheet): """Reorganize the frames in a flipped sprite sheet so that they are in the same order as the original sheet. Args: flipped_sheet: A PyGame Surface containing a flipped sprite sheet. Returns: A PyGame Surface containing the sprite sheet with each frame flipped and in the correct order. """ ordered_sheet = Surface((self.spritesheet.get_width(), self.spritesheet.get_height()), SRCALPHA) ordered_sheet.convert_alpha() for frame_index in xrange(0, self.get_num_of_frames()): frame_x = self.get_width() * frame_index old_frame_index = self.get_num_of_frames() - 1 - frame_index old_region = self.get_frame_region(old_frame_index) ordered_sheet.blit(flipped_sheet, (frame_x, 0), old_region) return ordered_sheet
def draw_status(self, surface: Surface): text = Fonts.shields.render( str(self.current_hull) + '/' + str(self.max_hull), True, (255, 255, 255)) text2 = Fonts.shields.render(str(self.command), True, (0, 255, 0)) surface.blit(text, (0, 30)) surface.blit(text2, (0, 10))
def refresh_loc(self, field_size): """ updates coordinates on teh table surface :param field_size: float; size of a virtual field that is determined by the size of the window that inhabits the GUI """ # gets surface with fitting size if self.title == "Remaining Ships": self.location = [field_size * 25, field_size * 5 ] # updates location on the game window column_width = 3 else: self.location = [field_size * 10, field_size * 5.5] column_width = 3.75 self.surf = Surface((self.fake_size[0] * 4 * field_size, self.fake_size[1] * 3 * field_size)) self.writing.font = SysFont(None, int(field_size * 3 / 2)) # resizes title's font # calculates title's center self.writing.top_left_corner = [ field_size * self.columns.__len__() * column_width / 2, field_size * 3 / 4 ] for column in self.columns: # goes through every column column.refresh_loc(field_size) # updates its locations
def __init__(self, image, movement_speed): Surface.__init__(self, image.get_size()) self.image = image self.blit(self.image, (0, 0)) self.movement_speed = movement_speed
def render(self, text, antialias, color, background=None): """Font.render(text, antialias, color, background=None): return Surface draw text on a new Surface""" color = Color(color) fg = ffi.new("SDL_Color [1]") bg = ffi.new("SDL_Color [1]") fg[0].r = color.r fg[0].g = color.g fg[0].b = color.b if background: try: background = Color(background) bg[0].r = background.r bg[0].g = background.g bg[0].b = background.b except (TypeError, ValueError): # Same error behaviour as pygame bg[0].r = 0 bg[0].g = 0 bg[0].b = 0 else: bg[0].r = 0 bg[0].g = 0 bg[0].b = 0 if text is None or text == "": # Just return a surface of width 1 x font height height = sdl.TTF_FontHeight(self._sdl_font) surf = Surface((1, height)) if background and isinstance(background, Color): surf.fill(background) else: # clear the colorkey surf.set_colorkey(flags=sdl.SDL_SRCCOLORKEY) return surf if not isinstance(text, basestring): raise TypeError("text must be a string or unicode") if "\x00" in text: raise ValueError("A null character was found in the text") if isinstance(text, unicode): text = text.encode("utf-8", "replace") if utf_8_needs_UCS_4(text): raise UnicodeError("A Unicode character above '\\uFFFF' was found;" " not supported") if antialias: if background is None: sdl_surf = sdl.TTF_RenderUTF8_Blended(self._sdl_font, text, fg[0]) else: sdl_surf = sdl.TTF_RenderUTF8_Shaded(self._sdl_font, text, fg[0], bg[0]) else: sdl_surf = sdl.TTF_RenderUTF8_Solid(self._sdl_font, text, fg[0]) if not sdl_surf: raise SDLError(ffi.string(sdl.TTF_GetError())) surf = Surface._from_sdl_surface(sdl_surf) if not antialias and background is not None: surf.set_colorkey() surf.set_palette([(bg[0].r, bg[0].g, bg[0].b)]) return surf
class LoadingScene(AbstractScene): """ @type image: SurfaceType @type rect: pygame.rect.RectType """ image = None rect = None def __init__(self, manager): """ @type manager: slg.application.manager.Manager """ super().__init__(manager) self.group = GameSceneGroup(self) image = pygame.image.load(os.path.join(GUI_DIR, 'loading_screen.jpg')) self.image = Surface(self._manager.get_display().get_size()) self.rect = pygame.rect.Rect(self.image.get_rect()) image_size = image.get_size() surface_size = self.image.get_size() x = int((image_size[0] - surface_size[0]) / 2) y = int((image_size[1] - surface_size[1]) / 2) if x < 0 and y < 0: image = pygame.transform.scale(image, surface_size) x, y = 0, 0 elif x <= 0 <= y: image = pygame.transform.scale(image, (surface_size[0], image_size[1])) x = 0 elif y <= 0 <= x: image = pygame.transform.scale(image, (image_size[0], surface_size[1])) y = 0 styles = {'font': 'alger', 'font_size': 40, 'align': [TextWidget.CENTER, TextWidget.CENTER]} text = TextWidget(**styles) text.set_text("""Loading... Please wait""") self.image.blit(image, (-x, -y)) text.draw(self.image) def handle_events(self, events): self.group.handle_events(events) for e in events: if e.type == KEYDOWN: self.handle_keypress(e.key, pygame.key.get_mods()) def handle_keypress(self, key, modificated): if key == K_SPACE and self._manager.state < GAME_STATE_LOADING: ChangeState(int(not bool(self._manager.state))).post() if key == K_m and modificated and pygame.KMOD_CTRL: Selector(self._manager.get_display(), self.group) ChangeState(GAME_STATE_PAUSED).post() def draw(self): display_surface = self._manager.get_display() display_surface.blit(self.image, (0, 0)) self.group.update(display_surface) self.group.draw(display_surface)
def __init__(self, image): Surface.__init__(self, (300, 300)) self.rotation = 0 self.originalImage = image self.cubeSide = CubeSide(image, (100, 100), 0) self.imageLocation = (100, 100)
def __init__(self, size, score_manager): Surface.__init__(self, size) self.background = None self.width, self.height = size self.font = pygame.font.SysFont("Comic Sans MS", int(0.09 * self.width)) self.font2 = pygame.font.SysFont("Comic Sans MS", int(0.07 * self.width)) self.score_manager = score_manager self._load_images() self._init_board()
class FilteredSpList(Clickable): def __init__(self, data, x, y, filters): self.data = data self.filter = filters self.surface = Surface((200, 170)) self.x = x self.y = y self.up_button = Button(86, 0, 28, 21, callback=self.decrease_offset, sprite=SpriteManager().sprites['up_button']) self.down_button = Button(86, 142, 28, 21, callback=self.increase_offset, sprite=SpriteManager().sprites['down_button']) self.offset = 0 self.items = [self.up_button, self.down_button] self.clickables = [self.up_button, self.down_button] self.reset() def update_specialists(self): self.shown_sp_panels = self.sp_panels[self.offset:self.offset + 2] for i in range(len(self.shown_sp_panels)): self.shown_sp_panels[i].y = i * 60 + 21 def increase_offset(self): if self.offset < len(self.data.specialists) - 2: self.offset += 1 self.update_specialists() def decrease_offset(self): if self.offset > 0: self.offset -= 1 self.update_specialists() def draw(self, screen): self.surface.fill(0x000000) for item in self.items: item.draw(self.surface) for item in self.shown_sp_panels: item.draw(self.surface) screen.blit(self.surface, (self.x, self.y)) def is_pressed(self, wx, wy, button): x = wx - self.x y = wy - self.y res = False for item in self.clickables: res = res or item.is_pressed(x, y, button) for item in self.shown_sp_panels: if item.is_pressed(x, y, button): if item.selected: self.chosen.add(item.specialist) else: self.chosen.remove(item.specialist) res = True return res def reset(self): free_specialists = [sp for sp in self.data.specialists if not sp.occupied and sp.s_type in self.filter] self.sp_panels = [SpecialistPanel(0, 0, specialist, True) for specialist in free_specialists] self.update_specialists() self.chosen = set()
def text(self, value): #set the new text self._label.text = value #reconstruction of the frame surface, maybe resized frame = Surface((self._padding_left * 2 + self._label.width, self._padding_top * 2 + self._label.height)) frame.fill(Color("grey")) self._sprite.image = frame #self._sprite = SpriteFactory().fromSurface("widget.button", frame, self._sprite.rect.topleft, layer=self._sprite.layer) self._sprite.dirty = 1
class World(object): def __init__(self, width, height): self.width = 300 self.height = 300 self.grid_size = 20 self.pixel_size = Rect(0, 0, width, height) self.full_grid = Rect(0, 0, self.width, self.height) self.view_grid = Rect(10, 10, 0, 0) self.prev_view_grid = None self.zoom(0) self.ground = [[0 for col in range(self.width)] for row in range(self.height)] for y in range(self.height): for x in range(self.width): self.ground[y][x] = Assets.colors_db.any('dirt') self.surface = Surface((width, height), HWSURFACE, 32) def draw(self, screen): rect = self.view_grid if self.prev_view_grid != rect: self.prev_view_grid = Rect(rect) x1 = rect.left y1 = rect.top x2 = min(self.width, rect.left + rect.width) y2 = min(self.height, rect.top + rect.height) r = Rect(0, 0, self.grid_size, self.grid_size) for row in self.ground[y1:y2 - 1]: for col in row[x1:x2 - 1]: self.surface.fill(col, r) r.left += self.grid_size r.left = 0 r.top += self.grid_size screen.blit(self.surface, self.pixel_size) def view_move(self, move): self.view_grid.left += move.x self.view_grid.top += move.y self.view_grid.clamp_ip(self.full_grid) def zoom_in(self): self.zoom(+1) def zoom_out(self): self.zoom(-1) def zoom(self, dz): if 50 >= self.grid_size + dz >= 5: self.grid_size = self.grid_size + dz self.view_grid.width = int(math.ceil(self.pixel_size.width / float(self.grid_size))) + 1 self.view_grid.height = int(math.ceil(self.pixel_size.height / float(self.grid_size))) + 1 self.view_grid.clamp_ip(self.full_grid) self.prev_view_grid = None
def redraw(self, rotation_x, rotation_y): resize_width = 0 resize_height = 0 if (rotation_x + self.originalRotationX > 360): resize_width = (rotation_x + self.originalRotationX * 1.0) % 90.0 resize_width = int(resize_width * 100) Surface.__init__(self, self.get_size(), pygame.SRCALPHA) Transform.skew_surface(self.originalImage, 0, -rotation_y), (0, 0) self.blit(pygame.transform.scale(Transform.skew_surface(self.originalImage, 0, -rotation_y), (resize_width, self.get_size()[1])), (-rotation_x,0))
def create_layer(self): bgimg = media.load_image('bg.png').convert() rbgimg = bgimg.get_rect() rows = int(600 / rbgimg.height) + 2 layer = Surface((rbgimg.width, 600)) for y in xrange(rows): layer.blit(bgimg, rbgimg) rbgimg = rbgimg.move([0, rbgimg.height]) return layer
def __init__(self, size, game): Surface.__init__(self, size) self.width, self.height = size self.game = game self._load_images() self.font = pygame.font.SysFont("Comic Sans MS", int(0.09 * self.width)) self.font2 = pygame.font.SysFont("Comic Sans MS", int(0.035 * self.width)) self.select_column_text = self.font.render("Select column", 1, (255, 255, 0)) self.select_school_text = self.font.render("Select school", 1, (255, 255, 0)) self.move_text = self.font2.render("MOVE", 1, (255, 0, 0))
def create_bottom(self): bgimg = media.load_image('tile_wall.png').convert() bgimg = pygame.transform.flip(bgimg, False, True) rbgimg = bgimg.get_rect() cols = int(1000 / rbgimg.width) top = Surface((1000, rbgimg.height)) for x in xrange(cols): top.blit(bgimg, rbgimg) rbgimg = rbgimg.move([rbgimg.width, 0]) return top
def create_top(self): bgimg = media.load_image('tile_wall.png').convert() rbgimg = bgimg.get_rect() self.top_size = rbgimg.width cols = int(1000 / rbgimg.width) top = Surface((1000, rbgimg.height)) for x in xrange(cols): top.blit(bgimg, rbgimg) rbgimg = rbgimg.move([rbgimg.width, 0]) return top
def __init__(self, surface_image, front_size, side): Surface.__init__(self, front_size, pygame.SRCALPHA) self.originalImage = surface_image self.blit(surface_image, (0, 0)) self.side = side self.isVisible = True self.originalRotationX = 0 self.originalRotationY = 0 self.get_rotation()
def __init__(self, size, game, acceleration=ACCELERATION): Surface.__init__(self, size) self.width, self.height = size self.game = game self.player = Player(self, (size[0]/2, size[1]*0.8)) self.obstacle_manager = ObstacleManager(self, OBSTACLE_BASE_SPEED, MAX_OBSTACLES, CollisionStrategyFactory(self.game), self.player) self.children = [self.player, self.obstacle_manager] self.acceleration = acceleration