def __init__(self, width, height): # init vars self.uiobj = ui.UI(width, height) self.userinputobj = userinput.UserInput() self.gameobj = entity.Game(entity.Player(), entity.Player()) self.logicobj = logic.Logic() # update ui at start self.uiobj.update(self.gameobj, userinput)
def __init__(self): #set physics variables self.clock = pygame.time.Clock() self.__physics_FPS = 100.0 self.__dt = 1.0 / self.__physics_FPS self.time_current = self.get_time() self.accumulator = 0.0 self.tile_size = 32 self.camera = camera.Camera((1280, 720)) tile_images = { "tile_grass": IMAGES.tile_grass, "tile_dirt": IMAGES.tile_dirt, "tile_wall": IMAGES.tile_wall } world = WORLD.World("level.map", tile_images) self.path_finder = pathfinder.PathFinder(world.nodes) player = entity.Player(IMAGES.player) dummy = entity.Entity(IMAGES.player, spawn_location = (16, 2)) self.entities = pygame.sprite.Group(player, dummy) self.objects = dict(world=world, player=player, dummy=dummy) self.console = console.Console() s = item.Sword(IMAGES.key) b = item.Bandage(IMAGES.key) player.hand.add(s) player.bag.add(0, b)
def __init__(self, spritesheet): self.player = E.Player() self.direction = "" self.player_moves = 0 self.level = 0 self.newMap(30) self.sprites = spritesheet self.font = pygame.font.Font('freesansbold.ttf', 12) self.currentTriggers = [] self.graphics_updates = True self.bg_image = None self.fg_image = None self.gg_image = None self.last_image = None self.Cooldown = 0 self.maxCooldown = 200 self.waitForDialogue = False self.graphicsCD = 0 self.currentTrap = None self.arrow = None self.hiding = False self.bouncing = False self.bouncingCD = 0 self.currentCellContents = [] self.DEBUGGING = False
def update(self, data): self.players.update(data['players'], data.get('full', False), self) self.entities.update(data['entities'], data.get('full', False), self) self.npcs.update(data['npcs'], data.get('full', False), self) if len(data['players']) != 0: for i in data['players']: p = entity.Player(self) # TODO: create from data p.id = i['id'] p.standalone = False p.original_center = (i['x'], i['y']) p.update(data['players'], data.get('full', False), self) p.update({'target': self.target}) self.players.add(p) if len(data['entities']) != 0: for i in data['entities']: p = entity.Entity(self) # TODO: create from data p.id = i['id'] p.original_center = (i['x'], i['y']) p.update(data['players'], data.get('full', False), self) p.update({'target': self.target}) self.entities.add(p) if len(data['npcs']) != 0: for i in data['npcs']: p = entity.NPC(self) # TODO: create from data p.id = i['id'] p.original_center = (i['x'], i['y']) p.update(data['npcs'], data.get('full', False), self) p.update({'target': self.target}) self.npcs.add(p)
def __init__(self, host='127.0.0.1', port=5000): self.host = host self.port = port self.world = jsonpickle.decode( requests.get("http://" + host + ":" + str(port) + "/world/get").json()) self.player = entity.Player(input("What's your name? "), 20, 10, {}, 0) self.world.start.entities.append(self.player) requests.post("http://" + host + ":" + str(port) + "/world/set", data=jsonpickle.encode(self.world))
def __init__(self): self.clock = pygame.time.Clock() self.FPS = 60 self.surface = pygame.display.set_mode(cfg.dim) self.running = True self.group = entity.Group() self.player = entity.Player() self.floor = entity.Floor() self.jumping = False self.time_init = 0.0 self.wait = 0.0 self.maxspd = 2.5 self.minspd = 0.8
def __init__(self, game, scene_name, my_map): super().__init__() self.game = game self.scene_name = scene_name self.my_map = my_map self.game_dim = self.game_width, self.game_height = self.game.win_dim self.world_dim = self.world_width, self.world_height = my_map.world_dim self.tile_dim = self.tile_width, self.tile_height = my_map.tile_dim self.map_id = my_map.map_id self.tile_map = tile.TileMap(self) self.tile_manager = tile.TileManager(self) self.player = entity.Player(self, my_map.player_x, my_map.player_y) self.enemy = entity.Enemy(self, my_map.enemy_x, my_map.enemy_y) self.entity_manager = entity.EntityManager(self, self.player, self.enemy) self.player_camera = camera.Camera(self, self.player)
def __init__(self,map_name,camera): self.next="" self.current_maps=[] self.name_list=[] self.current_map=0 while self.next!=None: self.current_maps.append(map.map(map_name)) self.name_list.append(map_name) self.next=self.current_maps[-1].get_next_map() map_name=self.next spawn=self.current_maps[self.current_map].get_p_spawn() self.player=entity.Player(spawn[0],spawn[1],32,32) self.current_map=0 self.camera=camera self.camera.cam_max_x=self.current_maps[self.current_map].map_width() self.camera.cam_max_y=self.current_maps[self.current_map].map_height()
def __init__(self, inputObject, worldPos, moverSpriteDBase, dimensions, world, appPtr, paneScreenPos, paneNum): self.appPtr = appPtr self.world = world self.paneNum = paneNum self.idevice = inputObject # Something derived from # idevice.IDevice self.surface = pygame.Surface(dimensions) self.cameraPos = worldPos - math2d.Vector2(dimensions[0] / 2, dimensions[1] / 2) self.player = entity.Player(worldPos, "Human", moverSpriteDBase, appPtr.soundeffects) self.visibleObjects = [] self.traps = [] self.trapCheckList = [self.player] #self.GManager = gui_manager.GUI_Manager() for enemy in world.enemies: self.trapCheckList.append(enemy) self.paneScreenPos = paneScreenPos
pygame.display.set_caption("Hello World!") pygame.display.set_icon(pygame.image.load("Resources/Default/gameIcon.png")) # Convert all images to optimized form tiles.loadImageTable() items.loadImageTable() for i in range(len(chunkBuffer)): chunkBuffer[i].draw() chunkBuffer.renderLightmap(i) # Input handling containers eventHandler = entity.ClientEventHandler() # Player variables player = entity.Player(screen, [0, 0], chunkBuffer, eventHandler, eventHandler.keyStates, eventHandler.mouseState, eventHandler.cursorPos, DEFAULT_FRICTION) currChunk = prevChunk = deltaChunk = 0 # Initialize the renderer Renderer.initialize(chunkBuffer, camera, player, displaySize, screen) dt = 0 def takeCommand( ): global cameraBound command = input(">> ") what = "" cntr = 4 for i in command[4::]: cntr += 1 if(i == ' '): break
def add_client(self, client: socket.socket): player = entity.Player("", "", 0, 0, 0) print(f"add client with uuid:{player.uuid.hex}") self.clients.update({player.uuid: client})
def runGame(): #INITIALIZE GAME blocks_per_window = 18 #length wise block_s = screen_width // blocks_per_window sandbox_block_s = block_s STAGE_SIZE = (90, 60) numSnakes = 10 #too many lags the game a significant amount import world import entity import lighting import physics import TXT STAGE = world.Stage(STAGE_SIZE[1], STAGE_SIZE[0], block_s, numSnakes) STAGE.newStage() STAGE.furnish() STAGE.spawnSnakes() player = entity.Player(block_s, WINDOW_SIZE) EXPIRETORCH = pygame.USEREVENT + 1 pygame.time.set_timer(EXPIRETORCH, lighting.Torch.expTime) DARK = True darkness = lighting.DarkFilter(WINDOW_SIZE) SANDBOXMODE = False SCROLLMODE = False DX, DY = 0, 0 #for sandbox scrolling TIMEPASSED = 0 #ms MSG_CODE = 0 LAST_MSG_TIME = None LAST_MSG = None def redrawGameWindow(): #draw stage window.fill((0, 0, 0)) #(210,180,140)) #tan flares = [] for block in STAGE.stage: if type(block) != world.Flare: window.blit(block.image, (block.rect.x, block.rect.y)) else: flares.append(block) #flares drawn later, over dark if not SANDBOXMODE: #lighting effect here if DARK: darkness.update(player, flares) #update lighting window.blit(darkness.image, (0, 0), special_flags=pygame.BLEND_RGBA_MIN) #draw flares for block in flares: window.blit(block.image, (block.rect.x, block.rect.y)) #entities drawn over darkness so still visible when torch dead for ent in STAGE.entities: window.blit(ent.image, (ent.rect.x, ent.rect.y)) window.blit(player.image, (player.rect.x, player.rect.y)) window.blit(TXT.icons(player), (0, 0)) #icon display if player.demoMode: TXT.drawDemoMsg( window) #messages display (game message called elsewhere) if SCROLLMODE: TXT.drawModeMsg(window, 1) elif SANDBOXMODE: TXT.drawModeMsg(window, 2) else: TXT.drawGameMsg(window, MSG_CODE) pygame.display.update() while True: if SANDBOXMODE: d = 15 (x, y) = pygame.mouse.get_pos() if x < 100: STAGE.scroll(-1 * d, 0) DX -= d elif x > WINDOW_SIZE[0] - 100: STAGE.scroll(d, 0) DX += d if y < 100: STAGE.scroll(0, -1 * d) DY -= d elif y > WINDOW_SIZE[1] - 100: STAGE.scroll(0, d) DY += d #EVENT LOOP / CONTROLS for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == KEYDOWN: if event.key == K_s: #exit sandbox STAGE.scroll(-1 * DX, -1 * DY) DX, DY = 0, 0 STAGE.changeSize(block_s) STAGE.spawnSnakes() SANDBOXMODE = False if event.key == K_DOWN: #zoom out sandbox_block_s = int(sandbox_block_s / 1.25) STAGE.changeSize(sandbox_block_s, DX, DY) if event.key == K_UP: #zoom in sandbox_block_s = int(sandbox_block_s * 1.25) STAGE.changeSize(sandbox_block_s, DX, DY) if event.key == K_h: helpScreenSB() #semi-automatic generation if event.key == K_RIGHT: #make new stage STAGE.newStage() STAGE.changeSize(sandbox_block_s, DX, DY) if event.key == K_SPACE: #make pathways and spawn special blocks STAGE.furnish() STAGE.changeSize(sandbox_block_s, DX, DY) #manual generation if event.key == K_r: #new completely random map STAGE = world.Stage(STAGE_SIZE[1], STAGE_SIZE[0], block_s, numSnakes) STAGE.changeSize(sandbox_block_s, DX, DY) if event.key == K_g: #game of life step STAGE.step() STAGE.changeSize(sandbox_block_s, DX, DY) if event.key == K_d: #clears out stage, basically STAGE.rmvD() STAGE.changeSize(sandbox_block_s, DX, DY) if event.key == K_f: #fills first room to upper left STAGE.fillRoom() STAGE.changeSize(sandbox_block_s, DX, DY) elif SCROLLMODE: d = 20 #scroll with mouse (x, y) = pygame.mouse.get_pos() if x < 100: STAGE.scroll(-1 * d, 0) player.scroll(-1 * d, 0) DX -= d elif x > WINDOW_SIZE[0] - 100: STAGE.scroll(d, 0) player.scroll(d, 0) DX += d if y < 100: STAGE.scroll(0, -1 * d) player.scroll(0, -1 * d) DY -= d elif y > WINDOW_SIZE[1] - 100: STAGE.scroll(0, d) player.scroll(0, d) DY += d #EVENT LOOP / CONTROLS for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == KEYDOWN: if event.key == K_SPACE: #exit scrollmode STAGE.scroll(-1 * DX, -1 * DY) player.scroll(-1 * DX, -1 * DY) DX, DY = 0, 0 SCROLLMODE = False if event.key == K_h: helpScreen() else: TIMEPASSED += 20 #I measured the average tick of one loop to be about 20ms on avg early on, #but now its more like 100ms. I kept the increments of 20 though. if MSG_CODE < 3: MSG_CODE = 0 elif LAST_MSG_TIME == None or LAST_MSG != MSG_CODE: LAST_MSG_TIME = TIMEPASSED LAST_MSG = MSG_CODE else: if ( TIMEPASSED - LAST_MSG_TIME ) // 200 > 0: #delay if last message was a single-trigger message MSG_CODE = 0 LAST_MSG_TIME = None #update player (DX, DY, MSG_CODE) = physics.updatePlayer(player, STAGE, DX, DY, block_s, blocks_per_window, MSG_CODE) #update/remove entities removed = set() for ent in STAGE.entities: if type(ent) == entity.Bomb: MSG_CODE = max(MSG_CODE, 2) #take cover! if ent.state == -1: removed.add(ent) else: ent.update(TIMEPASSED, STAGE, player) for ent in removed: STAGE.entities.discard(ent) #remove spikes without floor / kill player and snakes if touching removed = set() for spike in STAGE.spikes: if spike.checkRemove(STAGE): removed.add(spike) if player.rect.colliderect( spike.rect ) and player.rect.bottom == spike.rect.bottom and not player.demoMode: player.dead = True for ent in STAGE.entities: if type(ent) == entity.Snake: if ent.rect.colliderect( spike.rect ) and ent.rect.bottom >= spike.rect.centery: ent.state = -1 player.killedSnakes += 1 for spike in removed: STAGE.stage.discard(spike) STAGE.spikes.discard(spike) #CHECK DIE if player.dead: pygame.time.wait(500) endScreen(TIMEPASSED, player.treasures, player.killedSnakes, True) #CHECK WIN (temporary) for block in STAGE.exitBlocks: if player.rect.colliderect(block.rect): endScreen(TIMEPASSED, player.treasures, player.killedSnakes) #EVENT LOOP / CONTROLS for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == KEYDOWN: if event.key == K_LEFT: player.moveLeft = True if event.key == K_RIGHT: player.moveRight = True if event.key == K_UP: touchingRope = False touchedRope = None for block in player.getCollidedBlocks(STAGE): if isinstance(block, world.Rope): touchingRope = True touchedRope = block player.isClimb = True if player.isClimb: STAGE.scroll( touchedRope.rect.centerx - player.rect.centerx, 0) player.ducked = False player.touchedBlocks['bottom'] = None player.yVel = -1 * player.jumpSpd elif player.jumps > 0: player.jumps -= 1 player.ducked = False player.touchedBlocks['bottom'] = None player.yVel = -1 * player.jumpSpd if event.key == K_DOWN: touchingRope = False touchedRope = None for block in player.getCollidedBlocks(STAGE): if isinstance(block, world.Rope): touchingRope = True touchedRope = block player.isClimb = True if player.isClimb: STAGE.scroll( touchedRope.rect.centerx - player.rect.centerx, 0) player.ducked = False player.yVel = player.jumpSpd elif player.jumps > 0: player.ducked = not player.ducked if event.key == K_r: MSG_CODE = player.placeRope(STAGE, MSG_CODE) if event.key == K_t: temp = player.torches player.torches = player.torches2 player.torches2 = temp if event.key == K_f: MSG_CODE = player.placeFlare(STAGE, MSG_CODE) if event.key == K_g: MSG_CODE = player.collect(STAGE, MSG_CODE) if event.key == K_b: MSG_CODE = player.placeBomb(STAGE, TIMEPASSED, MSG_CODE) if event.key == K_d: #demo mode player.demoMode = not player.demoMode if event.key == K_s: sandbox_block_s = block_s STAGE.entities = set() #so snakes don't teleport SANDBOXMODE = True if event.key == K_SPACE: SCROLLMODE = True if event.key == K_h: helpScreen() if event.key == K_RETURN and player.demoMode: endScreen(TIMEPASSED, player.treasures, player.killedSnakes) if event.type == KEYUP: if event.key == K_LEFT: player.moveLeft = False if event.key == K_RIGHT: player.moveRight = False if event.key == K_UP: if player.yVel < 0: if player.isClimb: player.yVel = 0 else: player.yVel //= 2 if event.key == K_DOWN: if player.isClimb and player.yVel > 0: player.yVel = 0 if event.type == pygame.MOUSEBUTTONDOWN: DARK = not DARK if DARK: if event.type == EXPIRETORCH: if player.torches != []: player.torches[-1].expire() redrawGameWindow() clock.tick(60) #100ms, approx.
import os os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (100, 25) pygame.init() screen = pygame.display.set_mode((1000, 800)) background = pygame.image.load('Assets/Background/temple_room.png').convert() pygame.display.set_caption("Temple Game") icon = pygame.image.load('Assets/temple.png') pygame.display.set_icon(icon) player_image_sheet = entity.SpriteSheet('Assets/Sprite/Cowboy_Top.png') player1 = entity.Player(player_image_sheet, 360, 40) dynamic_rooms.create_plot() item_slots.create_slots() font = pygame.font.Font('freesansbold.ttf', 28) def show_FPS(frames, x, y): fps = font.render("FPS: " + str(frames), True, (5, 5, 5)) screen.blit(fps, (x, y)) # Game Loop animation_frame = 0 next_frame = pygame.time.get_ticks()
def _generate_room(self, difficulty): self.tables = [] self.chairs = [] self.students = [] self.safe_areas = [] center_x = config.ROOM_SIZE.y / 2 # Génération des chemins de navigation, allé centrale + tables. paths = [[Vector2(0, center_x), Vector2(config.ROOM_SIZE.x, center_x)]] + \ [[Vector2(r, 0), Vector2(r, config.ROOM_SIZE.y)] for _, r in row_range(self.rows)] random_targets = [] # Génération de points de navigation supplémentaire pour le tableau. board_x = config.ROOM_SIZE.x - config.TEACHER_SIZE.x board_prob = int( config.NAV_BOARD_PROB * exp(-difficulty * config.TEACHER_BOARD_PROP_DIFFICULTY)) for i in range(config.BOARD_POINTS): random_targets.append((Vector2(board_x, \ (i + 1) / (config.BOARD_POINTS + 1) * config.ROOM_SIZE.y), board_prob)) # Ajout d'un chemin pour le tableau. paths.append( [Vector2(board_x, 0), Vector2(board_x, config.ROOM_SIZE.y)]) # Le numéro aléatoire de la chaise du joueur. rand_col = random.randint(0, self.columns - 1) max_row = self.rows - 1 # Choix du rang en fonction de la difficulté, plus elle augmente plus il y a de chance # d'être près du tableau. rand_row = random.randint( max_row - int(max_row * exp(-difficulty * config.PLAYER_ROW_DIFFICULTY)), max_row) rand_chair = random.randint(0, 1) # Génération des chaises, des tables et des élèves. for c_i, c in column_range(self.columns): for r_i, r in row_range(self.rows): pos = Vector2(r + config.CHAIR_SIZE.x + config.TEACHER_SIZE.x, c) t = entity.Table(pos) self.tables.append(t) # Deux chaises par table. for i in range(2): # Position de la chaise cpos = pos + Vector2(-42, (i * 2 - 1) * 35) random_targets.append((Vector2( cpos.x - config.CHAIR_SIZE.x / 2 - config.TEACHER_SIZE.x / 2, cpos.y), config.NAV_CHAIR_PROB)) ch = entity.Chair(cpos) self.chairs.append(ch) # Assignation d'un élève ou du joueur. if c_i == rand_col and r_i == rand_row and i == rand_chair: player_position = Vector2( cpos.x - config.STUDENT_SIZE.x / 2, cpos.y) self.player = entity.Player(paths, \ config.PLAYER_SPEED * config.PLAYER_SPEED_DIFFICULTY ** difficulty, player_position) ch.student = self.player else: stud = entity.Student(cpos) ch.student = stud self.students.append(stud) ch.student.rotation = pi / 2 # Division des probabilités pour garder une somme à 1. prob_sum = sum((v for _, v in random_targets)) random_targets = [(p, v / prob_sum) for p, v in random_targets] self.teacher = entity.Teacher(paths, random_targets, \ config.TEACHER_SPEED * config.TEACHER_SPEED_DIFFICULTY ** difficulty, \ Vector2(config.ROOM_SIZE.x, center_x)) self.effects.append(self.teacher.view_effect) for i in range(self.columns): # Génération d'une zone saine pour se cacher. safe_area = collision.Rectangle( Vector2(config.ROOM_SIZE.x * 0.8, config.TABLE_SIZE.y)) self.safe_areas.append((safe_area, Vector2(config.ROOM_SIZE.x * 0.45, \ config.TABLE_SIZE.y / 2 + (config.ROOM_SIZE.y - config.TABLE_SIZE.y) * i))) # Création des portes. door_front = entity.Door(Vector2(config.ROOM_SIZE.x * 0.97 - config.DOOR_SIZE.x / 2, \ config.ROOM_SIZE.y - config.DOOR_SIZE.y / 2)) door_back = entity.Door(Vector2(config.ROOM_SIZE.x * 0.03 + config.DOOR_SIZE.x / 2, \ config.ROOM_SIZE.y - config.DOOR_SIZE.y / 2)) self.doors = [door_front, door_back] self.floor = entity.Floor() self.students.append(self.player) self.humans = [self.teacher] + self.students self.objects = self.humans + self.tables + self.chairs + self.doors + [ self.floor ]
self.gm_window = gm_window self.gm_data = gm_data self.gm_logic = gm_logic def run(self): pyglet.app.run() if __name__ == '__main__': # TODO: Add menu interface!!! my_map = mapset.Map() my_map.load('data/map_ascii/test1.map') my_player = entity.Player('Engineer', 1, 1, '@') entity1 = entity.Entity('Mike', 3, 3, 'M') entity2 = entity.Entity('Paul', 3, 1, 'P') gm_data = game_data.GameData(my_map, my_player, [entity1, entity2]) gm_wind = game_window.GameWindow(config.window_width, config.window_height, resizable=True, caption=config.window_caption) gm_wind.load_graphx('tileset.png', config.gfx_tilesize) gm_wind.render_mapset(gm_data.root_map.get_all()) gm_wind.render_player(gm_data.player) gm_wind.render_entities(gm_data.entities)
elif event.key == pygame.K_DOWN or event.key == pygame.K_s: player.moving["down"] = False elif event.key == pygame.K_UP or event.key == pygame.K_w: player.moving["up"] = False elif event.key == pygame.K_SPACE: player.growing = False elif event.key == pygame.K_LSHIFT: player.shrinking = False pygame.init() windowSurface = pygame.display.set_mode((constant.WIDTH, constant.HEIGHT), 0, 32) pygame.display.set_caption('Hop Hop Hop') player = entity.Player([500, 0], 60) wall = entity.Wall([200, 200], 100, 100) while True: #game loop handleEvents() windowSurface.fill(constant.WHITE) levels.update(player) levels.draw(windowSurface) player.update() player.draw(windowSurface) wall.update(player) wall.draw(windowSurface)
def main(): screen_width = 128 screen_height = 48 sch_height = 3 sch_width = 27 # Inventory inv_height = screen_height - sch_height inv_width = sch_width # Log log_height = 10 log_width = screen_width - inv_width # Size of the map map_width = screen_width - inv_width map_height = screen_height - log_height - 1 # Popup size popup_width = round(7 * map_width / 12) popup_height = round(7 * map_height / 12) # tcod init tcod.console_set_custom_font(resource_path('font.png'), tcod.FONT_LAYOUT_ASCII_INROW) root_console = tcod.console_init_root(screen_width, screen_height, '1RL v1.2 – 7DRL 2019') tcod.console_set_default_background(root_console, const.base03) # map console con = tcod.console.Console(map_width, map_height) tcod.console_set_default_background(con, const.base03) # description console des_panel = tcod.console.Console(log_width, 1) tcod.console_set_default_background(des_panel, const.base03) # log console log_panel = tcod.console.Console(log_width, log_height) tcod.console_set_default_background(log_panel, const.base03) # popup console popup_panel = tcod.console.Console(popup_width, popup_height) tcod.console_set_default_background(popup_panel, const.base03) # scheduling console sch_panel = tcod.console.Console(sch_width, sch_height) tcod.console_set_default_background(sch_panel, const.base03) # inventory console inv_panel = tcod.console.Console(inv_width, inv_height) tcod.console_set_default_background(inv_panel, const.base03) # scheduling turns = sch.Scheduling() # map generation game_map = gmap.GameMap(map_width, map_height, con) # log init msglog = log.Log(log_width - 2, log_height - 2) # splash image splash_img = tcod.image_load(resource_path("splash.png")) while not tcod.console_is_window_closed(): tcod.console_clear(con) tcod.console_clear(des_panel) tcod.console_clear(log_panel) tcod.console_clear(popup_panel) tcod.console_clear(sch_panel) tcod.console_clear(inv_panel) const.n_bugs_max = [[5, 0, 0], [2, 5, 1]] player = entity.Player(None, None) entities = [player] msglog.reset() turns.reset() turns.add_turn( 0, const.TurnType.MSG, log.Msg( "They say the hardest part is actually choosing to make a game. So I guess I've already won?", const.green, const.desat_green2)) turns.add_turn(0, const.TurnType.PLAYER, player) turns.add_turn( 3600 * 24, const.TurnType.MSG, log.Msg("You have 6 days left.", const.green, const.desat_green2)) turns.add_turn( 3600 * 24 * 2, const.TurnType.MSG, log.Msg("You have 5 days left. Keep going.", const.green, const.desat_green2)) turns.add_turn( 3600 * 24 * 3, const.TurnType.MSG, log.Msg("You have 4 days left. Don't be too ambitious!", const.orange, const.desat_orange)) turns.add_turn( 3600 * 24 * 4, const.TurnType.MSG, log.Msg("You have 3 days left. That's less than half a week...", const.orange, const.desat_orange)) turns.add_turn( 3600 * 24 * 5, const.TurnType.MSG, log.Msg("You have 2 days left. Don't panic.", const.orange, const.desat_orange)) turns.add_turn( 3600 * 24 * 6, const.TurnType.MSG, log.Msg("Only 1 day left. OK, maybe it's time to panic.", const.red, const.desat_red)) turns.add_turn( 3600 * 24 * 6.5, const.TurnType.MSG, log.Msg("Only 12 hours left! You need to finish this NOW!", const.red, const.desat_red)) turns.add_turn(3600 * 24 * 7, const.TurnType.GAME_OVER, None) i = 0 for fslot in const.FeatureSlot: turns.add_turn(int(i), const.TurnType.SPAWN, fslot) i += const.spawn_interval / len(const.FeatureSlot) # game_map.make_boss_map(turns, entities, player) game_map.make_map_bsp(turns, entities, player) # Splash tcod.console_clear(root_console) splash_img.blit_2x(root_console, 10, 5) tcod.console_set_default_foreground(root_console, const.yellow) tcod.console_print_ex( root_console, 85, 15, tcod.BKGND_NONE, tcod.CENTER, "Press any key to create your\nfirst roguelike!") tcod.console_print_ex(root_console, int(screen_width / 2), screen_height - 2, tcod.BKGND_NONE, tcod.CENTER, "By a cheap plastic imitation of a game dev") tcod.console_print_ex(root_console, int(screen_width / 2), screen_height - 1, tcod.BKGND_NONE, tcod.CENTER, "during the 7DRL 2019") again = True while again: tcod.console_flush() for event in tcod.event.wait(): if event.type == "QUIT": raise SystemExit() elif event.type == "KEYDOWN" or event.type == "MOUSEBUTTONDOWN": again = False # give a level 1 feature first_feature = random_loot.get_random_feature(random.choice( list(const.FeatureSlot)), turns, player, level=1) key = player.add_to_inventory(first_feature) # no hack as first weapon first_weapon = random_loot.get_random_weapon(random.choice( [const.WeaponSlot.slow, const.WeaponSlot.fast]), turns, player, level=1) # first_weapon = random_loot.get_random_weapon(random.choice([const.WeaponSlot.slow, const.WeaponSlot.fast]), turns, player, level=3) # DEBUG key = player.add_to_inventory(first_weapon) # first_weapon = random_loot.get_random_weapon(const.WeaponSlot.hack, turns, player, level=1)# DEBUG # key = player.add_to_inventory(first_weapon) # initial render render.render_map(root_console, con, entities, player, game_map, screen_width, screen_height) render.render_log(root_console, log_panel, msglog, map_height) render.render_des(root_console, des_panel, map_height, "") render.render_sch(root_console, sch_panel, turns, map_width, 0) render.render_inv(root_console, inv_panel, player, map_width, sch_height) menu_state = const.MenuState.POPUP render.render_popup(root_console, popup_panel, map_width, map_height, const.intro_strings) tcod.console_flush() fov_recompute = False render_inv = False # render inventory force_log = False # force to pass log new_turn = True # end of the turn render_map = False # render all the map need_flush = False mouse = (500, 500) #OOB new_mouse = False # did the mouse move boss = None # is it the final fight? boss_confirm = False # did the player confirm they are ready? last_boss_hp = 0 while not tcod.console_is_window_closed(): if new_turn: # The boss is defeated if boss and boss.hp <= 0: msglog.add_log( "Congratulations! You defeated your self-doubt and completed your game!", const.green, const.green) msglog.add_log( "You ascend to the status of RL game dev...", const.green, const.green) msglog.add_log("Score: " + str(10 * player.get_score()), const.green, const.green) render.render_boss_hp(root_console, des_panel, map_height, boss) render.render_log(root_console, log_panel, msglog, map_height) tcod.console_flush() break # A bunch of assert to be sure there are no serious bugs assert turns.nb_turns( const.TurnType.PLAYER) == 1, turns.nb_turns( const.TurnType.PLAYER) assert turns.nb_turns( const.TurnType.SPAWN) == 5, turns.nb_turns( const.TurnType.SPAWN) assert turns.nb_turns(const.TurnType.ENEMY) == len([ e for e in entities if isinstance(e, entity.Monster) ]), (turns.nb_turns(const.TurnType.ENEMY), len([ e for e in entities if isinstance(e, entity.Monster) ]), entities, turns.turns) current_turn = turns.get_turn() if current_turn.ttype == const.TurnType.PLAYER: # reset the attack counter for e in entities: if isinstance(e, entity.Monster): e.reset_nb_atk() render.render_sch(root_console, sch_panel, turns, map_width, player.time_malus) need_flush = True new_turn = False if current_turn.ttype == const.TurnType.PLAYER: if fov_recompute: game_map.recompute_fov(player.x, player.y) new_ent = [] for e in entities: if not e.is_seen and game_map.is_visible(e.x, e.y): if isinstance(e, entity.Weapon) or isinstance( e, entity.Feature): new_ent.append(e.name) e.is_seen = True if new_ent: if len(new_ent) > 1: last = new_ent.pop() new_ent = ', a '.join(new_ent) + ' and a ' + last else: new_ent = new_ent[0] msglog.add_log("You discover a " + new_ent + ".") if fov_recompute or render_map: # maybe what is under the mouse changed new_mouse = True render.render_map(root_console, con, entities, player, game_map, screen_width, screen_height) need_flush = True render_map = False if new_mouse and not boss: # and menu_state != const.MenuState.POPUP: render.render_des( root_console, des_panel, map_height, render.get_names_under_mouse(mouse, entities, game_map, log_width)) need_flush = True new_mouse = False if boss and last_boss_hp != boss.hp: last_boss_hp = boss.hp render.render_boss_hp(root_console, des_panel, map_height, boss) need_flush = True fov_recompute = False if force_log or msglog.is_there_new(): render.render_log(root_console, log_panel, msglog, map_height, force_log) need_flush = True force_log = False if render_inv: render.render_inv(root_console, inv_panel, player, map_width, sch_height) render_inv = False need_flush = True if need_flush: tcod.console_flush() need_flush = False for event in tcod.event.wait(): key = None modifiers = [] if event.type == "QUIT": raise SystemExit() elif event.type.startswith("WINDOW"): need_flush = True elif event.type == "KEYDOWN": for m in tcod.event_constants._REVERSE_MOD_TABLE: if m & event.mod != 0: modifiers.append( tcod.event_constants._REVERSE_MOD_TABLE[m]) key = tcod.event_constants._REVERSE_SYM_TABLE.get( event.sym) elif event.type == "MOUSEMOTION": if event.tile != mouse: mouse = event.tile new_mouse = True continue elif event.type == "MOUSEBUTTONDOWN" and event.button == tcod.event.BUTTON_LEFT: if menu_state == const.MenuState.STANDARD: e = render.get_object_under_mouse( mouse, turns, player, entities, game_map, screen_width, map_width) if e: menu_state = const.MenuState.POPUP render.render_popup( root_console, popup_panel, map_width, map_height, [render.capitalize(e.name)] + e.describe()) need_flush = True else: msglog.add_log( "There is nothing to describe here.") elif menu_state == const.MenuState.POPUP: render.render_map(root_console, con, entities, player, game_map, screen_width, screen_height) render.render_log(root_console, log_panel, msglog, map_height) if boss: render.render_boss_hp(root_console, des_panel, map_height, boss) else: render.render_des(root_console, des_panel, map_height, "") render.render_sch(root_console, sch_panel, turns, map_width, player.time_malus) render.render_inv(root_console, inv_panel, player, map_width, sch_height) menu_state = const.MenuState.STANDARD need_flush = True else: # nothing interesting continue if menu_state == const.MenuState.STANDARD: action = keys.handle_player_turn_keys(key, modifiers) elif menu_state == const.MenuState.DROP: action = keys.handle_drop_keys(key, modifiers) elif menu_state == const.MenuState.EQUIP: action = keys.handle_equip_keys(key, modifiers) elif menu_state == const.MenuState.POPUP: action = keys.handle_popup_keys(key, modifiers) else: assert False use_weapon = action.get('use_weapon') if use_weapon: previous_active = player.active_weapon new_active = player.wequiped.get(use_weapon) if not new_active: msglog.add_log("You don't have this weapon.") elif previous_active == new_active: msglog.add_log("This weapon is already wielded.") else: player.change_active_weapon(new_active) player.active_weapon.equip_log(msglog) render_map = True render_inv = True help_popup = action.get('help') if help_popup: menu_state = const.MenuState.POPUP render.render_popup(root_console, popup_panel, map_width, map_height, const.help_strings) need_flush = True fullscreen = action.get("fullscreen") if fullscreen: tcod.console_set_fullscreen( not tcod.console_is_fullscreen()) descend = action.get('descend') if descend: stairs = game_map.is_stairs(player.x, player.y) boss_stairs = game_map.is_boss_stairs( player.x, player.y) assert not (stairs and boss_stairs) if stairs or boss_stairs: if boss_stairs and (not player.can_go_boss() or not boss_confirm): if not player.can_go_boss(): msglog.add_log( "This is the release exit. But you don't have five stable features!" ) elif not boss_confirm: msglog.add_log( "You feel anxious about this. Are you really sure that you are ready to release your game? If not, find the other stairs to continue your adventure." ) boss_confirm = True else: if stairs: msglog.add_log("You go down the stairs.") for e in entities: if isinstance(e, entity.Monster): e.dead(stabilize=False) turns.remove_turn(e) entities = [player] if stairs: game_map.make_map_bsp( turns, entities, player) else: boss = game_map.make_boss_map( turns, entities, player) const.n_bugs_max = [ const.boss_level_invok, const.boss_level_invok ] msglog.add_log( "To release your game, you need to fight your inner ennemy: self-doubt.", const.red) turns.add_turn( player.time_malus + player.time_move, const.TurnType.PLAYER, player) player.reset_time_malus() render_map = True new_turn = True break else: msglog.add_log("You see no stairs.") grab = action.get('pickup') if grab: if game_map.is_there_item_on_floor(player): if game_map.is_weapon_on_floor_directly_equipable( player): (item, key) = game_map.get_item_on_floor( player, entities) player.wequip(item, key) msglog.add_log("You equip a " + item.name + ".") render_inv = True elif player.is_inventory_full(): msglog.add_log("Your inventory is full.") assert not render_inv else: item, _ = game_map.get_item_on_floor( player, entities) msglog.add_log("You pick up a " + item.name + ".") render_inv = True if render_inv: if isinstance(item, entity.Weapon): l = item.wego.value.get("fego") msglog.add_log("It is effective against " + l[0].value.get("name") + ", " + l[1].value.get("name") + " and " + l[2].value.get("name") + " bugs.") elif isinstance(item, entity.Feature): wego = [ wego for wego in const.WeaponEgo if item.fego in wego.value.get("fego") ] assert len(wego) == 1 wego = wego[0] msglog.add_log( "Its bugs are squashed by " + wego.value.get("name") + " weapons.") else: assert False # render_inv = True else: msglog.add_log( "There is nothing on the floor to pick up.") drop = action.get('drop') if drop: if player.is_inventory_empty(): msglog.add_log("Your inventory is empty.") elif game_map.is_there_item_on_floor(player): msglog.add_log("There is already something there.") else: msglog.add_log("What do you want to drop? [abcde]") menu_state = const.MenuState.DROP equip = action.get('equip') if equip: if player.is_inventory_empty(): msglog.add_log("Your inventory is empty.") else: msglog.add_log( "What do you want to equip? [abcde]") menu_state = const.MenuState.EQUIP drop_unknow = action.get('drop_unknow') # we didn't understand what the player want to drop if drop_unknow: msglog.add_log("What do you want to drop? [abcde]") equip_unknow = action.get('equip_unknow') # we didn't understand what the player want to equip if equip_unknow: msglog.add_log("What do you want to equip? [abcde]") drop_key = action.get('drop_key') if drop_key: item = player.inventory.get(drop_key) if item: msglog.add_log("You drop a " + item.name + ".") game_map.drop_item_on_floor( player, entities, item, drop_key) menu_state = const.MenuState.STANDARD render_inv = True else: msglog.add_log("You don't have this item!") menu_state = const.MenuState.STANDARD equip_key = action.get('equip_key') if equip_key: item = player.inventory.get(equip_key) if item: menu_state = const.MenuState.STANDARD previous_active = player.active_weapon if isinstance(item, entity.Feature): out = player.fequip(item, equip_key) synergy = out.get("synergy") if synergy: if synergy == 2: msglog.add_log( "You feel a small synergy between your two " + item.fego.value.get("name") + " features.", color_active=const.green, color_inactive=const.desat_green2) elif synergy == 3: msglog.add_log( "You feel a good synergy between your three " + item.fego.value.get("name") + " features.", color_active=const.green, color_inactive=const.desat_green2) elif synergy == 4: msglog.add_log( "You feel a great synergy between your four " + item.fego.value.get("name") + " features!", color_active=const.green, color_inactive=const.desat_green2) elif synergy == 5: msglog.add_log( "You feel an incredible synergy between your five " + item.fego.value.get("name") + " features!", color_active=const.green, color_inactive=const.desat_green2) else: assert False elif isinstance(item, entity.Weapon): out = player.wequip(item, equip_key) render_map = True # update telepathy else: assert False previous = out.get("unstable-previous") level_problem_no_previous = out.get( "level-problem-no-previous") level_problem_previous = out.get( "level-problem-previous") inheritance = out.get("inheritance") if inheritance: msglog.add_log( "You upgraded your " + item.fego.value.get("name") + " " + item.fslot.value.get("name") + ": it is already quite stable!", color_active=const.green, color_inactive=const.desat_green2) item.stability = min( item.max_stability, max(item.stability, inheritance.stability)) render_inv = True turns.add_turn( player.time_malus + const.time_equip, const.TurnType.PLAYER, player) player.reset_time_malus() render_map = True new_turn = True break elif level_problem_previous: msglog.add_log( "You cannot equip a v" + str(item.level) + " feature on a v" + str(level_problem_previous.level) + " feature.") elif level_problem_no_previous: msglog.add_log("You need to equip a v1 " + item.fslot.value.get("name") + " feature first.") elif not previous: msglog.add_log("You equip a " + item.name + ".") if isinstance(item, entity.Weapon): msglog.add_log( "You can change your active weapon with [123]." ) if not previous_active: render_map = True player.active_weapon.equip_log(msglog) render_inv = True turns.add_turn( player.time_malus + const.time_equip, const.TurnType.PLAYER, player) player.reset_time_malus() render_map = True new_turn = True break else: msglog.add_log( "You try to equip the " + item.name + " but your " + previous.name + " is too unstable to be removed!") else: msglog.add_log("You don't have this item!") menu_state = const.MenuState.STANDARD cancel = action.get('cancel') if cancel: if menu_state == const.MenuState.POPUP: render.render_map(root_console, con, entities, player, game_map, screen_width, screen_height) render.render_log(root_console, log_panel, msglog, map_height) if boss: render.render_boss_hp(root_console, des_panel, map_height, boss) else: render.render_des(root_console, des_panel, map_height, "") render.render_sch(root_console, sch_panel, turns, map_width, player.time_malus) render.render_inv(root_console, inv_panel, player, map_width, sch_height) need_flush = True else: msglog.add_log("Nevermind.") menu_state = const.MenuState.STANDARD move = action.get('move') if move: dx, dy = move if (dx, dy) == (0, 0): turns.add_turn( player.time_malus + player.time_move, const.TurnType.PLAYER, player) player.reset_time_malus() render_map = True new_turn = True force_log = True break else: destination_x = player.x + dx destination_y = player.y + dy target = entity.get_blocking_entities_at_location( entities, destination_x, destination_y) if target and target != player: weapon = player.active_weapon if not weapon: msglog.add_log( "You have no weapon to attack with! Equip with w." ) else: if target == boss and weapon.wslot.value.get( "unstable"): msglog.add_log( "Your hack has no effect on " + boss.name + ".", color_active=const.red, color_inactive=const.desat_red) duration = weapon.duration dmg = 0 else: (dmg, duration, more_stable, less_stable) = attack( weapon, target, msglog, player, entities, turns) # stability may have changed if more_stable or less_stable: render_inv = True turns.add_turn( player.time_malus + duration, const.TurnType.PLAYER, player) player.reset_time_malus() new_turn = True if dmg > 0 and target != boss: render_map = True break elif not game_map.is_blocked( destination_x, destination_y): player.move(dx, dy) des = game_map.description_item_on_floor( player) if des: msglog.add_log("You see a " + des + " on the floor.") turns.add_turn( player.time_malus + player.time_move, const.TurnType.PLAYER, player) player.reset_time_malus() render_map = True fov_recompute = True new_turn = True force_log = True break elif current_turn.ttype == const.TurnType.ENEMY: e = current_turn.entity assert e.hp > 0, e.hp if e in entities: if e.distance_to(player) >= 2: # if close, attack moved = e.move_astar(player, entities, game_map, turns) if moved and (game_map.is_visible(e.x, e.y) or (player.active_weapon and isinstance( player.active_weapon, entity.TelepathicWeapon))): render_map = True turns.add_turn(e.speed_mov, const.TurnType.ENEMY, e) else: # if far, move turns.add_turn(e.speed_atk, const.TurnType.ENEMY, e) d = e.attack(player, turns) delta_malus = d.get("dmg") invok = d.get("invok") if invok: # the boss invoks minions msglog.add_log(e.name + " invokes " + invok.value.get("name") + " bugs!") for level in range(1, 4): nb = const.boss_level_invok[level - 1] for n in range(nb): new_e = game_map.spawn_boss( entities, invok, level, player) if new_e: turns.add_turn(e.speed_mov, const.TurnType.ENEMY, new_e) elif delta_malus: assert int(delta_malus) == delta_malus, delta_malus player.add_time_malus(delta_malus, e.fslot) else: missed = d.get("missed") # basic passive attack if missed and player.active_weapon and isinstance( player.active_weapon, entity.BasicWeapon) and not isinstance( e, entity.Boss) and random.randint( 1, 3) < 3: msglog.add_log("The " + e.name + " is burned by your " + player.active_weapon.name + "!") (dmg, duration, more_stable, less_stable) = attack(player.active_weapon, e, msglog, player, entities, turns, log_effective=False, passive=True) # stability may have changed if more_stable or less_stable: render_inv = True if dmg > 0: render_map = True new_turn = True elif current_turn.ttype == const.TurnType.SPAWN: # regurlarly, we spawn bugs if not boss: creator = player.fequiped.get(current_turn.entity) # stable features don't generate bugs if creator and not creator.is_stable() and sum( creator.n_bugs) < sum( const.n_bugs_max[creator.level - 1]): # the more stable, the slower it generates bugs chance = 1 - creator.stability / creator.max_stability / const.stability_threshold + 0.4 if random.random() < chance: e = game_map.spawn(entities, creator) if e: turns.add_turn(e.speed_mov, const.TurnType.ENEMY, e) turns.add_turn(const.spawn_interval, const.TurnType.SPAWN, current_turn.entity) new_turn = True elif current_turn.ttype == const.TurnType.MSG: # a message to this particular date msglog.add_log(current_turn.entity.string, current_turn.entity.color_active, current_turn.entity.color_inactive) new_turn = True elif current_turn.ttype == const.TurnType.GAME_OVER: # :( msglog.add_log( "Your self-doubt is too strong. You don't feel your game is worth showing to the world. Who said releasing a game was easy?", const.red, const.red) msglog.add_log("Score: " + str(player.get_score()), const.red, const.red) msglog.add_log("Game over.", const.red, const.red) render.render_log(root_console, log_panel, msglog, map_height) render.render_sch(root_console, sch_panel, turns, map_width, -1) tcod.console_flush() break # That's the end. again = True while again: for event in tcod.event.wait(): key = None modifiers = [] if event.type == "QUIT": raise SystemExit() elif event.type == "KEYDOWN": for m in tcod.event_constants._REVERSE_MOD_TABLE: if m & event.mod != 0: modifiers.append( tcod.event_constants._REVERSE_MOD_TABLE[m]) key = tcod.event_constants._REVERSE_SYM_TABLE.get( event.sym) action = keys.handle_popup_keys(key, modifiers) if action.get("cancel"): again = False tcod.console_flush()