def __init__(self, Level): Hud.__init__(self, Level) # Tableau contenant la définition des clefs self.level_keys = [[ constants.HUDYELLOWKEY, constants.POSHUDKEY1_X, constants.POSHUDKEY_Y ]] for key in self.level_keys: temp_key = SpriteSheet(key[0][0]) temp_key.rect.x = key[1] temp_key.rect.y = key[2] self.keys_list.add(temp_key) self.level_coin = [[ constants.HUDCOIN, constants.POSHUDCOIN_X, constants.POSHUDCOIN_Y ]] for coin in self.level_coin: temp_coin = SpriteSheet(coin[0]) temp_coin.rect.x = coin[1] temp_coin.rect.y = coin[2] self.coin_list.add(temp_coin) self.score_text = self.font.render( " : " + str(levels.Level_01.picked_coins) + " / " + str(constants.LEVEL1TOTALCOIN), 1, (96, 96, 96))
def __init__(self, scene, x, y): super().__init__(scene, x, y) self.groups = scene.all_sprites, scene.hud pygame.sprite.Sprite.__init__(self, self.groups) self.sprite_sheet = SpriteSheet(INVENTORY_SPRITESHEET) self.image = self.sprite_sheet.get_image(0, 0, 32, 32) self.item_list = []
class Player(pygame.sprite.Sprite): def __init__(self,posx,posy,imgindex): pygame.sprite.Sprite.__init__(self) global playerimagePath self.posx = posx self.posy = 600 - posy self.pos = vec(posx,posy) self.velocity = vec(8,0) self.gravity = vec(0,1) self.step = 8 self.spritesheet = SpriteSheet(playerimagePath) self.image = self.spritesheet.get_image(imgindex) self.image.set_colorkey((247,247,247)) self.rect = self.image.get_rect() self.rect.center = (posx,posy) self.move_f = False self.move_b = False self.move_u = False self.grounded = False def update(self,spritegroup,coin_sprites): pygame.sprite.spritecollide(self,coin_sprites,True) self.gravity.y = 1 hits = pygame.sprite.spritecollide(self,spritegroup,False) if hits and self.velocity.y>=0: self.pos.y = hits[0].rect.top + 1 self.velocity.y = 0 self.gravity.y = 0 if self.move_u: self.move_u = False else: self.gravity.y = 1 self.velocity.y += self.gravity.y self.pos.y += self.velocity.y + 0.5*self.gravity.y self.rect.midbottom = self.pos def move(self,dx,moveindex): if not self.move_u: if dx == 1: self.image = self.spritesheet.get_image(moveindex) self.pos.x += dx*self.velocity.x else: self.image = self.spritesheet.get_image(moveindex) self.image = pygame.transform.flip(self.image,True,False) self.pos.x += dx*self.velocity.x else: self.pos.x += dx*self.velocity.x def player_jump(self): if self.move_u: self.velocity.y += self.gravity.y self.pos.y += self.velocity.y + 0.5 * self.gravity.y
def __init__(self): super().__init__() # Définition des sprites IDLE du joueur sprite_sheet = SpriteSheet(constants.FIDLE1) self.idle_frames_r.append(sprite_sheet.image) self.idle_frames_l.append( pygame.transform.flip(sprite_sheet.image, True, False)) sprite_sheet = SpriteSheet(constants.FIDLE2) self.idle_frames_r.append(sprite_sheet.image) self.idle_frames_l.append( pygame.transform.flip(sprite_sheet.image, True, False)) # Définition des sprites RUNNING du joueur sprite_sheet = SpriteSheet(constants.FRUN1) self.walking_frames_r.append(sprite_sheet.image) self.walking_frames_l.append( pygame.transform.flip(sprite_sheet.image, True, False)) sprite_sheet = SpriteSheet(constants.FRUN2) self.walking_frames_r.append(sprite_sheet.image) self.walking_frames_l.append( pygame.transform.flip(sprite_sheet.image, True, False)) sprite_sheet = SpriteSheet(constants.FRUN3) self.walking_frames_r.append(sprite_sheet.image) self.walking_frames_l.append( pygame.transform.flip(sprite_sheet.image, True, False)) sprite_sheet = SpriteSheet(constants.FRUN4) self.walking_frames_r.append(sprite_sheet.image) self.walking_frames_l.append( pygame.transform.flip(sprite_sheet.image, True, False)) sprite_sheet = SpriteSheet(constants.FRUN5) self.walking_frames_r.append(sprite_sheet.image) self.walking_frames_l.append( pygame.transform.flip(sprite_sheet.image, True, False)) sprite_sheet = SpriteSheet(constants.FRUN6) self.walking_frames_r.append(sprite_sheet.image) self.walking_frames_l.append( pygame.transform.flip(sprite_sheet.image, True, False)) # Définition des sprites JUMP du joueur sprite_sheet = SpriteSheet(constants.FUP) self.jump_frames.append(sprite_sheet.image) self.jump_frames.append( pygame.transform.flip(sprite_sheet.image, True, False)) sprite_sheet = SpriteSheet(constants.FDOWN) self.jump_frames.append(sprite_sheet.image) self.jump_frames.append( pygame.transform.flip(sprite_sheet.image, True, False)) # Sélectionne l'image de départ self.image = self.idle_frames_r[0] # Récupère la zone de collision du personnage et la réduit à la largeur de ses pieds self.rect_image = self.image.get_rect() self.rect = pygame.Rect(constants.PLAYERLEFT, constants.PLAYERTOP, constants.PLAYERWIDTH, constants.PLAYERHEIGHT)
def __init__(self, scene, x, y, orientation, moves): super().__init__(scene, x, y, orientation, moves) self.groups = scene.all_sprites, scene.enemies pygame.sprite.Sprite.__init__(self, self.groups) self.health = 2 sprite_sheet = SpriteSheet(GHOST_SPRITE_SHEET) self.image = sprite_sheet.get_image(0, 0, 32, 32) self.walking_up = [] self.walking_down = [] self.walking_left = [] self.walking_right = [] # Append sprites to walking arrays for x in range(0, 33, 32): self.walking_right.append(sprite_sheet.get_image(x, 0, 32, 32)) self.walking_left.append(sprite_sheet.get_image(x, 32, 32, 32)) self.walking_down.append(sprite_sheet.get_image(x, 64, 32, 32)) self.walking_up.append(sprite_sheet.get_image(x, 96, 32, 32)) self.damage_up = [] self.damage_down = [] self.damage_left = [] self.damage_right = [] # Append sprites to damage arrays for x in range(64, 128, 32): self.damage_right.append(sprite_sheet.get_image(x, 0, 32, 32)) self.damage_left.append(sprite_sheet.get_image(x, 32, 32, 32)) self.damage_down.append(sprite_sheet.get_image(x, 64, 32, 32)) self.damage_up.append(sprite_sheet.get_image(x, 96, 32, 32))
def __init__(self,posx,posy,rect,resize = None): global coinimagepath pygame.sprite.Sprite.__init__(self) self.spritesheet = SpriteSheet(coinimagepath) if resize == None: self.image = self.spritesheet.get_bgsprites(rect) else: self.image = self.spritesheet.get_bgsprites(rect,resize) self.rect = self.image.get_rect() self.rect.x = posx self.rect.y = posy
def __init__(self,posx,posy,rect,resize = None): pygame.sprite.Sprite.__init__(self) global floorimagePath self.spritesheet = SpriteSheet(floorimagePath) if resize==None: self.image = self.spritesheet.get_floor(rect) else: self.image = self.spritesheet.get_floor(rect,resize) self.rect = self.image.get_rect() self.rect.x = posx self.rect.y = posy
class bgSprites(pygame.sprite.Sprite): def __init__(self,posx,posy,rect,resize = None): global bgimagepath pygame.sprite.Sprite.__init__(self) self.spritesheet = SpriteSheet(bgimagepath) if resize == None: self.image = self.spritesheet.get_bgsprites(rect) else: self.image = self.spritesheet.get_bgsprites(rect,resize) self.rect = self.image.get_rect() self.rect.x = posx self.rect.y = 600 - posy - self.rect.height
def change_key(self, sprite): for key in self.keys_list: if sprite.rect.width == key.rect.width: self.keys_list.remove(key) for key in self.level_keys: temp_key = SpriteSheet(key[0][0]) if sprite.rect.width == temp_key.rect.width: temp = key[0][0] key[0][0] = key[0][1] key[0][1] = temp temp_key = SpriteSheet(key[0][0]) temp_key.rect.x = key[1] temp_key.rect.y = key[2] self.keys_list.add(temp_key)
def __init__(self, scene, x, y, orientation, moves): super().__init__(scene, x, y) self.groups = scene.all_sprites, scene.enemies pygame.sprite.Sprite.__init__(self, self.groups) self.orientation = orientation self.moves = moves self.interactable = False self.collidable = False self.move_counter = 0 self.move_counter_increment = 1 self.reverse = False self.health = 1 self.hit = False self.hit_detected = False self.attacking = False self.attack_detected = False if len(moves) > 0: self.direction = None # Animation self.animation_index = 0 self.update_delay = ENEMY_SPEED self.attack_delay = ENEMY_ATTACK_DELAY self.last_update = pygame.time.get_ticks() self.last_idle_update = pygame.time.get_ticks() self.hit_delay = HIT_DELAY sprite_sheet = SpriteSheet(BAT_SPRITE_SHEET) self.image = sprite_sheet.get_image(0, 0, 32, 32) self.walking_up = [] self.walking_down = [] self.walking_left = [] self.walking_right = [] # Append sprites to walking arrays for x in range(0, 33, 32): self.walking_right.append(sprite_sheet.get_image(x, 0, 32, 32)) self.walking_left.append(sprite_sheet.get_image(x, 32, 32, 32)) self.walking_down.append(sprite_sheet.get_image(x, 64, 32, 32)) self.walking_up.append(sprite_sheet.get_image(x, 96, 32, 32)) self.damage_up = [] self.damage_down = [] self.damage_left = [] self.damage_right = [] # Append sprites to damage arrays for x in range(64, 128, 32): self.damage_right.append(sprite_sheet.get_image(x, 0, 32, 32)) self.damage_left.append(sprite_sheet.get_image(x, 32, 32, 32)) self.damage_down.append(sprite_sheet.get_image(x, 64, 32, 32)) self.damage_up.append(sprite_sheet.get_image(x, 96, 32, 32))
def __init__(self, scene, x, y): super().__init__(scene, x, y) self.groups = scene.all_sprites, scene.items, scene.keys # Animation self.animation_index = 0 self.last_update = pygame.time.get_ticks() self.update_delay = KEY_IDLE_DELAY self.animation = [] sprite_sheet = SpriteSheet(KEY_SPRITESHEET) self.image = sprite_sheet.get_image(0, 0, 32, 32) # Append sprites to animation array for x in range(0, 65, 32): self.animation.append(sprite_sheet.get_image(x, 0, 32, 32))
def __init__(self,posx,posy,imgindex): pygame.sprite.Sprite.__init__(self) global playerimagePath self.posx = posx self.posy = 600 - posy self.pos = vec(posx,posy) self.velocity = vec(8,0) self.gravity = vec(0,1) self.step = 8 self.spritesheet = SpriteSheet(playerimagePath) self.image = self.spritesheet.get_image(imgindex) self.image.set_colorkey((247,247,247)) self.rect = self.image.get_rect() self.rect.center = (posx,posy) self.move_f = False self.move_b = False self.move_u = False self.grounded = False
class Inventory(GameObject): def __init__(self, scene, x, y): super().__init__(scene, x, y) self.groups = scene.all_sprites, scene.hud pygame.sprite.Sprite.__init__(self, self.groups) self.sprite_sheet = SpriteSheet(INVENTORY_SPRITESHEET) self.image = self.sprite_sheet.get_image(0, 0, 32, 32) self.item_list = [] def update(self): if len(self.item_list) > 0: if type(self.item_list[0]) == Key: self.image = self.sprite_sheet.get_image(0, 32, 32, 32) else: self.image = self.sprite_sheet.get_image(0, 0, 32, 32) self.rect.x = self.x * TILESIZE self.rect.y = self.y * TILESIZE
def __init__(self, nome: str, x: int, y: int, velx: int, vida: int): ##### ATRIBUTOS GERAIS ##### self.__vida = 10 self.__nome = nome self.__imagem = SpriteSheet("andando") ##### ATRIBUTOS POSICIONAIS ##### self.__x = x self.__y = y self.__altura = 46 self.__largura = 46 self.__velx = velx self.__vely = 0 self.__face = 1 self.__corpo = pygame.Rect(self.__x, self.__y, self.__largura, self.__altura) ##### ATRIBUTOS COMPORTAMENTAIS ##### self.__poder = PretoDoNinja() self.__recarga = 0
def draw_mc_hp(surface, destination, x, y, perc_hp): # draw hearts in mc fov, updates in quarter incriments if perc_hp < 0: perc_hp = 0 sprite_sheet = SpriteSheet(mc_hud_gfx) full_image = sprite_sheet.get_image(63, 0, 16, 16) three_quarters_image = sprite_sheet.get_image(79, 0, 16, 16) half_image = sprite_sheet.get_image(95, 0, 16, 16) quarter_image = sprite_sheet.get_image(111, 0, 16, 16) empty_image = sprite_sheet.get_image(127, 0, 16, 16) if perc_hp == 1.0: image = full_image elif perc_hp > .75: image = three_quarters_image elif perc_hp > .50: image = half_image elif perc_hp > .25: image = quarter_image else: image = empty_image surface.blit(image, [x, y])
def draw_mc_level(surface, destination, x, y, level): # draws numbers represeting the level, currently capped at 9 # displays a 0 for anything above 9 sprite_sheet = SpriteSheet(mc_hud_gfx) images = [ sprite_sheet.get_image(80, 224, 16, 16), sprite_sheet.get_image(96, 224, 16, 16), sprite_sheet.get_image(112, 224, 16, 16), sprite_sheet.get_image(128, 224, 16, 16), sprite_sheet.get_image(80, 240, 16, 16), sprite_sheet.get_image(96, 240, 16, 16), sprite_sheet.get_image(112, 240, 16, 16), sprite_sheet.get_image(128, 240, 16, 16), sprite_sheet.get_image(80, 256, 16, 16), sprite_sheet.get_image(96, 256, 16, 16), ] if level <= 9: image = images[level - 1] else: image = images[:-1] surface.blit(image, [x, y])
def load_data(self): """Loads all necessary data. Highscore, spritesheets, images, sounds. """ self.dir = os.path.dirname(__file__) self.img_dir = os.path.join(self.dir, 'images') self.sound_dir = os.path.join(self.dir, 'sounds') self.comic_dir = os.path.join(self.dir, 'Comic Strips') # load high score try: # if file exists, load data with open(os.path.join(self.dir, s.HS_FILE), 'r') as f: self.highscore = int(f.read()) except Exception: # else create new file and set highscore to 0 with open(os.path.join(self.dir, s.HS_FILE), 'w') as f: self.highscore = 0 # load spritesheets self.enemy_spritesheet = SpriteSheet( os.path.join(self.img_dir, s.ENEMY_SPRITESHEET)) self.hud_spritesheet = SpriteSheet( os.path.join(self.img_dir, s.HUD_SPRITESHEET)) self.expl_spritesheet = SpriteSheet( os.path.join(self.img_dir, s.EXPL_SPRITESHEET)) self.plat_spritesheet = SpriteSheet( os.path.join(self.img_dir, s.PLAT_SPRITESHEET)) self.bac_spritesheet = SpriteSheet( os.path.join(self.img_dir, s.BAC_SPRITESHEET)) # load base image self.base_img = pygame.image.load( os.path.join(self.img_dir, 'grassCenter.png')).convert() # load virus image virus_image = pygame.image.load( os.path.join(self.img_dir, 'coronavirus.png')).convert() rect = virus_image.get_rect() self.virus_image = pygame.transform.scale( virus_image, (rect.width * 2, rect.height * 2)) self.virus_image.set_colorkey(s.BLACK) # load pause screen image image = pygame.image.load(os.path.join(self.img_dir, 'pausescreen.jpg')).convert() self.pause_image = pygame.transform.scale(image, (s.WIDTH, s.HEIGHT)) # load mission screen image image = pygame.image.load(os.path.join(self.img_dir, 'mis_screen.jpg')).convert() self.mis_image = pygame.transform.scale(image, (s.WIDTH, s.HEIGHT)) # load mission failed image image = pygame.image.load(os.path.join(self.img_dir, 'mis_failed.jpg')).convert() self.mis_failed_image = pygame.transform.scale(image, (s.WIDTH, s.HEIGHT)) # load mission completed image image = pygame.image.load(os.path.join(self.img_dir, 'mis_success.jpg')).convert() self.mis_completed_img = pygame.transform.scale( image, (s.WIDTH, s.HEIGHT)) # load cloud images self.cloud_images = [] cloud_dir = os.path.join(self.img_dir, 'clouds') for i in range(1, 4): self.cloud_images.append( pygame.image.load(os.path.join(cloud_dir, f'cloud{i}.png')).convert()) # load comic strips self.comic_strips = [] for i in range(1, 17): image = pygame.image.load( os.path.join(self.comic_dir, f'scene_{i}.png')).convert() image = pygame.transform.scale(image, (s.WIDTH, s.HEIGHT)) self.comic_strips.append(image) # load sounds self.jump_sound = pygame.mixer.Sound( os.path.join(self.sound_dir, 'jump.wav')) self.powerup_sound = pygame.mixer.Sound( os.path.join(self.sound_dir, 'powerup.wav')) self.dead_sound = pygame.mixer.Sound( os.path.join(self.sound_dir, 'dead.wav')) self.bullet_sound = pygame.mixer.Sound( os.path.join(self.sound_dir, 'bullet.wav'))
class Jogador: def __init__(self, nome: str, x: int, y: int, velx: int, vida: int): ##### ATRIBUTOS GERAIS ##### self.__vida = 10 self.__nome = nome self.__imagem = SpriteSheet("andando") ##### ATRIBUTOS POSICIONAIS ##### self.__x = x self.__y = y self.__altura = 46 self.__largura = 46 self.__velx = velx self.__vely = 0 self.__face = 1 self.__corpo = pygame.Rect(self.__x, self.__y, self.__largura, self.__altura) ##### ATRIBUTOS COMPORTAMENTAIS ##### self.__poder = PretoDoNinja() self.__recarga = 0 @property def nome(self): return self.__nome @nome.setter def nome(self, nome): self.__nome = nome @property def x(self): return self.__x @property def y(self): return self.__y @property def velx(self): return self.__velx @velx.setter def velx(self, velx): self.__velx = velx @property def velocidade_max(self): return self.__velmax @velocidade_max.setter def velocidade_max(self, velocidade_max): self.__velmax = velocidade_max @property def corpo(self): return self.__corpo @property def poder(self): return self.__poder @poder.setter def poder(self, poder): self.__poder = poder @property def vida(self): return self.__vida @property def face(self): return self.__face def vida_pra_zero(self): self.__vida = 0 def checar_colisao(self, lista_de_entidades, tipos_transparentes): ##### COLISOES ##### obsBaixo, obsCima, obsEsquerda, obsDireita = 0, 0, 0, 0 ##### COLISOES COM OBSTACULOS ##### for entidade in lista_de_entidades: if entidade != self and not type(entidade) in tipos_transparentes: cCima, cBaixo, cEsquerda, cDireita = False, False, False, False if self.__velx < 0: # movimento para a esquerda cveloz_left = self.corpo.left - 1 + self.__velx cveloz_largura = self.corpo.right - cveloz_left + 1 else: # movimento para a direita cveloz_left = self.corpo.left - 1 cveloz_largura = self.corpo.right - cveloz_left + 1 + self.__velx if self.__vely < 0: # movimento para cima cveloz_top = self.corpo.top - 1 + self.__vely cveloz_altura = self.corpo.bottom - cveloz_top + 1 else: # movimento para baixo cveloz_top = self.corpo.top cveloz_altura = self.corpo.bottom - cveloz_top + 1 + self.__vely self.__corpoveloz = pygame.Rect(cveloz_left, cveloz_top, cveloz_largura, cveloz_altura) colisaoVeloz = self.__corpoveloz.colliderect(entidade.corpo) if colisaoVeloz: # CALCULO DE O QUAO DENTRO O OBJETO TA HORIZONTALMENTE E VERTICALMENTE ##### VERTICIAIS ##### dist_y = 0 if not self.__vely: # parado dist_y = min( self.__corpoveloz.bottom - entidade.corpo.top, entidade.corpo.bottom - self.__corpoveloz.top) elif self.__vely > 0: # caindo dist_y = self.__corpoveloz.bottom - entidade.corpo.top else: # subindo dist_y = entidade.corpo.bottom - self.__corpoveloz.top dist_x = 0 ##### HORIZONTAL ##### if not self.__velx: # parado dist_x = min( entidade.corpo.right - self.__corpoveloz.left, self.__corpoveloz.right - entidade.corpo.left) # colisao a direita = + elif self.__velx > 0: # movimentacao pra direita dist_x = self.__corpoveloz.right - entidade.corpo.left else: # movimentacao pra esquerda dist_x = entidade.corpo.right - self.__corpoveloz.left if self.__vely >= 0 and dist_x + self.__largura / 2 >= dist_y: cBaixo = True elif self.__vely < 0 and dist_x + self.__largura / 2 >= dist_y: cCima = True elif self.__velx > 0 and dist_x < dist_y: cDireita = True elif self.__velx < 0 and dist_x < dist_y: cEsquerda = True elif not self.__velx and abs(dist_x) < dist_y: if self.__corpoveloz.right - entidade.corpo.left > entidade.corpo.right - self.__corpoveloz.left: cEsquerda = True else: cDireita = True # Essa checagem em dois passos tem que ocorrer por que se nao ele so salva a colisao com o utlimo obstaculo if cCima: obsCima = entidade if cBaixo: obsBaixo = entidade if cEsquerda: obsEsquerda = entidade if cDireita: obsDireita = entidade return [obsCima, obsBaixo, obsDireita, obsEsquerda] def coletar(self, item): if isinstance(item, PoderNoMapa): self.poder = item.poder_atribuido def renderizar(self, tela, campo_visivel, ciclo): if renderizar_hitbox: pygame.draw.rect(tela, (0, 0, 0), [ self.corpo.x - campo_visivel.x, self.corpo.y, self.corpo.w, self.corpo.h ]) if renderizar_sprite: self.__imagem.imprimir("andando" + str(ciclo % 12), self.__x - campo_visivel.x, self.__y, tela, self.__face) def atualizar(self, screen, campo_visivel, ciclo): ### REQUER AREA VISIVEL PARA RENDERIZAR self.renderizar(screen, campo_visivel, ciclo) if self.__recarga > 0: self.__recarga -= 1 if self.__poder != '': self.__poder.atualizar(screen, campo_visivel) if self.x > campo_visivel.x + 600: return pygame.Rect(self.x - 600, 0, campo_visivel.w, campo_visivel.h) elif self.x < campo_visivel.x + 400: return pygame.Rect( self.x - 400, 0, campo_visivel.w, campo_visivel.h) if campo_visivel.x > 0 else pygame.Rect( 0, 0, campo_visivel.w, campo_visivel.h) return campo_visivel def mover(self, direita, esquerda, espaco, screen, mapa, atrito): ##### MOVIMENTO HORIZONTAL ##### aceleracao = (direita - esquerda) self.__velx += aceleracao ##### COLISOES ##### coletaveis = [OrbeDoMago, ShurikenDoNinja] #Tipos coletaveis #0-Cima, 1-Baixo, 2-Direita, 3-Esquerda obstaculos = self.checar_colisao(mapa.lista_de_entidades, [BolaFogo]) ##### COLETA ITENS ##### for i in range(len(obstaculos)): if type(obstaculos[i]) in coletaveis: self.coletar(obstaculos[i]) obstaculos[i].auto_destruir(mapa) obstaculos[i] = False ##### REPOSICIONAMENTO POS COLISAO ##### if obstaculos[2] and obstaculos[3]: #ESMAGAMENTO self.__vida = 0 #AQUI EH TESTE N SEI SE ESSA VARIAVEL VAI FICAR COMO STRING MSM if obstaculos[3]: #print("COLISAO PELA ESQUERDA", obsEsquerda.nome) if self.__velx <= 0: self.__velx = 0 aceleracao = 0 self.__x = obstaculos[3].corpo.right + 1 if obstaculos[2]: #print("COLISAO PELA DIREITA", obsDireita.nome) if self.__velx >= 0: self.__velx = 0 aceleracao = 0 self.__x = obstaculos[2].corpo.left - self.__largura if obstaculos[1]: self.__vely = 0 self.__y = obstaculos[1].corpo.top - self.__altura if espaco: self.__vely = -self.poder.pulo if obstaculos[0]: if self.__vely < 0: self.__vely = 0 self.__y = obstaculos[0].corpo.bottom #### COLISAO GOOMBA #### for cada_termo in mapa.lista_de_entidades: if isinstance(cada_termo, Goomba): entidade = cada_termo if obstaculos[3] != 0: if isinstance(obstaculos[3], Goomba): self.__vida -= entidade.dano_contato if obstaculos[2] != 0: if isinstance(obstaculos[2], Goomba): self.__vida -= entidade.dano_contato ### CHECANDO VITÓRIA ### for cada_termo in mapa.lista_de_entidades: if isinstance(cada_termo, Vitoria): entidade = cada_termo if obstaculos[3] != 0: if isinstance(obstaculos[3], Vitoria): mapa.ganhou = True if obstaculos[2] != 0: if isinstance(obstaculos[2], Vitoria): mapa.ganhou = True if obstaculos[1] != 0: if isinstance(obstaculos[1], Vitoria): mapa.ganhou = True ##### GRAVIDADE ###### if not obstaculos[1]: self.__vely += gravidade ##### ATRITO ###### if aceleracao == 0: if self.__velx < 0: self.__velx += atrito elif self.__velx > 0: self.__velx -= atrito ##### AJUSTE DE VELOCIDADE MAXIMA ##### if self.__velx > self.poder.velmax: if self.__velx > self.poder.velmax + 1: self.__velx -= 1 else: self.__velx = self.poder.velmax elif self.__velx < -self.poder.velmax: if self.__velx < -self.poder.velmax - 1: self.__velx += 1 else: self.__velx = -self.poder.velmax ##### ATUALIZACAO DE POSICOES ##### self.__y += self.__vely self.__x += self.__velx ##### MATA O JOGADOR SE CAIR NO BURACO ##### if self.__y > screen[1]: self.__vida = 0 ##### INDICA A DIRECAO DO JOGADOR PARA DIRECIONAR PODERES ##### if self.__velx > 0: self.__face = 1 elif self.__velx < 0: self.__face = -1 ##### ATUALIZACAO DO CORPO DO JOGADOR ##### self.__corpo = pygame.Rect(self.__x, self.__y, self.__largura, self.__altura) def poderes(self, screen, mapa, acao=False, outros_poderes=False): ##### ATIRA BOLA DE FOGO SE ESTIVER DISPONIVEL if acao and not self.__recarga: self.__poder.acao(self, screen, mapa) self.__recarga = self.poder.recarga # TORNAR ESSA PARTE MAIS GENERICA
self.speedx = random.randrange(-3, 3) def update(self): """should spawn right in front of the player""" self.rect.y += self.speedy self.rect.x += self.speedx if self.rect.bottom < 0: self.kill() class Missile(pygame.sprite.Sprite): def __init__(self, x, y): pygame.sprite.Sprite.__init__(self) self.image = missile_img self.image.set_colorkey(Commons.BLACK) self.rect = self.image.get_rect() self.rect.bottom = y self.rect.centerx = x self.speedy = -5 def update(self): """should spawn right in front of the player""" self.rect.y += self.speedy if self.rect.bottom < 0: self.kill() ss = SpriteSheet('Bullet_Collection.png') bullet_img = ss.get_image(398, 255, 20, 20) bullet_enemy_img = ss.get_image(320, 268, 18, 18)
def draw_iframes(surface, destination, x, y, who): # draw invincibility buff when invincible sprite_sheet = SpriteSheet(mc_hud_gfx) image = sprite_sheet.get_image(229, 54, 5, 5) if who.invincible == True: surface.blit(image, [x, y])
class NhClient: """ Uses telnet to connect to Nethack and communicate on a basic level with it. Note to self: Do not put game logic here. This is a low level interface. """ game_address = 'localhost' game_port = 23 cols = 80 rows = 24 encoding = 'ascii' history = [] data_history = [] wb_message = b'welcome back to NetHack!' MAX_GLYPH = 1012 map_x_y = MapXY(21, 80) nhdata = NhData() cursor = Point(0, 0) monster_count = len(nhdata.monsters.monster_data) tn = None _more_prompt = b'ore--\x1b[27m\x1b[3z' is_always_yes_question = False is_killed = False is_end = False is_stale = False is_more = False is_killed_something = False is_always_no_question = False is_special_prompt = False is_blank = False _states = { 'always_yes_question': ['Force its termination? [yn]'], 'killed': ['killed by'], 'end': ['(end)'], 'stale': ['stale'], 'more': ['--More--'], 'killed_something': ['You kill'], 'always_no_question': ['Still climb?', 're you sure?'], 'dgamelaunch': ['dgamelaunch'] } def __init__(self, username='******'): self.username = username self.sprite_sheet = SpriteSheet("sprite_sheets/chozo32.bmp", 40, 30) self._init_screen() self._set_states() #self.start_session() def __del__(self): self.close() def start_session(self): self._init_screen() self.tn = telnetlib.Telnet(self.game_address) prompt = b'=>' self.tn.read_until(prompt, 2) self.send_and_read_to_prompt(prompt, b'l') message = self.username.encode(self.encoding) + b'\n' self.send_and_read_to_prompt(prompt, message) self.send_and_read_to_prompt(prompt, message) self.send_and_read_to_prompt(prompt, b'p') # play page = self.history[-1] # Important not to send anything while stale processes are being killed while self.is_stale: print("stale") data = self.tn.read_until(b'seconds.', 1) page = self.render_data(data) self.history.append(page) self._set_states() self.tn.read_until(self._more_prompt, 2) while self.is_more or self.is_blank: self.send_and_read_to_prompt(self._more_prompt, b'\n') #[print(line) for line in self.history] def reset_game(self): self.send_and_read_to_prompt(b'[yes/no]?', b'#quit\n') self.send_and_read_to_prompt(b'(end)', b'yes\n') while self.is_end or self.is_more: self.send_and_read_to_prompt(self._more_prompt, b' ') self.close() def render_glyphs(self): """ Creates a three channel numpy array and copies the correct glyphs to the array. Compatible with png and matplotlib ex: png.from_array(img.tolist(), 'RGB').save('map.png') """ screen = np.zeros((self.map_x_y.x * 32, self.map_x_y.y * 32, 3)) glyphs = self.buffer_to_npdata() for row in range(len(glyphs)): for col in range(len(glyphs[row])): glyph = glyphs[row, col] tile = self.sprite_sheet.get_image_by_number(int(glyph)) screen[row * 32:(row * 32) + 32, col * 32:(col * 32) + 32, :] = tile return screen def send_and_read_to_prompt(self, prompt, message, timeout=2): if type(prompt) == str: prompt = prompt.encode('ascii') if type(message) == str: message = message.encode('ascii') self.tn.write(message) #print(prompt, message) data = self.tn.read_until(prompt, timeout) data += self.tn.read_very_eager() self.data_history.append(data) screen = self.render_data(data) self.history.append(screen) self._set_states() return data def close(self): print("closing") if self.tn: self.send_string('S') self.send_string('y\n') self.tn.close() def _init_screen(self): self.byte_stream = ByteStream() self.screen = Screen(self.cols, self.rows) self.byte_stream = ByteStream() self.byte_stream.attach(self.screen) def render_data(self, data): self.byte_stream.feed(data) lines = self.screen.display self.cursor.x = self.screen.cursor.x self.cursor.y = self.screen.cursor.y - 1 # last char is just before cursor return lines def buffer_to_npdata(self): skiplines = 1 npdata = np.zeros((self.map_x_y.x, self.map_x_y.y), dtype=np.float32) npdata += 829 # set default to solid rock for line in range(skiplines, self.map_x_y.x + skiplines): for row in range(self.map_x_y.y): if self.screen.buffer[line] == {}: continue glyph = self.screen.buffer[line][row].glyph glyph = self.nhdata.collapse_glyph(glyph) if not self.screen.buffer[line][row].data == ' ': npdata[line - skiplines, row] = glyph return npdata def buffer_to_rgb(self): npdata = self.buffer_to_npdata() min_m, max_m = self.nhdata.monsters.minkey, self.nhdata.monsters.maxkey min_o, max_o = self.nhdata.objects.minkey, self.nhdata.objects.maxkey min_r, max_r = self.nhdata.rooms.minkey, self.nhdata.rooms.maxkey r, b, g = npdata.copy(), npdata.copy(), npdata.copy() r = self._normalize_layer(r, min_m, max_m) # creatures b = self._normalize_layer(b, min_r, max_r) # room g = self._normalize_layer(g, min_o, max_o) # object rgb = np.zeros((r.shape + (3, ))) rgb[:, :, 0] = r rgb[:, :, 1] = b rgb[:, :, 2] = g # cursor axis are flipped v.s. image or I made more x,y mistakes if self.cursor.y < self.map_x_y.x and self.cursor.x < self.map_x_y.y: rgb[self.cursor.y, self.cursor.x, :] = 1 # highlight player. return rgb def _normalize_layer(self, data, min_val, max_val, skew=0.2): #backup = data.copy() data[data < min_val] = min_val data[data > max_val] = min_val data += -(min_val) data /= max_val if data.min() < 0: raise ValueError("dang") #skew data away from 0 data *= 1.0 - skew data[data > 0] += skew return data def _set_states(self): page = " ".join(self.screen.display) self.is_special_prompt = False for s in self._states: setattr(self, "is_" + s, False) for string in self._states[s]: if string in page: setattr(self, "is_" + s, True) if 'killed_something' != s: self.is_special_prompt = True self.is_blank = True for c in page: if c != ' ': self.is_blank = False break def _get_states(self): states = {} for s in self._states: states[s] = getattr(self, "is_" + s) states['blank'] = self.is_blank return states def imshow_map(self): img = self.render_glyphs() fig, ax = plt.subplots(figsize=(12, 4)) ax.axis('off') ax.imshow(img) plt.tight_layout() def get_visible_mobs(self): npdata = self.buffer_to_npdata() mobs = np.argwhere(npdata < self.monster_count) visible = [] for mob in mobs: if not np.array_equal(mob, [self.cursor.x, self.cursor.y]): visible.append([mob, npdata[mob[0], mob[1]]]) return visible # TODO: Move this to nhstate? def get_status(self): return self.nhdata.get_status(self.screen.display) def send_command(self, action_num): command = self.nhdata.COMMANDS[action_num] data = command.command self.send_and_read_to_prompt(b'\x1b[3z', data.encode('ascii')) def send_string(self, string): self.send_and_read_to_prompt(b'\x1b[3z', string)
def draw_hud_bg(surface, destination, x, y): # draw the bg image for the rest of the hud sprite_sheet = SpriteSheet(mc_hud_gfx) image = sprite_sheet.get_image(0, 226, 16, 16) surface.blit(image, [x, y]) image = sprite_sheet.get_image(0, 242, 16, 16) surface.blit(image, [x, y + 32]) image = sprite_sheet.get_image(0, 258, 16, 16) surface.blit(image, [x, y + 64]) image = sprite_sheet.get_image(0, 274, 16, 16) surface.blit(image, [x, y + 96]) image = sprite_sheet.get_image(16, 226, 16, 16) surface.blit(image, [x + 32, y]) image = sprite_sheet.get_image(16, 242, 16, 16) surface.blit(image, [x + 32, y + 32]) image = sprite_sheet.get_image(16, 258, 16, 16) surface.blit(image, [x + 32, y + 64]) image = sprite_sheet.get_image(16, 274, 16, 16) surface.blit(image, [x + 32, y + 96]) image = sprite_sheet.get_image(32, 258, 16, 16) surface.blit(image, [x + 64, y + 64]) image = sprite_sheet.get_image(48, 258, 16, 16) surface.blit(image, [x + 96, y + 64]) image = sprite_sheet.get_image(64, 258, 16, 16) surface.blit(image, [x + 128, y + 64])
def __init__(self, username='******'): self.username = username self.sprite_sheet = SpriteSheet("sprite_sheets/chozo32.bmp", 40, 30) self._init_screen() self._set_states()
now = pygame.time.get_ticks() if now - self.last_shot > self.shoot_delay: self.last_shot = now bullet = BulletEnemy(self.rect.centerx, self.rect.bottom, player.x, player.y) sprites.add(bullet) bulletsEnemy.add(bullet) def new_enemy(): enemy = Enemy() sprites.add(enemy) enemies.add(enemy) ss = SpriteSheet('Lightning.png') player_imgs = [] player_imgs.append(ss.get_image(0, 0, 30, 30)) player_imgs.append(ss.get_image(32, 0, 30, 30)) player_imgs.append(ss.get_image(64, 0, 30, 30)) player_imgs.append(ss.get_image(96, 0, 30, 30)) ss1 = SpriteSheet('UFO.png') enemy_imgs = [] enemy_imgs.append(ss1.get_image(0, 0, 30, 30)) enemy_imgs.append(ss1.get_image(32, 0, 30, 30)) enemy_imgs.append(ss1.get_image(64, 0, 30, 30)) enemy_imgs.append(ss1.get_image(96, 0, 30, 30)) player = Player() for i in range(4):
from sprites import SpriteSheet from sprites import power_ups class Pow(pygame.sprite.Sprite): def __init__(self, center): pygame.sprite.Sprite.__init__(self) self.type = random.choice(['upgrade', 'extra_live']) self.image = powerup_imgs[self.type] self.image.set_colorkey(Commons.BLACK) self.image = pygame.transform.scale(self.image, (30, 30)) self.rect = self.image.get_rect() self.rect.center = center self.speedy = 1 def update(self): """should spawn right in front of the player""" self.rect.y += self.speedy ## kill the sprite after it moves over the top border if self.rect.top > Commons.HEIGHT: self.kill() ss = SpriteSheet('Power_Ups.png') extra_live = ss.get_image(525, 30, 130, 130) upgrade = ss.get_image(792, 33, 120, 120) powerup_imgs = {} powerup_imgs['upgrade'] = upgrade powerup_imgs['extra_live'] = extra_live