def __init__(self, city, msgs=[], padding=0, background_color=None): """ initialize. Initialized with a name, destroy button in upper right, and basic city information. """ planes.gui.Container.__init__(self, "{}_status".format(city.name), padding, background_color) self.city = city if city.owner: owner_name = city.owner.name else: owner_name = 'Neutral' city_data_strs = [('city_name', city.name), ('city owner', owner_name)] city_data_strs.extend(msgs) self.num_proj = -1 name_length = max([len(s[1]) for s in city_data_strs]) * char_width + char_width for s in city_data_strs: name_label = planes.gui.Label(s[0], s[1], Rect(0, 0, name_length, 15), background_color=teal) self.sub(name_label) destroy_button = planes.gui.Button( 'X', Rect(name_label.rect.width - char_width, 0, char_width, 15), lambda x: x.parent.parent.destroy(), background_color=teal) name_label.sub(destroy_button)
def 그리기(점수판, 게임종료메시지): # 그리기 함수 선언 화면.blit(배경, (0, 0)) # 화면색상 색으로 칠하기 # 음식 그리기 for food in 음식: # 음식 리스트의 개수 만큼 반복하기 pygame.draw.ellipse(화면, (255, 255, 0), Rect(food[0] * 20, food[1] * 20, 20, 20)) # 음식 그리기(타원) 색 가로 세로 # 뱀 그리기 for body in 뱀: # 뱀 리스트의 개수 만큼 반복하기 pygame.draw.rect(화면, (255, 255, 255), Rect(body[0] * 20, body[1] * 20, 20, 20)) # 음식 그리기(타원) 색 가로 세로 # 점수 그리기 if 점수판 != None: # 점수에 내용이 있으면 화면.blit(점수판, (10, 10)) # 점수판 위치 # 종료 메시지 그리기 if 게임종료: # 게임종료 메시지가 내용이 있으면 게임종료메시지 = my글꼴1.render("게임종료 점수 : " + str(점수), True, (255, 255, 255)) 화면.blit(게임종료메시지, (375, 400)) print(단계) pygame.display.update() # 화면 업데이트
def __init__(self, game_speed): self.x = randrange(350, WIDTH) self.y = randrange(4 / 5 * HEIGHT - 80) self.speed = game_speed self.surface = pygame.Surface((35, 35)) self.surface.fill(color.THECOLORS["orange"]) self.rect = Rect(self.surface.get_rect())
def main(): """main routine""" while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() SURFACE.fill((255, 255, 255)) pygame.draw.rect(SURFACE, (255, 0, 0), (10, 20, 100, 50)) pygame.draw.rect(SURFACE, (255, 0, 0), (150, 10, 100, 30), 3) pygame.draw.rect(SURFACE, (0, 255, 0), ((100, 80), (80, 50))) rect0 = Rect(200, 60, 140, 80) pygame.draw.rect(SURFACE, (0, 0, 255), rect0) rect1 = Rect((30, 160), (100, 50)) pygame.draw.rect(SURFACE, (255, 255, 0), rect1) # circle( Surface, color, pos, radius, width = 0) -> Rect pygame.draw.circle(SURFACE, (255, 0, 0), (150, 50), 20, 10) # ellipse( Surface, color, Rect, width = 0) -> Rect pygame.draw.ellipse(SURFACE, (0, 255, 0), (50, 150, 110, 60), 5) # line( Surface, color, start_ pos, end_ pos, width = 1) -> Rect # 青: 斜線( 太 さ 10) start_pos = (300, 30) end_pos = (380, 200) pygame.draw.line(SURFACE, (0, 0, 255), start_pos, end_pos, 10) pygame.display.update() FPSCLOCK.tick(3)
def main(): """main routine""" while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() SURFACE.fill((255, 255, 255)) # 빨간색: 직사각형(꽉 채워서 칠한다.) pygame.draw.rect(SURFACE, (255, 0, 0), (10, 20, 100, 50)) # 빨간색: 직사각형(굵기3) pygame.draw.rect(SURFACE, (255, 0, 0), (150, 10, 100, 30), 3) # 녹색:직사각형 pygame.draw.rect(SURFACE, (0, 255, 0), ((100, 80), (80, 50))) # 파란색:직사각형,Rect객체 rect0 = Rect(200, 60, 140, 80) pygame.draw.rect(SURFACE, (0, 0, 255), rect0) # 노란색:직사각형,Rect객체 rect1 = Rect((30, 160), (100, 50)) pygame.draw.rect(SURFACE, (255, 255, 0), rect1) pygame.display.update() FPSCLOCK.tick(3)
def update(self, game): """update - update the game window""" #self.game_plane.image.blit(self.game_background, (0,0)) #reset background drawing for c in game.cities: if not c.plane: c.plane = clickndrag.Plane("city of %s" % c.name, Rect(c.location, c.image_size)) c.plane.image.blit(c.image, (0, 0)) self.game_plane.sub(c.plane) for d in game.dredges: if not d.plane: image_size = 50, 50 d.plane = clickndrag.Plane(d.name, Rect(d.location, image_size)) d.plane.image.set_colorkey(white) d.plane.image.fill(white) draw_dredge(d.plane.image, d.dimensions, image_size[0]) #todo: figure out scaling #d.plane.image.blit(d.image, (0,0)) d.plane.draggable = True self.game_plane.sub(d.plane) self.date_status.text = game.date.strftime("Date: %d %B %Y") self.player_status.text = "Value: {0:,}".format( int(game.players[0].value)) self.screen.update() self.screen.render() pygame.display.flip() return True
def __init__(self, x_dim, y_dim): init() # Dimensions Game Screen (grid) self.x_dim = x_dim self.y_dim = y_dim self.MARGIN = 8 self.HEADER_BAR = 70 self.SPACE_PIXELS = 32 if (self.SPACE_PIXELS*self.x_dim + 2 * self.MARGIN) < 550 : self.WIDTH = 550 else: self.WIDTH = self.SPACE_PIXELS*self.x_dim + 2 * self.MARGIN self.HEIGHT = self.SPACE_PIXELS*self.y_dim + 2 * self.MARGIN + self.HEADER_BAR self._screen = display.set_mode((self.WIDTH, self.HEIGHT)) display.set_caption("BitSweeper") if (self.x_dim*self.SPACE_PIXELS) < self.WIDTH : self.GAME_SCREEN_LEFT = (self.WIDTH / 2) - ((self.x_dim* self.SPACE_PIXELS) / 2) else : self.GAME_SCREEN_LEFT = self.MARGIN # Dimensions buttons self.BUTTON_WIDTH = math.floor(self.WIDTH/3) # Dimensions timer and flag counter self.TIMER_WIDTH = 150 self.FLAG_COUNTER_HEIGHT = 20 self.FLAG_COUNTER_WIDTH = 150 # Game Screen (grid) self._gameScreen = self._screen.subsurface( Rect(self.GAME_SCREEN_LEFT, self.HEADER_BAR + self.MARGIN, self.SPACE_PIXELS*self.x_dim, self.SPACE_PIXELS*self.y_dim) ) # Reset button self._reset = self._screen.subsurface( Rect(self.MARGIN, self.MARGIN, self.BUTTON_WIDTH, self.HEADER_BAR-self.MARGIN) ) # Timer and flag counter self._timer = self._screen.subsurface( Rect(self.MARGIN + self.BUTTON_WIDTH + self.MARGIN, self.MARGIN, self.TIMER_WIDTH, self.FLAG_COUNTER_HEIGHT) ) self._flagCounter = self._screen.subsurface( Rect(self.MARGIN + self.BUTTON_WIDTH + self.MARGIN, self.MARGIN + self.FLAG_COUNTER_HEIGHT, self.FLAG_COUNTER_WIDTH, self.FLAG_COUNTER_HEIGHT) ) self._screen.fill(Color('light grey')) # Cheat Mode button self.CHEATMODE_WIDTH = math.floor(self.WIDTH/3) self._cheatMode = self._screen.subsurface( Rect(self.MARGIN + self.BUTTON_WIDTH + self.MARGIN + self.TIMER_WIDTH + self.MARGIN, self.MARGIN, self.CHEATMODE_WIDTH, self.HEADER_BAR-self.MARGIN) ) display.flip()
def draw_scoreboard(self, screen, screen_size, score): """Draws a box with the score in it onto the screen.""" screenw, screenh = screen_size wellx, welly = self.well_pixel_coords(screen_size) wellw, wellh = self.well_size() border_size = 5 padding = 20 height = 50 left = wellx + wellw + padding right = screenw - padding top = welly #bottom = top + height width = right - left + 1 pygame.draw.rect( screen, Color(255, 255, 255, 255), Rect(left - border_size, top - border_size, width + border_size * 2, height + border_size * 2)) pygame.draw.rect(screen, Color(0, 0, 0, 255), Rect(left, top, width, height)) text = str(score) font = pygame.font.SysFont("Lucida Console", 32, 1, 0) text_surface = font.render(text, False, Color(255, 255, 255, 255)) screen.blit(text_surface, (left + (width - text_surface.get_width()) / 2, top + (height - text_surface.get_height()) / 2))
def 그리기(점수판, 게임종료메세지): 화면.fill((0, 0, 0)) # 검정색으로 칠하기 화면.blit(배경, (0, 0)) # 음식 그리기 for food in 음식: pygame.draw.ellipse(화면, (0, 255, 0), Rect(food[0] * 20, food[1] * 20, 20, 20)) # 뱀 그리기 for body in 뱀[::2]: pygame.draw.rect(화면, (0, 0, 0), Rect(body[0] * 20, body[1] * 20, 20, 20)) for body in 뱀[1::2]: pygame.draw.rect(화면, (255, 255, 255), Rect(body[0] * 20, body[1] * 20, 20, 20)) # 점수 그리기 if 점수판 != None: # 점수에 내용이 있으면 화면.blit(점수판, (10, 10)) # 종료 메세지 그리기 if 게임종료메세지 != None: 화면.blit(게임종료메세지, (280, 500)) pygame.display.update() # 화면 업데이트
def draw_graph(): ''' 根据处理后的频域信息进行图像绘制 ''' # 从左到右让RGB渐变,并尽量不出现RGB(255,255,255)颜色 setColor = list(color) for n in range(0, transformedL.size, GAP): if setColor[0] + 5 <= COLOR_BOUND_H: setColor[0] += 5 elif setColor[1] + 5 <= COLOR_BOUND_H: setColor[1] += 5 setColor[0] -= 2 else: setColor[0] -= 5 # 左耳信息绘制在界面中线上方,右耳信息绘制在界面中线下方 # 为了美观在矩阵(RECT)上方绘制了一条短线 heightL = np.nan_to_num(transformedL[n]) heightR = np.nan_to_num(transformedR[n]) draw.rect( screen, setColor, Rect((GAP + n, WINDOW_SIZE[1] / 2 - heightL / 2 - 5), (GAP * 0.8, 1))) draw.rect( screen, setColor, Rect((GAP + n, WINDOW_SIZE[1] / 2), (GAP * 0.8, -heightL / 2))) draw.rect( screen, setColor, Rect((GAP + n, WINDOW_SIZE[1] / 2 + heightR / 2 + 5), (GAP * 0.8, 1))) draw.rect( screen, setColor, Rect((GAP + n, WINDOW_SIZE[1] / 2), (GAP * 0.8, heightR / 2)))
def __init__(self, game_speed): self.x = WIDTH + 100 self.y = 4 / 5 * HEIGHT - 60 self.speed = 2.25 * game_speed self.surface = pygame.Surface((60, 60)) self.surface.fill(color.THECOLORS["purple"]) self.rect = Rect(self.surface.get_rect())
def paint(): """update the screen""" SURFACE.fill((0, 0, 0)) for shape in SHAPES: polygons = shape.model.work for vertices in polygons: poly = [] for vertex in vertices: pos_z = vertex[2] if pos_z <= 1: continue poly.append((vertex[0] / pos_z * 1000 + 300, -vertex[1] / pos_z * 1000 + 300)) if len(poly) > 1: pygame.draw.lines(SURFACE, shape.get_color(), True, poly) pos_x, pos_z, theta = CAMERA[0], CAMERA[1], CAMERA_THETA RADAR.set_alpha(128) RADAR.fill((128, 128, 128)) pygame.draw.arc(RADAR, (0, 0, 225), Rect(pos_x + 100, -pos_z + 100, 200, 200), theta - 0.6 + pi / 2, theta + 0.6 + pi / 2, 100) pygame.draw.rect(RADAR, (225, 0, 0), Rect(pos_x + 200, -pos_z + 200, 5, 5)) for tank in TANKS: pygame.draw.rect(RADAR, (0, 255, 0), Rect(tank.get_x() + 200, -tank.get_z() + 200, 5, 5)) for shot in SHOTS: pygame.draw.rect(RADAR, (225, 225, 225), Rect(shot.get_x() + 200, -shot.get_z() + 200, 5, 5)) scaled_radar = pygame.transform.scale(RADAR, (300, 300)) SURFACE.blit(scaled_radar, (650, 50)) pygame.display.update()
def __init__(self, toState, image, x, y, w, h): '''Initializes button's draw rectangle, image, isDown state and click event transition state''' self.rect = Rect(x, y, w, h) self.image = image self.toState = toState self.isDown = False
def main(): """ main routine """ while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() SURFACE.fill((255, 255, 255)) # 赤:矩形(塗りつぶし) pygame.draw.rect(SURFACE, (255, 0, 0), (10, 20, 100, 50)) # 赤:矩形(太さ3) pygame.draw.rect(SURFACE, (255, 0, 0), (150, 10, 100, 30), 3) # 緑:矩形 pygame.draw.rect(SURFACE, (0, 255, 0), ((100, 80), (80, 50))) # 青:矩形、Rectオブジェクト rect0 = Rect(200, 60, 140, 80) pygame.draw.rect(SURFACE, (0, 0, 255), rect0) # 黄:矩形、Rectオブジェクト rect1 = Rect((30, 160), (100, 50)) pygame.draw.rect(SURFACE, (255, 255, 0), rect1) pygame.display.update() FPSCLOCK.tick(3)
def update_col(self, col=0, num=3, base=16, blank=False): # ある桁にある数字を表示する関数 # numをcol桁目に表示、桁は最上位桁の左から右へ進む。 block_size = self.BLOCK_SIZE num = num % base # デフォルトは16進数表示 for segment in segments: # 7つのセグメントのうちの、あるセグメントについて、 if segment[num] == 1: color = self.COLOR_ON else: color = self.COLOR_OFF if blank is True: # ブランク表示の場合は、すべてOFFで上書き color = self.COLOR_OFF # 桁の原点 x0 = self.X_ORG + self.COL_INTV * col y0 = self.Y_ORG # ブロック1、ブロック2の座標オフセット x1, y1 = segment[16][0] x2, y2 = segment[16][1] # ブロック1、ブロック2の原点座標 org1 = (x0 + x1 * self.BLOCK_INTV, y0 - y1 * self.BLOCK_INTV) org2 = (x0 + x2 * self.BLOCK_INTV, y0 - y2 * self.BLOCK_INTV) # ブロック1,2を描く pygame.draw.rect(self.screen, color, Rect(org1[0], org1[1], block_size, block_size)) pygame.draw.rect(self.screen, color, Rect(org2[0], org2[1], block_size, block_size))
def main(): """メインルーチン""" pos_x = 0 pos_y = 0 velocity_x = 5 velocity_y = 6 while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() SURFACE.fill((0, 0, 0)) pos_x += velocity_x if pos_x > 600: pos_x = 0 pos_y += velocity_y if pos_y > 600: pos_y = 0 pygame.draw.rect(SURFACE, (255, 255, 255), Rect(pos_x, 200, 10, 10)) pygame.draw.rect(SURFACE, (255, 255, 255), Rect(200, pos_y, 10, 10)) pygame.display.update() FPSCLOCK.tick(10)
def __init__(self, table_dim, margins, p1, p2, b): self.p1 = fRect(p1.pos, p2.size) self.p2 = fRect(p1.pos, p2.size) self.b = fRect(b.pos, b.size) self.dim = (table_dim[0], table_dim[1]) self.walls_Rects = [Rect((-100, -100), (table_size[0]+200, 100)), Rect((-100, table_size[1]), (table_size[0]+200, 100))]
def draw(self, p_game_screen: Surface, p_actor: Actor): """ Draw an Energy bar on a Surface using the energy value of an Actor Args: p_game_screen: The Surface to draw to p_actor: The Actor to display the energy status of """ if p_actor.get_energy() > 70: rectangle = Rect(self.coordinate.get_x(), self.coordinate.get_y(), 60, 20) draw.rect(p_game_screen, color.THECOLORS['green'], rectangle) elif p_actor.get_energy() > 30: rectangle = Rect(self.coordinate.get_x(), self.coordinate.get_y(), 60, 20) draw.rect(p_game_screen, color.THECOLORS['orange'], rectangle) else: rectangle = Rect(self.coordinate.get_x(), self.coordinate.get_y(), 60, 20) draw.rect(p_game_screen, color.THECOLORS['red'], rectangle) rectangle_border = Rect(self.coordinate.get_x() - 3, self.coordinate.get_y() - 3, 65, 25) draw.rect(p_game_screen, color.THECOLORS['black'], rectangle_border, 2) self.draw_header(p_game_screen, "Energy")
def chamadaImagensDominoCentroMesa(self): for i in range(len(Utils.listaPedrasInseridasNaMesa)): Utils.img = pygame.image.load( Utils.listaPedrasInseridasNaMesa[i]['url']) size = Utils.listaPedrasInseridasNaMesa[i]['size'] pos = Utils.listaPedrasInseridasNaMesa[i]['pos'] Utils.img = pygame.transform.scale(Utils.img, (size)) if Utils.listaPedrasInseridasNaMesa[i]["rotate"]["verify"] == True: Utils.img = pygame.transform.rotate( Utils.img, Utils.listaPedrasInseridasNaMesa[i]["rotate"]["grau"]) Utils.listaPedrasInseridasNaMesa[i]["rectLadosPedra"][ "rectEsquerda"] = Rect((pos[0], (pos[1] + 2)), ((size[0] - 6), (size[1] / 2))) print "POS = ", pos print "SIZE = ", size Utils.listaPedrasInseridasNaMesa[i]["rectLadosPedra"][ "rectDireita"] = Rect(((pos[0] + 40), pos[1] + 2), ((size[0] - 7), (size[1] / 2))) else: Utils.listaPedrasInseridasNaMesa[i]['rect'] = Rect( Utils.listaPedrasInseridasNaMesa[i]['pos'], (Utils.listaPedrasInseridasNaMesa[i]['size'])) self.screen.blit(Utils.img, Utils.listaPedrasInseridasNaMesa[i]['pos']) pygame.display.update()
def main(): while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() SURFACE.fill((255, 255, 255)) # Red rectangle(full) pygame.draw.rect(SURFACE, (255, 0, 0), (10, 20, 100, 50)) # Red rectangle(not full) pygame.draw.rect(SURFACE, (255, 0, 0), (150, 10, 100, 50), 3) # Green rectangle pygame.draw.rect(SURFACE, (0, 255, 0), (100, 80, 80, 50)) # Blue rectangle rect0 = Rect(200, 60, 140, 80) pygame.draw.rect(SURFACE, (0, 0, 255), rect0) # Yellow rectangle rect1 = Rect(30, 160, 100, 50) pygame.draw.rect(SURFACE, (255, 255, 0), rect1) pygame.display.update()
def main(): # メイン関数 while True: # 無限ループ for event in pygame.event.get(): # イベントキューからイベントを取得 if event.type == QUIT: # 終了イベントの判定 pygame.quit() # PyGameの初期化を解除 sys.exit() # プログラム終了 # White surface SCREEN.fill((255, 255, 255)) # Red:rectangle pygame.draw.rect(SCREEN, (255, 0, 0), (10, 20, 100, 50)) # Red:rectangle pygame.draw.rect(SCREEN, (255, 0, 0), (150, 10, 100, 30), 3) # Green:rectangle pygame.draw.rect(SCREEN, (0, 255, 0), ((100, 80), (80, 50))) # Blue:rectangle Rect object rect0 = Rect(200, 60, 140, 80) pygame.draw.rect(SCREEN, (0, 0, 255), rect0) # Yellow:rectangle Rect object rect1 = Rect((30, 160), (100, 50)) pygame.draw.rect(SCREEN, (255, 255, 0), rect1) pygame.display.update() # 描画内容を画面に反映 FPSCLOCK.tick(3) # 1 秒間に 3 回ループする
def paint(message): SURFACE.fill((0, 0, 0)) for food in FOODS: pygame.draw.ellipse(SURFACE, (0, 255, 0), Rect(food[0] * 30, food[1] * 30, 30, 30)) for bomb in BOMBS: pygame.draw.ellipse(SURFACE, (255, 0, 0), Rect(bomb[0] * 30, bomb[1] * 30, 30, 30)) for body in SNAKE: pygame.draw.rect(SURFACE, (0, 255, 255), Rect(body[0] * 30, body[1] * 30, 30, 30)) for enemy in ENEMY: pygame.draw.rect(SURFACE, (255, 30, 30), Rect(enemy[0] * 30, enemy[1] * 30, 30, 30)) for index in range(20): pygame.draw.line(SURFACE, (64, 64, 64), (index * 30, 0), (index * 30, 600)) pygame.draw.line(SURFACE, (64, 64, 64), (0, index * 30), (600, index * 30)) if message is not None: SURFACE.blit(message, (150, 300)) smallfont = pygame.font.SysFont(None, 36) message_score = smallfont.render("SCORE = " f'{len(SNAKE)}', True, (0, 255, 255)) SURFACE.blit(message_score, (250, 0)) pygame.display.update()
def __init__(self, screensize, id): self.screensize = screensize self.id = id # place ball in the center self.centerx = int(screensize[0] * 0.5) self.centery = int(screensize[1] * 0.5) self.radius = 8 # create shape and sizes it self.rect = Rect(self.centerx - self.radius, self.centery - self.radius, self.radius * 2, self.radius * 2) self.color = const.WHITE self.direction = [1, 1] # current direction to the right and up # list so we can access each individual part because it will change self.speedx = 2 self.speedy = 5 self.hit_left_edge = False self.hit_right_edge = False self.ai_score = 0 self.player_score = 0 self.player_paddle_win = False self.ai_paddle_win = False self.play_sound = False
def 그리기(점수판, 게임종료): # 음식 그리기 for food in 음식: pygame.draw.ellipse(화면, (0, 255, 0), Rect(food[0] * 20, food[1] * 20, 20, 20)) # 타원그리기( 화면이동 , (칼라[RGB] , 타원( x축 , y축 , 가로크기 , 세로크기 ) # 점수 그리기 if 점수판 != None: # 점수에 내용이 있으면 화면.blit(점수판, (10, 10)) # x좌표 y좌표 표기 # 뱀 그리기 for body in 뱀: pygame.draw.rect(화면, (0, 255, 255), Rect(body[0] * 20, body[1] * 20, 20, 20)) # 사각형그리기( 화면이름 , (칼라[RGB] , 사각형( x축 , y축 , 가로크기 , 세로크기 ) # 종료메세지 그리기 if 게임종료: # 게임종료메세지 내용이 있으면 게임종료메세지 = my글꼴.render("게임 종료 [ 획득점수는: ] " + str(점수), True, (255, 255, 0)) 화면.blit(게임종료메세지, (275, 450)) # x좌표 y좌표에 표기 pygame.display.update() # 화면 업데이트
def main(): """メインルーチン""" rect = Rect(0, 600, 10, 10) velocity = [5, -20] accel = (0, 0.5) while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() SURFACE.fill((0, 0, 0)) velocity[1] += accel[1]; rect.move_ip(velocity) if rect.x > 600: rect.x = 0 if rect.y > 600: velocity[1] = -20 pygame.draw.rect(SURFACE, (255, 255, 255), rect) pygame.display.update() FPSCLOCK.tick(10)
def __init__(self, left: int, top: int, game_player, image_height: int=50): super().__init__() self.game_player = game_player surface = game_player.character.face_image name = game_player.player.name stock = game_player.stock # キャラ画像 image_width = image_height rect = Rect(left, top, image_width, image_height) image = surface_fit_to_rect(surface, rect) self.character_sprite = SimpleSprite(rect, image) self.add(self.character_sprite) # ストックの丸 self.stock = stock self.stock_sprites = [Group() for i in range(stock)] x, y = self.character_sprite.rect.bottomright stock_radius = int(0.05 * image_height) left, top = x, y - stock_radius * 2 for i in range(stock): surface = Surface((stock_radius * 2, stock_radius * 2)).convert_alpha() surface.fill((125, 125, 125)) surface.set_colorkey(surface.get_at((0, 0))) pygame.gfxdraw.filled_circle(surface, stock_radius, stock_radius, stock_radius-1, (255, 255, 255)) stock_sprite = SimpleSprite(Rect(left, top, stock_radius * 2, stock_radius * 2), surface) self.stock_sprites[i].add(stock_sprite) print(self.stock_sprites[i]) left += stock_radius * 2 # プレイヤーネーム font_size = int(0.2 * image_height) font = pygame.font.Font(None, font_size) left, bottom = self.character_sprite.rect.bottomright bottom -= stock_radius * 2 self.player_name_sprite = TextSprite( x=left, y=bottom, align="left", vertical_align="bottom", text=name, font=font, color=(255, 255, 255) ) self.add(self.player_name_sprite) # プレイヤーネームのbg width = self.character_sprite.rect.w + max(stock_radius * 2 * stock, self.player_name_sprite.rect.w) + 10 height = self.character_sprite.rect.h self.base_rect = Rect(*self.character_sprite.rect.topleft, width, height) rect = self.base_rect bg_image = Surface(rect.size).convert_alpha() bg_image.fill((0, 0, 0)) bg_image.set_alpha(225) bg_sprite = SimpleSprite(rect, bg_image) self.bg_group = Group() self.bg_group.add(bg_sprite)
def makeRectangle(self,xCenter,yCenter): # rectangle rectangle = Rect(0,0,config.buttonWidth,config.buttonHeight) # align rectangle.centerx = xCenter rectangle.centery = yCenter # store return(rectangle)
def __init__(self, pos, piece, isIt): self.pos = pos self.piece = piece self.isFull = isIt self.clicked = False self.highlightme = False self.square = Rect(self.pos[0], self.pos[1], 80, 80)
def __init__(self, xpos): self.rect = Rect(xpos, 550, 40, 40) self.exploded = False strip = pygame.image.load("strip.png") self.images = (pygame.Surface((20, 20), pygame.SRCALPHA), pygame.Surface((20, 20), pygame.SRCALPHA)) self.images[0].blit(strip, (0, 0), Rect(0, 0, 20, 20)) self.images[1].blit(strip, (0, 0), Rect(20, 0, 20, 20))
def __init__(self, rect, offset0, offset1): strip = pygame.image.load("./image/strip.png") self.images = (pygame.Surface((24, 24), pygame.SRCALPHA), pygame.Surface((24, 24), pygame.SRCALPHA)) self.rect = rect self.count = 0 self.images[0].blit(strip, (0, 0), Rect(offset0, 0, 24, 24)) self.images[1].blit(strip, (0, 0), Rect(offset1, 0, 24, 24))
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 testRow1(self): rect = Rect(3 * view.TILE_SIZE + 4, 5 * view.TILE_SIZE + 4, 24, 24) baseRect = rect.move(0, 0) self.assertEqual(1, len(rpgMap.getRectTiles(baseRect))) self.assertEqual((True, 2), rpgMap.isMoveValid(2, baseRect)) baseRect = rect.move(16, 0) self.assertEqual(2, len(rpgMap.getRectTiles(baseRect))) self.assertEqual((False, 2), rpgMap.isMoveValid(2, baseRect)) baseRect = rect.move(32, 0) self.assertEqual(1, len(rpgMap.getRectTiles(baseRect))) self.assertEqual((True, 2.5), rpgMap.isMoveValid(2, baseRect))
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 initBaseRect(self): baseRectWidth = self.mapRect.width baseRectHeight = BASE_RECT_HEIGHT if hasattr(self, "baseRectSize"): baseRectWidth = self.baseRectSize[0] baseRectHeight = self.baseRectSize[1] baseRectTop = self.getBaseRectTop(baseRectHeight) baseRectLeft = (self.mapRect.width - baseRectWidth) / 2 self.baseRect = Rect(baseRectLeft, baseRectTop, baseRectWidth, baseRectHeight)
def __init__(self, x_init_world, y_init_world, width_view_camera, height_view_camera): # rect that represents the surface visible of the camera self.rect_view_camera = Rect(x_init_world, y_init_world, width_view_camera, height_view_camera) self.pos_dest_screen = (0, 0) # Position to draw the map captured by this Camera self.map_handler = None # Controller of the map self.map_tile_surface = None # Surface Buffer that contains the map drawn self.rect_hidden_camera = None # Rect of the surface buffer with pos on map self.following = None self.can_follow = {"left": False, "top": False, "bottom": False, "right": True}
def create_image(self, rect_camera_map): # pre: rect_image must be created <TILE_SIZE*rows>X<TILE_SIZE*columns> assert self.is_map_loaded, "There's no map loaded yet!" image_map_tile = pygame.Surface(rect_camera_map.size, SRCALPHA) n_rows = rect_camera_map.height // self.tile_size n_columns = rect_camera_map.width // self.tile_size i_init_matriz = rect_camera_map.y // self.tile_size j_init_matriz = rect_camera_map.x // self.tile_size src_srfc_tile_rect = Rect(0, 0, self.tile_size, self.tile_size) for i in range(n_rows): i_matrix = i_init_matriz + i if i_matrix >= self.n_rows: continue for j in range(n_columns): j_matrix = j_init_matriz + j if j_matrix >= self.n_cols: continue tile_index = self.matrix_tiles[i_matrix][j_matrix] if tile_index != 0: src_srfc_tile_rect.x = self.tile_size * (tile_index - 1) image_map_tile.blit(self.tileset_surface, ( (j_matrix - j_init_matriz) * self.tile_size, (i_matrix - i_init_matriz) * self.tile_size), src_srfc_tile_rect) return image_map_tile
def __init__(self, *args): if not hasattr(self, "image"): self.image = None if not hasattr(self, "rect"): self.rect = Rect(0, 0, 32, 32) self._group = args[0] self._visible = False self._zindex = 0 self._dirty = True self._alpha = 255 self.damaged = False self.damaged_areas = [] self.last_state = None Sprite.__init__(self, *args)
def __init__(self): self.Sprite = Sprite.Sprite() self.start = (0, 0) self.end = (0, 0) self.dim = Rect(0, 0, 0, 0) self.on = False self.shaders = ("", "") self.anim_rate= -1 self.anim_fn = "" # Various entity attributes self.phyz = False self.anim = False self.static = False self.p_spawn = False self.e_spawn = False
class ButtonRect: """Button class for add players based on the Command pattern.""" def __init__(self, x, y, w, h, command): """ Constructor """ self.rect = Rect(x, y, w, h) self.command = command def handleMouseDown(self, x, y): if self.rect.collidepoint(x, y): if self.command <> None: self.command.do() def draw(self, surface): # TODO : use picture here. # This method could also be implemented by subclasses. pygame.draw.rect(surface, (100, 100, 100), self.rect)
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 __init__(self): # References to draw self.image_path = ('character', 'human_sprite.png') self.image = Assets.load_image(self.image_path) self.name = Assets.names_db.random_full_name() #frm = display.font.render(str(frame), True, text_color) #rect = frm.get_rect() self.rect = Rect(0, 0, 0, 0) self.location = Rect(0, 0, 1, 1) self.target = Rect(50, 20, 1, 1) self.pct = 0.0 self.next = Rect(self.location.x, self.location.y, 1, 1) # Traits and skills. General idea self.traits = { "health": 100, "intelligence": 0, "strength": 0, "mining": 0, "shooting": 0, "armour": 0, "weight": 0, "rotation": 0, "speed": 0, "versatility:": 0, "weight-capacity:": 0 } # What the character has equipped self.equips = { "body_part_upper": None, "body_part_lower": None } # Condition: [inflicted?, Damage, Duration, Duration Remaining] self.conditions = { "Burn": [False, 1, 10, 0], "Frost": [False, 1, 15, 0], "Stun": [False, 1, 5, 0], "Sleep": [False, 1, 20, 0], "Shock": [False, 1, 3, 0], "Poison": [False, 1, 15, 0], "Bleed": [False, 1, 3, 0] }
class ButtonCircle: """Button class for add players based on the Command pattern.""" def __init__(self, x, y, r, command, color=(100,100,100)): """ Constructor """ self.r = r self.rect = Rect(x-r, y-r, r*2, r*2) self.command = command self.color = color def handleMouseDown(self, x, y): if self.rect.collidepoint(x, y): if self.command <> None: self.command.do() def draw(self, surface): # TODO : use picture here. # This method could also be implemented by subclasses. pygame.draw.circle(surface, self.color, (self.rect.x, self.rect.y), self.r)
def load_map(self, path_to_file_level): # Tile s positioning data file_level = open(path_to_file_level) self.matrix_tiles = [] # lines = file_level.readlines() # n_lines = len(lines) self.n_rows, self.n_cols, self.n_tiles = read_n_rows_columns_num_tiles(file_level) if self.is_map_loaded: self.check_loaded_tileset() # We check that we can cover the tiles with our current # tile set i = 0 while i < self.n_rows: j = 0 line = list(file_level.readline().strip()) while j < self.n_cols: try: line[j] = int(line[j]) if line[j] < 0 or line[j] >= self.n_tiles: raise AssertionError("Tile Value at ({0},{1}) must be in range {2}-{3}. '{4}' not permitted". format(i + 2, j + 1, 0, self.n_tiles - 1, line[j])) except ValueError: raise AssertionError("Tile Value at ({0},{1}) must be an Integer. '{2}' not permitted". format(i + 2, j + 1, line[j])) except IndexError: raise AssertionError("Wrong number of tiles at line {0}. {1} tiles are missing". format(i + 2, self.n_cols - j)) j += 1 self.matrix_tiles.append(line) i += 1 file_level.close() self.rect_full_map = Rect(0, 0, self.n_cols * self.tile_size, self.n_rows * self.tile_size) self.is_map_loaded = True
def testLevel3(self): rect = Rect(10 * view.TILE_SIZE + 4, 2 * view.TILE_SIZE + 4, 24, 24) baseRect = rect.move(0, 0) self.assertEqual(1, len(rpgMap.getRectTiles(baseRect))) self.assertEqual((False, 3), rpgMap.isMoveValid(3, baseRect)) baseRect = rect.move(0, 16) self.assertEqual(2, len(rpgMap.getRectTiles(baseRect))) self.assertEqual((False, 3), rpgMap.isMoveValid(3, baseRect)) baseRect = rect.move(0, 32) self.assertEqual(1, len(rpgMap.getRectTiles(baseRect))) self.assertEqual((True, 3), rpgMap.isMoveValid(3, baseRect)) baseRect = rect.move(0, 48) self.assertEqual(2, len(rpgMap.getRectTiles(baseRect))) self.assertEqual((False, 3), rpgMap.isMoveValid(3, baseRect)) baseRect = rect.move(0, 64) self.assertEqual(1, len(rpgMap.getRectTiles(baseRect))) self.assertEqual((False, 3), rpgMap.isMoveValid(3, baseRect))
class MapHandler: def __init__(self, tile_size): self.matrix_tiles = None self.rect_full_map = None self.tileset_surface = None self.is_map_loaded = False self.n_rows = 0 self.n_cols = 0 self.n_tiles = 0 self.path_to_tileset = None self.tile_size = tile_size # Load a file containing tile positioning def load_map(self, path_to_file_level): # Tile s positioning data file_level = open(path_to_file_level) self.matrix_tiles = [] # lines = file_level.readlines() # n_lines = len(lines) self.n_rows, self.n_cols, self.n_tiles = read_n_rows_columns_num_tiles(file_level) if self.is_map_loaded: self.check_loaded_tileset() # We check that we can cover the tiles with our current # tile set i = 0 while i < self.n_rows: j = 0 line = list(file_level.readline().strip()) while j < self.n_cols: try: line[j] = int(line[j]) if line[j] < 0 or line[j] >= self.n_tiles: raise AssertionError("Tile Value at ({0},{1}) must be in range {2}-{3}. '{4}' not permitted". format(i + 2, j + 1, 0, self.n_tiles - 1, line[j])) except ValueError: raise AssertionError("Tile Value at ({0},{1}) must be an Integer. '{2}' not permitted". format(i + 2, j + 1, line[j])) except IndexError: raise AssertionError("Wrong number of tiles at line {0}. {1} tiles are missing". format(i + 2, self.n_cols - j)) j += 1 self.matrix_tiles.append(line) i += 1 file_level.close() self.rect_full_map = Rect(0, 0, self.n_cols * self.tile_size, self.n_rows * self.tile_size) self.is_map_loaded = True def clamp_rect(self, rect): return rect.clamp(self.rect_full_map) def has_map_loaded(self): return self.is_map_loaded def load_tileset(self, path_to_file_image): # Tile s image self.tileset_surface = pygame.image.load(path_to_file_image) self.check_loaded_tileset() self.tileset_surface.convert() self.path_to_tileset = path_to_file_image def is_rect_out_of_map_bounds(self, rect): return not self.rect_full_map.contains(rect) # Create a Surface that contains/draws all the visible tiles that are contained in rect_cut def create_image(self, rect_camera_map): # pre: rect_image must be created <TILE_SIZE*rows>X<TILE_SIZE*columns> assert self.is_map_loaded, "There's no map loaded yet!" image_map_tile = pygame.Surface(rect_camera_map.size, SRCALPHA) n_rows = rect_camera_map.height // self.tile_size n_columns = rect_camera_map.width // self.tile_size i_init_matriz = rect_camera_map.y // self.tile_size j_init_matriz = rect_camera_map.x // self.tile_size src_srfc_tile_rect = Rect(0, 0, self.tile_size, self.tile_size) for i in range(n_rows): i_matrix = i_init_matriz + i if i_matrix >= self.n_rows: continue for j in range(n_columns): j_matrix = j_init_matriz + j if j_matrix >= self.n_cols: continue tile_index = self.matrix_tiles[i_matrix][j_matrix] if tile_index != 0: src_srfc_tile_rect.x = self.tile_size * (tile_index - 1) image_map_tile.blit(self.tileset_surface, ( (j_matrix - j_init_matriz) * self.tile_size, (i_matrix - i_init_matriz) * self.tile_size), src_srfc_tile_rect) return image_map_tile def check_loaded_tileset(self): if normalize(self.tileset_surface.get_width(), self.tile_size) != self.tileset_surface.get_width() or \ self.tileset_surface.get_width() // self.tile_size < ( self.n_tiles - 1) or self.tileset_surface.get_height() != self.tile_size: raise AssertionError( 'Wrong tileset, {0} must be width>={1} , height={2} and contain {3} different aligned tiles.'.format( self.path_to_tileset, self.n_tiles * self.tile_size, self.tile_size, self.n_tiles - 1)) def collide_map(self, rect): assert self.is_map_loaded, "There's no map loaded yet!" rect_collide = create_camera_rect(rect, self.tile_size) n_rows = rect_collide.height // self.tile_size n_columns = rect_collide.width // self.tile_size i_init_matriz = rect_collide.y // self.tile_size j_init_matriz = rect_collide.x // self.tile_size collide_list = [] for i in range(n_rows): i_matrix = i_init_matriz + i if i_matrix >= self.n_rows: continue for j in range(n_columns): j_matrix = j_init_matriz + j if j_matrix >= self.n_cols: continue tile_index = self.matrix_tiles[i_matrix][j_matrix] if tile_index != 0: collide_list.append((tile_index, (i, j))) return collide_list def get_tile_size(self): return self.tile_size def get_floor_dist(self, x, y, max_dist): """Obtiene la distancia entre el punto (x, y) y el proximo bloque solido hacia abajo""" for dy in range(max_dist): if (y + dy) % self.tile_size == 0 and self.matrix_tiles[int((y + dy) // self.tile_size)][ x // self.tile_size] != 0: return dy return max_dist def get_nearest_bottom_tile(self, rect, max_deep): """"Regresa el primer tile que se encuentre hacia abajo""" rect_collide = create_camera_rect(rect, self.tile_size) n_columns = rect_collide.width // self.tile_size i_init_matriz = rect_collide.bottom // self.tile_size j_init_matriz = rect_collide.x // self.tile_size for i in range(max_deep): i_matrix = i_init_matriz + i if i_matrix >= self.n_rows: return None for j in range(n_columns): j_matrix = j_init_matriz + j if j_matrix >= self.n_cols: break tile_index = self.matrix_tiles[i_matrix][j_matrix] if tile_index != 0: return tile_index, (i_matrix, j_matrix), rect_collide.bottom - rect.bottom + i * self.tile_size return None
class Character(object): """ This class defines the characteristics of any character starting out """ def __init__(self): # References to draw self.image_path = ('character', 'human_sprite.png') self.image = Assets.load_image(self.image_path) self.name = Assets.names_db.random_full_name() #frm = display.font.render(str(frame), True, text_color) #rect = frm.get_rect() self.rect = Rect(0, 0, 0, 0) self.location = Rect(0, 0, 1, 1) self.target = Rect(50, 20, 1, 1) self.pct = 0.0 self.next = Rect(self.location.x, self.location.y, 1, 1) # Traits and skills. General idea self.traits = { "health": 100, "intelligence": 0, "strength": 0, "mining": 0, "shooting": 0, "armour": 0, "weight": 0, "rotation": 0, "speed": 0, "versatility:": 0, "weight-capacity:": 0 } # What the character has equipped self.equips = { "body_part_upper": None, "body_part_lower": None } # Condition: [inflicted?, Damage, Duration, Duration Remaining] self.conditions = { "Burn": [False, 1, 10, 0], "Frost": [False, 1, 15, 0], "Stun": [False, 1, 5, 0], "Sleep": [False, 1, 20, 0], "Shock": [False, 1, 3, 0], "Poison": [False, 1, 15, 0], "Bleed": [False, 1, 3, 0] } # Draw character def draw(self, screen, world): if not world.view_grid.contains(self.location) and not world.view_grid.contains(self.next): return if world.grid_size != self.rect.width: self.rect.width = self.rect.height = world.grid_size self.image = Assets.load_image(self.image_path, (world.grid_size, world.grid_size)) self.rect.x = (self.location.x - world.view_grid.x) * world.grid_size \ + (self.next.x - self.location.x) * self.pct * world.grid_size self.rect.y = (self.location.y - world.view_grid.y) * world.grid_size \ + (self.next.y - self.location.y) * self.pct * world.grid_size screen.blit(self.image, self.rect) # Equip component # Un-equip component # Equip Upper or Lower Body Part def body_part_equip(self, part): #If it's an upper body part if part.upper: self.equips["body_part_upper"] = part else: self.equips["body_part_lower"] = part #Pad character's stats with the stats of the part #Example: self.traits["weight"] = self.traits["weight"] + part.weight #... # Un-equip Armour def body_part_unequip(self, part): if part.upper: self.equips["body_part_upper"] = None else: self.equips["body_part_lower"] = None #Unpad character's stats with the stats of the part #... @property def weight(self): return self.traits["weight"] + sum(p.weight for p in self.equips.values() if p is not None) # Apply condition on the character. def inflict(self, condition): if condition not in self.conditions: return self.conditions[condition][0] = True self.conditions[condition][3] = self.conditions[condition][2] print(self.conditions) def set_target(self, pos): self.target.x, self.target.y = pos def tick(self): if self.target != self.location: if self.pct >= 0.9: self.location = self.next.copy() self.pct = 0.0 if self.next == self.location: # pick a block to go to next if self.target.x > self.location.x: self.next.x = self.location.x + 1 elif self.target.x < self.location.x: self.next.x = self.location.x - 1 if self.target.y > self.location.y: self.next.y = self.location.y + 1 elif self.target.y < self.location.y: self.next.y = self.location.y - 1 self.pct += 0.2 for condition in self.conditions: if self.conditions[condition][0]: if self.conditions[condition][3] == 0: # character lived through the condition self.conditions[condition][0] = False else: self.traits["health"] -= self.conditions[condition][1] self.conditions[condition][3] -= 1 print(self.conditions[condition][3]) # Character died. (Need to know what happens when a character dies) def death(self): print("Character has died.") # Absolve character of all conditions self.conditions = self.conditions.fromkeys(self.conditions, False) return
class RpgSprite(pygame.sprite.Sprite): def __init__(self, spriteFrames, position = (0, 0)): pygame.sprite.Sprite.__init__(self) # properties common to all RpgSprites self.spriteFrames = spriteFrames self.position = [i * SCALAR for i in position] self.image, temp = self.spriteFrames.advanceFrame(0) # indicates if this sprite stands upright self.upright = True # indicates if this sprite is currently visible self.inView = False # indicates if this sprite is currently masked by any map tiles self.masked = False # indicates if this sprite should be removed on next update self.toRemove = False def setup(self, uid, rpgMap, eventBus): self.uid = uid self.rpgMap = rpgMap self.eventBus = eventBus def setTilePosition(self, tx, ty, level): self.x, self.y = tx, ty self.setPixelPosition(tx * TILE_SIZE + self.position[0], ty * TILE_SIZE + self.position[1], level) def setPixelPosition(self, px = 0, py = 0, level = None): # main rect self.rect = self.image.get_rect() # other rectangles as required by the game engine self.mapRect = self.image.get_rect() self.initBaseRect() # if required, move to the requested position if level: self.level = level if px > 0 or py > 0: self.doMove(px, py) def initBaseRect(self): baseRectWidth = self.mapRect.width baseRectHeight = BASE_RECT_HEIGHT if hasattr(self, "baseRectSize"): baseRectWidth = self.baseRectSize[0] baseRectHeight = self.baseRectSize[1] baseRectTop = self.getBaseRectTop(baseRectHeight) baseRectLeft = (self.mapRect.width - baseRectWidth) / 2 self.baseRect = Rect(baseRectLeft, baseRectTop, baseRectWidth, baseRectHeight) # print self.uid, self.baseRect.width, self.baseRect.height def getBaseRectTop(self, baseRectHeight): return self.mapRect.bottom - baseRectHeight def doMove(self, px, py): self.mapRect.move_ip(px, py) self.baseRect.move_ip(px, py) # a pseudo z order is used to test if one sprite is behind another self.z = int(self.mapRect.bottom + self.level * TILE_SIZE) def clearMasks(self): if self.masked: self.masked = False self.spriteFrames.repairCurrentFrame() def applyMasks(self): # masks is a map of lists, keyed on the associated tile points masks = self.rpgMap.getMasks(self) if len(masks) > 0: self.masked = True for tilePoint in masks: px = tilePoint[0] * view.TILE_SIZE - self.mapRect.left py = tilePoint[1] * view.TILE_SIZE - self.mapRect.top [self.image.blit(mask, (px, py)) for mask in masks[tilePoint]] def advanceFrame(self, increment, metadata): self.image, frameIndex = self.spriteFrames.advanceFrame(increment, **metadata) self.playSound(frameIndex) def playSound(self, frameIndex): pass def isIntersecting(self, sprite): if self != sprite and self.level == sprite.level and self.baseRect.colliderect(sprite.baseRect): return True return False; def processCollision(self, player): pass def processAction(self, player): pass
def __init__(self, x, y, w, h, command): """ Constructor """ self.rect = Rect(x, y, w, h) self.command = command
class SmartSprite(Sprite): __slots__ = ("_group", "_zindex", "_dirty", "_alpha", "_visible", "damaged", "last_state", "rect", "image") def __init__(self, *args): if not hasattr(self, "image"): self.image = None if not hasattr(self, "rect"): self.rect = Rect(0, 0, 32, 32) self._group = args[0] self._visible = False self._zindex = 0 self._dirty = True self._alpha = 255 self.damaged = False self.damaged_areas = [] self.last_state = None Sprite.__init__(self, *args) # __init__() def __cmp__(self, obj): return cmp(self._zindex, obj.zindex) # __cmp__() def get_dirty(self): return self._dirty # get_dirty() def set_dirty(self, v): self._dirty = v if v: self._group.dirty = True # set_dirty() dirty = property(get_dirty, set_dirty) def get_alpha(self): return self._alpha # get_alpha() def set_alpha(self, v): if v == self._alpha: return self._alpha = v if self.image: self.image.set_alpha(v, RLEACCEL) self.dirty = True # set_alpha() alpha = property(get_alpha, set_alpha) def get_zindex(self): return self._zindex # get_zindex() def set_zindex(self, v): if v == self._zindex: return self._zindex = v # set_zindex() zindex = property(get_zindex, set_zindex) def get_visible(self): return self._visible # get_visible() def set_visible(self, v): if v == self._visible: return self._visible = v self.dirty = True # set_visible() visible = property(get_visible, set_visible) def show(self): self.visible = True # show() def hide(self): self.visible = False # hide() def move(self, x, y): r = self.rect d = False if r.left != x: r.left = x d = True if r.top != y: r.top = y d = True if d: self.dirty = True # move() def move_rel(self, dx, dy): if dx == 0 and dy == 0: return self.rect.move_ip(dx, dy) self.dirty = True # move_rel() def last_state_changed(self): return self.last_state and self.last_state.changed() # last_state_changed() def mouse_click(self, x, y): pass # mouse_click() def __str__(self): return ("%s(rect=%s, zindex=%s, visible=%s, dirty=%s, " "alpha=%s, damaged=%s, group=%s, last_state=%s)" )% \ (self.__class__.__name__, self.rect, self.zindex, self.visible, self.dirty, self.alpha, self.damaged, self._group, self.last_state)
def __init__(self, x, y, r, command, color=(100,100,100)): """ Constructor """ self.r = r self.rect = Rect(x-r, y-r, r*2, r*2) self.command = command self.color = color
for obj in shash.objects: print obj print 'Cell position:' for i in range(len(shash.buckets)): print i,shash.get_cell_grid(i),shash.get_cell_pos(i) print 'Nearby objects:' print ' Reference:', o,shash.cell_ids[o] for obj in shash.get_nearby_objects(o): print ' nearby:',obj,shash.cell_ids[obj] screen = pygame.display.set_mode(world_rect.size) draw_line = pygame.draw.line draw_rect = pygame.draw.rect color = pygame.Color('darkgrey') left,right,top,bottom = world_rect.left,world_rect.right,world_rect.top,world_rect.bottom fill_rect = Rect(0,0,shash.cell_size,shash.cell_size) while 1: pygame.event.clear() screen.fill((0,0,0)) minx = -1 miny = -1 for cell_id,cell in enumerate(shash.itercells()): x,y = shash.get_cell_pos(cell_id) if x > minx: minx = x p1 = x,top p2 = x,bottom draw_line(screen, color, p1, p2) if y > miny: miny = y p1 = left,y
class MapCamera: def __init__(self, x_init_world, y_init_world, width_view_camera, height_view_camera): # rect that represents the surface visible of the camera self.rect_view_camera = Rect(x_init_world, y_init_world, width_view_camera, height_view_camera) self.pos_dest_screen = (0, 0) # Position to draw the map captured by this Camera self.map_handler = None # Controller of the map self.map_tile_surface = None # Surface Buffer that contains the map drawn self.rect_hidden_camera = None # Rect of the surface buffer with pos on map self.following = None self.can_follow = {"left": False, "top": False, "bottom": False, "right": True} # Start the camera setting buffers def init(self): assert self.map_handler is not None, "There's not a " + str(MapHandler.__class__) + " instance " assert self.map_handler.has_map_loaded(), "MapHandler has no map loaded yet!" self.__create_buffer() def __create_buffer(self): self.rect_hidden_camera = create_camera_rect(self.rect_view_camera, self.map_handler.get_tile_size()) self.map_tile_surface = self.map_handler.create_image(self.rect_hidden_camera) def set_pos_screen(self, x_screen, y_screen): # Set position to draw the map on screen self.pos_dest_screen = (x_screen, y_screen) def set_maphandler(self, map_handler): self.map_handler = map_handler # Move camera x y pixels def move(self, x_world, y_world): rect_moved = self.rect_view_camera.move(x_world, y_world) if self.map_handler.is_rect_out_of_map_bounds(rect_moved): return self.rect_view_camera.move_ip(x_world, y_world) if not self.rect_hidden_camera.contains(self.rect_view_camera): # If new pos is out of the buffer, we create a new one! self.__create_buffer() def draw(self, screen): rect_area_visible = Rect(self.rect_view_camera.x - self.rect_hidden_camera.x, self.rect_view_camera.y - self.rect_hidden_camera.y, self.rect_view_camera.width, self.rect_view_camera.height) screen.blit(self.map_tile_surface, self.pos_dest_screen, rect_area_visible) def get_x(self): return self.rect_view_camera.x def get_y(self): return self.rect_view_camera.y def follow(self, player): self.following = player def update(self): if self.following: x_p, y_p = self.following.x, \ self.following.y if self.can_follow['right']: if x_p > self.rect_view_camera.x + self.rect_view_camera.width / 4: rect_moved = self.rect_view_camera.copy() rect_moved.x = x_p - self.rect_view_camera.width / 4 if self.map_handler.is_rect_out_of_map_bounds(rect_moved): return self.rect_view_camera = rect_moved if not self.rect_hidden_camera.contains(self.rect_view_camera): # If new pos is out of the buffer, we create a new one! self.__create_buffer() def is_rect_out_of_camera_bounds(self, rect): return not self.rect_view_camera.contains(rect)
def testEmptyTile(self): baseRect = Rect(7 * TILE_SIZE + 2, 5 * TILE_SIZE + 8, 28, 18) # [1] baseRect.move_ip(0, 0) self.assertEqual(1, len(rpgMap.getSpanTiles(baseRect))) self.assertEqual(True, all(rpgMap.getSpanTiles(baseRect))) self.assertEqual((True, 1), rpgMap.isMoveValid(1, baseRect)) self.assertEqual((False, 2), rpgMap.isMoveValid(2, baseRect)) # [1] [ ] baseRect.move_ip(0, 16) self.assertEqual(2, len(rpgMap.getSpanTiles(baseRect))) self.assertEqual(True, all(rpgMap.getSpanTiles(baseRect))) self.assertEqual((False, 1), rpgMap.isMoveValid(1, baseRect)) self.assertEqual((False, 2), rpgMap.isMoveValid(2, baseRect)) # [ ] baseRect.move_ip(0, 16) self.assertEqual(1, len(rpgMap.getSpanTiles(baseRect))) self.assertEqual(True, all(rpgMap.getSpanTiles(baseRect))) self.assertEqual((False, 1), rpgMap.isMoveValid(1, baseRect)) self.assertEqual((False, 2), rpgMap.isMoveValid(2, baseRect)) # [ ] [1] baseRect.move_ip(0, 16) self.assertEqual(2, len(rpgMap.getSpanTiles(baseRect))) self.assertEqual(True, all(rpgMap.getSpanTiles(baseRect))) self.assertEqual((False, 1), rpgMap.isMoveValid(1, baseRect)) self.assertEqual((False, 2), rpgMap.isMoveValid(2, baseRect)) # [1] baseRect.move_ip(0, 16) self.assertEqual(1, len(rpgMap.getSpanTiles(baseRect))) self.assertEqual(True, all(rpgMap.getSpanTiles(baseRect))) self.assertEqual((True, 1), rpgMap.isMoveValid(1, baseRect)) self.assertEqual((False, 2), rpgMap.isMoveValid(2, baseRect))
def testSpan2_2(self): # horizontally spans only one tile baseRect = Rect(6 * TILE_SIZE + 18, 1 * TILE_SIZE + 8, 28, 18) # [1] [1] baseRect.move_ip(0, 0) self.assertEqual(2, len(rpgMap.getSpanTiles(baseRect))) self.assertEqual((True, 1), rpgMap.isMoveValid(1, baseRect)) self.assertEqual((False, 2), rpgMap.isMoveValid(2, baseRect)) # [1] [1] [1,2] [1,2] baseRect.move_ip(0, 16) self.assertEqual(4, len(rpgMap.getSpanTiles(baseRect))) self.assertEqual((True, 1), rpgMap.isMoveValid(1, baseRect)) self.assertEqual((False, 2), rpgMap.isMoveValid(2, baseRect)) # [1,2] [1,2] baseRect.move_ip(0, 16) self.assertEqual(2, len(rpgMap.getSpanTiles(baseRect))) self.assertEqual((True, 1), rpgMap.isMoveValid(1, baseRect)) self.assertEqual((True, 2), rpgMap.isMoveValid(2, baseRect)) # [1,2] [1,2] [2] [2] baseRect.move_ip(0, 16) self.assertEqual(4, len(rpgMap.getSpanTiles(baseRect))) self.assertEqual((False, 1), rpgMap.isMoveValid(1, baseRect)) self.assertEqual((True, 2), rpgMap.isMoveValid(2, baseRect)) # [2] [2] baseRect.move_ip(0, 16) self.assertEqual(2, len(rpgMap.getSpanTiles(baseRect))) self.assertEqual((False, 1), rpgMap.isMoveValid(1, baseRect)) self.assertEqual((True, 2), rpgMap.isMoveValid(2, baseRect)) # [2] [2] [X] [X] baseRect.move_ip(0, 16) self.assertEqual(4, len(rpgMap.getSpanTiles(baseRect))) self.assertEqual((False, 1), rpgMap.isMoveValid(1, baseRect)) self.assertEqual((False, 2), rpgMap.isMoveValid(2, baseRect)) # [X] [X] baseRect.move_ip(0, 16) self.assertEqual(2, len(rpgMap.getSpanTiles(baseRect))) self.assertEqual((False, 1), rpgMap.isMoveValid(1, baseRect)) self.assertEqual((False, 2), rpgMap.isMoveValid(2, baseRect)) # [X] [X] [1] [1] baseRect.move_ip(0, 16) self.assertEqual(4, len(rpgMap.getSpanTiles(baseRect))) self.assertEqual((False, 1), rpgMap.isMoveValid(1, baseRect)) self.assertEqual((False, 2), rpgMap.isMoveValid(2, baseRect)) # [1] [1] baseRect.move_ip(0, 16) self.assertEqual(2, len(rpgMap.getSpanTiles(baseRect))) self.assertEqual((True, 1), rpgMap.isMoveValid(1, baseRect)) self.assertEqual((False, 2), rpgMap.isMoveValid(2, baseRect))
def testSpan2_1(self): # horizontally spans only one tile baseRect = Rect(5 * TILE_SIZE + 18, 2 * TILE_SIZE + 8, 28, 18) # [1,2] [1,2] [S2] [2] baseRect.move_ip(0, 16) self.assertEqual(4, len(rpgMap.getSpanTiles(baseRect))) self.assertEqual((False, 1), rpgMap.isMoveValid(1, baseRect)) self.assertEqual((False, 1.5), rpgMap.isMoveValid(1.5, baseRect)) self.assertEqual((True, 2), rpgMap.isMoveValid(2, baseRect)) # [S2] [2] baseRect.move_ip(0, 16) self.assertEqual(2, len(rpgMap.getSpanTiles(baseRect))) self.assertEqual((False, 1), rpgMap.isMoveValid(1, baseRect)) self.assertEqual((False, 1.5), rpgMap.isMoveValid(1.5, baseRect)) self.assertEqual((True, 2), rpgMap.isMoveValid(2, baseRect)) # [S2] [2] [S1.5] [X] baseRect.move_ip(0, 16) self.assertEqual(4, len(rpgMap.getSpanTiles(baseRect))) self.assertEqual((False, 1), rpgMap.isMoveValid(1, baseRect)) self.assertEqual((False, 1.5), rpgMap.isMoveValid(1.5, baseRect)) self.assertEqual((False, 2), rpgMap.isMoveValid(2, baseRect)) self.assertEqual((True, 2, -1), rpgMap.isVerticalValid(1.5, baseRect)) self.assertEqual((True, 2, -1), rpgMap.isVerticalValid(2, baseRect)) self.assertEqual((True, 2, -1), rpgMap.isHorizontalValid(2, baseRect)) # [S1.5] [X] baseRect.move_ip(0, 16) self.assertEqual(2, len(rpgMap.getSpanTiles(baseRect))) self.assertEqual((False, 1), rpgMap.isMoveValid(1, baseRect)) self.assertEqual((False, 1.5), rpgMap.isMoveValid(1.5, baseRect)) self.assertEqual((False, 2), rpgMap.isMoveValid(2, baseRect)) self.assertEqual((True, 1.5, -1), rpgMap.isVerticalValid(1, baseRect)) self.assertEqual((True, 1.5, -1), rpgMap.isVerticalValid(1.5, baseRect)) self.assertEqual((False, 1.5, 0), rpgMap.isHorizontalValid(1.5, baseRect)) # [S1.5] [X] [S1.5] [1] baseRect.move_ip(0, 16) self.assertEqual(4, len(rpgMap.getSpanTiles(baseRect))) self.assertEqual((False, 1), rpgMap.isMoveValid(1, baseRect)) self.assertEqual((False, 1.5), rpgMap.isMoveValid(1.5, baseRect)) self.assertEqual((False, 2), rpgMap.isMoveValid(2, baseRect)) self.assertEqual((True, 1.5, -1), rpgMap.isVerticalValid(1, baseRect)) self.assertEqual((True, 1.5, -1), rpgMap.isVerticalValid(1.5, baseRect)) self.assertEqual((False, 1.5, -1), rpgMap.isHorizontalValid(1.5, baseRect)) # [S1.5] [1] baseRect.move_ip(0, 16) self.assertEqual(2, len(rpgMap.getSpanTiles(baseRect))) self.assertEqual((False, 1), rpgMap.isMoveValid(1, baseRect)) self.assertEqual((False, 1.5), rpgMap.isMoveValid(1.5, baseRect)) self.assertEqual((False, 2), rpgMap.isMoveValid(2, baseRect)) self.assertEqual((True, 1, 1), rpgMap.isVerticalValid(1, baseRect)) self.assertEqual((True, 1.5, -1), rpgMap.isVerticalValid(1.5, baseRect)) self.assertEqual((False, 1.5, 0), rpgMap.isHorizontalValid(1.5, baseRect)) # [S1.5] [1] [S1] [1] baseRect.move_ip(0, 16) self.assertEqual(4, len(rpgMap.getSpanTiles(baseRect))) self.assertEqual((False, 1), rpgMap.isMoveValid(1, baseRect)) self.assertEqual((False, 1.5), rpgMap.isMoveValid(1.5, baseRect)) self.assertEqual((False, 2), rpgMap.isMoveValid(2, baseRect)) self.assertEqual((True, 1, 1), rpgMap.isVerticalValid(1, baseRect)) self.assertEqual((True, 1, -1), rpgMap.isVerticalValid(1.5, baseRect)) self.assertEqual((True, 1, 1), rpgMap.isHorizontalValid(1, baseRect)) # [S1] [1] baseRect.move_ip(0, 16) self.assertEqual(2, len(rpgMap.getSpanTiles(baseRect))) self.assertEqual((True, 1), rpgMap.isMoveValid(1, baseRect)) self.assertEqual((False, 1.5), rpgMap.isMoveValid(1.5, baseRect)) self.assertEqual((False, 2), rpgMap.isMoveValid(2, baseRect)) # [S1] [1] [1] [1] baseRect.move_ip(0, 16) self.assertEqual(4, len(rpgMap.getSpanTiles(baseRect))) self.assertEqual((True, 1), rpgMap.isMoveValid(1, baseRect)) self.assertEqual((False, 1.5), rpgMap.isMoveValid(1.5, baseRect)) self.assertEqual((False, 2), rpgMap.isMoveValid(2, baseRect)) # [1] [1] baseRect.move_ip(0, 16) self.assertEqual(2, len(rpgMap.getSpanTiles(baseRect))) self.assertEqual((True, 1), rpgMap.isMoveValid(1, baseRect)) self.assertEqual((False, 2), rpgMap.isMoveValid(2, baseRect))
def testSpan1_1(self): # horizontally spans only one tile baseRect = Rect(5 * TILE_SIZE + 2, 2 * TILE_SIZE + 8, 28, 18) # [1,2] [S2] baseRect.move_ip(0, 16) self.assertEqual(2, len(rpgMap.getBaseRectTiles(baseRect))) self.assertEqual((False, 1), rpgMap.isMoveValid(1, baseRect)) self.assertEqual((False, 1.5), rpgMap.isMoveValid(1.5, baseRect)) self.assertEqual((True, 2), rpgMap.isMoveValid(2, baseRect)) # [S2] baseRect.move_ip(0, 16) self.assertEqual(1, len(rpgMap.getBaseRectTiles(baseRect))) self.assertEqual((False, 1), rpgMap.isMoveValid(1, baseRect)) self.assertEqual((True, 2), rpgMap.isMoveValid(1.5, baseRect)) self.assertEqual((True, 2), rpgMap.isMoveValid(2, baseRect)) # [S2] [S1.5] baseRect.move_ip(0, 16) self.assertEqual(2, len(rpgMap.getBaseRectTiles(baseRect))) self.assertEqual((False, 1), rpgMap.isMoveValid(1, baseRect)) self.assertEqual((True, 2), rpgMap.isMoveValid(1.5, baseRect)) self.assertEqual((True, 2), rpgMap.isMoveValid(2, baseRect)) # [S1.5] baseRect.move_ip(0, 16) self.assertEqual(1, len(rpgMap.getBaseRectTiles(baseRect))) self.assertEqual((True, 1.5), rpgMap.isMoveValid(1, baseRect)) self.assertEqual((True, 1.5), rpgMap.isMoveValid(1.5, baseRect)) self.assertEqual((True, 1.5), rpgMap.isMoveValid(2, baseRect)) # [S1.5] [S1.5] baseRect.move_ip(0, 16) self.assertEqual(2, len(rpgMap.getBaseRectTiles(baseRect))) self.assertEqual((True, 1.5), rpgMap.isMoveValid(1, baseRect)) self.assertEqual((True, 1.5), rpgMap.isMoveValid(1.5, baseRect)) self.assertEqual((True, 1.5), rpgMap.isMoveValid(2, baseRect)) # [S1.5] baseRect.move_ip(0, 16) self.assertEqual(1, len(rpgMap.getBaseRectTiles(baseRect))) self.assertEqual((True, 1.5), rpgMap.isMoveValid(1, baseRect)) self.assertEqual((True, 1.5), rpgMap.isMoveValid(1.5, baseRect)) self.assertEqual((True, 1.5), rpgMap.isMoveValid(2, baseRect)) # [S1.5] [S1] baseRect.move_ip(0, 16) self.assertEqual(2, len(rpgMap.getBaseRectTiles(baseRect))) self.assertEqual((True, 1), rpgMap.isMoveValid(1, baseRect)) self.assertEqual((True, 1), rpgMap.isMoveValid(1.5, baseRect)) self.assertEqual((False, 2), rpgMap.isMoveValid(2, baseRect)) # [S1] baseRect.move_ip(0, 16) self.assertEqual(1, len(rpgMap.getBaseRectTiles(baseRect))) self.assertEqual((True, 1), rpgMap.isMoveValid(1, baseRect)) self.assertEqual((True, 1), rpgMap.isMoveValid(1.5, baseRect)) self.assertEqual((False, 2), rpgMap.isMoveValid(2, baseRect)) # [S1] [1] baseRect.move_ip(0, 16) self.assertEqual(2, len(rpgMap.getBaseRectTiles(baseRect))) self.assertEqual((True, 1), rpgMap.isMoveValid(1, baseRect)) self.assertEqual((False, 1.5), rpgMap.isMoveValid(1.5, baseRect)) self.assertEqual((False, 2), rpgMap.isMoveValid(2, baseRect)) # [1] baseRect.move_ip(0, 16) self.assertEqual(1, len(rpgMap.getBaseRectTiles(baseRect))) self.assertEqual((True, 1), rpgMap.isMoveValid(1, baseRect)) self.assertEqual((False, 2), rpgMap.isMoveValid(2, baseRect))
class Entity: def __init__(self): self.Sprite = Sprite.Sprite() self.start = (0, 0) self.end = (0, 0) self.dim = Rect(0, 0, 0, 0) self.on = False self.shaders = ("", "") self.anim_rate= -1 self.anim_fn = "" # Various entity attributes self.phyz = False self.anim = False self.static = False self.p_spawn = False self.e_spawn = False def Load(self, filename=None, surface=None): if(filename): self.Sprite.Load(filename=filename) elif surface: self.Sprite.Load(surface=surface) return self def Update(self, x, y): if not self.on: return self.Sprite.Move(x, y) self.end = (x, y) def Pan(self, x, y): self.start = (self.start[0] + x, self.start[1] + y) self.end = (self.end[0] + x, self.end[1] + y) self.dim.x += x self.dim.y += y def Enable(self, x, y): self.on = True self.start = (x, y) self.end = (x, y) self.dim.x = x self.dim.y = y def Disable(self, x, y): self.on = False def Collide(self, rect): return self.dim.colliderect(rect) def Render(self, screen): # Calculate how many should be rendered. count_x = abs(self.start[0] - self.end[0]) / self.Sprite.GetW() count_y = abs(self.start[1] - self.end[1]) / self.Sprite.GetH() # Fix dimensions. self.dim.topleft = self.start self.dim.w = (count_x + 1) * self.Sprite.GetW() self.dim.h = (count_y + 1) * self.Sprite.GetH() # Render count_x * count_y copies. for x in xrange(count_x + 1): for y in xrange(count_y + 1): coord = (self.start[0] + (x * self.Sprite.GetW()), \ (self.start[1] + (y * self.Sprite.GetH()))) screen.blit(self.Sprite.GetSprite(), coord) return self def BuildMeshString(self): return MESH_FORMAT % \ (self.GetW(), self.GetW(), self.GetH(), self.GetH(), \ self.GetH() / (1.0 * self.Sprite.GetH()), \ self.GetW() / (1.0 * self.Sprite.GetW()), \ self.GetH() / (1.0 * self.Sprite.GetH()), \ self.GetW() / (1.0 * self.Sprite.GetW()), \ os.path.splitext(os.path.basename(self.Sprite.GetFilename()))[0] + ".tga") def TogglePhysics(self):self.phyz = not self.phyz; return self.phyz def ToggleStatic(self): self.static = not self.static; return self.static def TogglePSpawn(self): self.p_spawn = not self.p_spawn; return self.p_spawn def ToggleESpawn(self): self.e_spawn = not self.e_spawn; return self.e_spawn def IsAnimation(self): return self.anim def IsPhysical(self): return self.phyz def IsStatic(self): return self.static def IsSpawn(self): return self.p_spawn or self.e_spawn def HasShader(self): return self.shaders[0] != "" or self.shaders[1] != "" def GetX(self): return self.start[0] def GetY(self): return self.start[1] def GetW(self): return self.dim.w def GetH(self): return self.dim.h def _GetRect(self): return self.dim def GetFilename(self): return self.Sprite.GetFilename() def GetVShader(self): return self.shaders[0] def GetFShader(self): return self.shaders[1] def ToggleAnimation(self): self.anim = not self.anim; return self.anim def GetAnimationFilename(self): return self.anim_fn def GetAnimationRate(self): return self.anim_rate