def render_map(map_, slice_heights, edges, edges_y, objects, bk_objects, sky_colour, day, lights, settings, redraw_all): if settings_ref['render_c']: return render_c.render_map(map_, slice_heights, edges, edges_y, objects, sky_colour, settings, redraw_all) else: return render.render_map(map_, slice_heights, edges, edges_y, objects, bk_objects, sky_colour, day, lights, settings, redraw_all)
def update_display(self): sector = -1 state = None areas = None connections = None elements = None #sector = self.map_data.get_sector(self.mouse.map_pos.x, self.mouse.map_pos.y) self.screen.fill(COLOR_BACKGROUND) #elements = render.render_nav(self.nav_grid, self.screen, self.camera, self.mouse.map_pos) render.render_map(self.map_data, self.screen, self.camera, self.config, sector) areas, connections = render.render_mesh(self.nav_mesh, self.map_data, self.screen, self.camera, self.mouse.map_pos) #state = self.render_collision_box() self.render_debug_text(connections, state, elements, areas) render.draw_connection_path(self.screen, self.camera, self.point_start, self.point_end, self.path) render.draw_point(self.screen, self.camera, self.point_start) render.draw_point(self.screen, self.camera, self.point_end) pygame.display.flip()
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()
import pygame, sys from pygame.locals import * from map.tile import * from render import render_map pygame.init() pygame.font.init() SCREENWIDTH = 800 SCREENHEIGHT = 600 # Create a new drawing surface (window), width=300 height=300 DISPLAYSURF = pygame.display.set_mode((SCREENWIDTH, SCREENHEIGHT)) pygame.display.set_caption("Isometric!") while True: # Get all user events for event in pygame.event.get(): # if the user wants to quit if event.type == QUIT: #end the game and close the window pygame.quit() sys.exit() render_map(DISPLAYSURF, tilemap, colors, SCREENWIDTH, SCREENHEIGHT, MAPWIDTH, MAPHEIGHT, TILESIZE) # Update the display pygame.display.update()
def game(blocks, meta, map_, save): x = meta['player_x'] y = meta['player_y'] dx = 0 dy = 0 dt = 0 # Tick df = 0 # Frame dc = 0 # Cursor ds = 0 # Selector dinv = False # Inventory dcraft = False # Crafting width = 40 height = terrain.world_gen['height'] - 1 FPS = 15 # Max TPS = 10 # Ticks IPS = 20 # Input MPS = 15 # Movement SUN_TICK = radians(1/32) old_bk_objects = None old_edges = None redraw = False last_frame = [] last_out = time() last_tick = time() last_inp = time() last_move = time() inp = None jump = 0 cursor = 0 crafting = False crafting_sel = 0 crafting_list = [] inv_sel = 0 c_hidden = True new_slices = {} alive = True events = [] crafting_list, crafting_sel = player.get_crafting( meta['inv'], crafting_list, crafting_sel, blocks ) # Game loop game = True with NonBlockingInput() as nbi: while game: # Finds display boundaries edges = (x - int(width / 2), x + int(width / 2)) extended_edges = (edges[0]-render.max_light, edges[1]+render.max_light) # Generates new terrain slice_list = terrain.detect_edges(map_, extended_edges) for pos in slice_list: new_slices[pos] = terrain.gen_slice(pos, meta, blocks) map_[pos] = new_slices[pos] # Save new terrain to file if new_slices: saves.save_map(save, new_slices) new_slices = {} redraw = True # Moving view if not edges == old_edges: view = terrain.move_map(map_, edges) extended_view = terrain.move_map(map_, extended_edges) old_edges = edges redraw = True # Sun has moved bk_objects, sky_colour = render.bk_objects(meta['tick'], width) if not bk_objects == old_bk_objects: old_bk_objects = bk_objects redraw = True # Draw view if redraw and time() >= 1/FPS + last_out: df = 1 redraw = False last_out = time() cursor_colour = player.cursor_colour( x, y, cursor, map_, blocks, meta['inv'], inv_sel ) objects = player.assemble_player( int(width / 2), y, cursor, cursor_colour, c_hidden ) lights = render.get_lights(extended_view, edges[0], blocks, bk_objects) out, last_frame = render.render_map( view, objects, blocks, bk_objects, sky_colour, lights, meta['tick'], last_frame ) crafting_grid = render.render_grid( player.CRAFT_TITLE, crafting, crafting_list, blocks, height, crafting_sel ) inv_grid = render.render_grid( player.INV_TITLE, not crafting, meta['inv'], blocks, height, inv_sel ) label = (player.label(crafting_list, crafting_sel, blocks) if crafting else player.label(meta['inv'], inv_sel, blocks)) out += render.render_grids( [ [inv_grid, crafting_grid], [[label]] ], width, height ) print(out) in_game_debug('({}, {})'.format(x, y), 0, 0) else: df = 0 # Respawn player if dead if not alive and df: alive = True x, y = player.respawn(meta) if dt: # Player falls when no solid block below it if jump > 0: # Countdown till fall jump -= 1 elif not terrain.is_solid(blocks, map_[x][y+1]): # Fall y += 1 redraw = True new_new_slices = process_events(events, map_, blocks) new_slices.update(new_new_slices) map_.update(new_new_slices) # If no block below, kill player try: block = map_[x][y+1] except IndexError: alive = False # Receive input if a key is pressed char = str(nbi.char()).lower() inp = char if char in 'wadkjliuo-=' else None # Input Frame if time() >= (1/IPS) + last_inp and alive and inp: if time() >= (1/MPS) + last_move: # Update player position dx, dy, jump = player.get_pos_delta( str(inp), map_, x, y, blocks, jump) y += dy x += dx last_move = time() new_new_slices, meta['inv'], inv_sel, new_events, dinv = \ player.cursor_func(str(inp), map_, x, y, cursor, inv_sel, meta, blocks) map_.update(new_new_slices) new_slices.update(new_new_slices) events += new_events dcraft, dcraftC, dcraftN = False, False, False if dinv: crafting = False if crafting: # Craft if player pressed craft meta['inv'], inv_sel, crafting_list, dcraftC = \ player.crafting(str(inp), meta['inv'], inv_sel, crafting_list, crafting_sel, blocks) # Increment/decrement craft no. crafting_list, dcraftN = \ player.craft_num(str(inp), meta['inv'], crafting_list, crafting_sel, blocks) dcraft = dcraftC or dcraftN # Update crafting list if dinv or dcraft: crafting_list, crafting_sel = \ player.get_crafting(meta['inv'], crafting_list, crafting_sel, blocks, dcraftC) if not len(crafting_list): crafting = False dc = player.move_cursor(inp) cursor = (cursor + dc) % 6 ds = player.move_sel(inp) if crafting: crafting_sel = ((crafting_sel + ds) % len(crafting_list) if len(crafting_list) else 0) else: inv_sel = ((inv_sel + ds) % len(meta['inv']) if len(meta['inv']) else 0) if any((dx, dy, dc, ds, dinv, dcraft)): meta['player_x'], meta['player_y'] = x, y saves.save_meta(save, meta) redraw = True if dx or dy: c_hidden = True if dc: c_hidden = False last_inp = time() inp = None if char in 'c': redraw = True crafting = not crafting and len(crafting_list) # Hard pause if DEBUG and char in '\n': input() char = '0' # Pause game if char in ' \n': meta['player_x'], meta['player_y'] = x, y saves.save_meta(save, meta) redraw = True last_frame = [] if ui.pause() == 'exit': game = False # Increase tick if time() >= (1/TPS) + last_tick: dt = 1 meta['tick'] += SUN_TICK last_tick = time() else: dt = 0
if is_pressed('w'): player.x -= 0.05 * cos(player.v_dir) player.y -= 0.05 * sin(player.v_dir) if is_pressed("s"): player.x += 0.05 * cos(player.v_dir) player.y += 0.05 * sin(player.v_dir) if is_pressed("d"): player.v_dir += 0.1 if is_pressed("a"): player.v_dir -= 0.1 else: player.v_dir += randint(0, 10) / 200 player.x -= randint(-1, 1) / 200 * cos(player.v_dir) player.y -= randint(-1, 1) / 200 * sin(player.v_dir) # remove old images from canvas for k in canvas.children: try: k.destroy() except: pass # add images map_img = ImageTk.PhotoImage(render_map(myMap, player)) image = ImageTk.PhotoImage(create_image(myMap, player)) imagesprite = canvas.create_image(WIDTH / 2, HEIGHT / 2, image=image) mapsprite = canvas.create_image(map_img.width() / 2, map_img.height() / 2, image=map_img) canvas.update()
from field import Field from player import Player from render import create_image, render_map player = Player(6, 6, 3.14159 / 4, 3.14159 / 3) field = Field() # show image img = create_image(field, player) img.show() map = render_map(field, player) map.show()
def game(server, settings): x, y = server.pos dx = 0 dy = 0 dt = 0 # Tick df = 0 # Frame dc = 0 # Cursor ds = 0 # Selector dinv = False # Inventory dcraft = False # Crafting FPS = 15 # Max IPS = 20 # Input MPS = 15 # Movement old_bk_objects = None old_edges = None last_frame = {} last_out = time() last_inp = time() last_move = time() inp = None jump = 0 cursor = 0 crafting = False crafting_sel = 0 crafting_list = [] inv_sel = 0 c_hidden = True new_blocks = {} alive = True events = [] crafting_list, crafting_sel = player.get_crafting( server.inv, crafting_list, crafting_sel ) # Game loop with NonBlockingInput() as nbi: while server.game: x, y = server.pos width = settings.get('width') height = settings.get('height') sleep(1/1000) # Finds display boundaries edges = (x - int(width / 2), x + int(width / 2)) edges_y = (y - int(height / 2), y + int(height / 2)) if edges_y[1] > data.world_gen['height']: edges_y = (data.world_gen['height'] - height, data.world_gen['height']) elif edges_y[0] < 0: edges_y = (0, height) extended_edges = (edges[0]-render.max_light, edges[1]+render.max_light) slice_list = terrain.detect_edges(server.map_, extended_edges) if slice_list: log('slices to load', slice_list) chunk_list = terrain.get_chunk_list(slice_list) server.get_chunks(chunk_list) server.unload_slices(extended_edges) # Moving view if not edges == old_edges or server.view_change: extended_view = terrain.move_map(server.map_, extended_edges) old_edges = edges server.redraw = True server.view_change = False # Sun has moved bk_objects, sky_colour, day = render.bk_objects(server.time, width, settings.get('fancy_lights')) if not bk_objects == old_bk_objects: old_bk_objects = bk_objects server.redraw = True # Draw view if server.redraw and time() >= 1/FPS + last_out: df = 1 server.redraw = False last_out = time() if settings.get('gravity'): blocks = terrain.apply_gravity(server.map_, edges) if blocks: server.set_blocks(blocks) cursor_colour = player.cursor_colour( x, y, cursor, server.map_, server.inv, inv_sel ) objects = player.assemble_players( server.current_players, x, y, int(width / 2), edges ) if not c_hidden: objects.append(player.assemble_cursor( int(width / 2), y, cursor, cursor_colour )) lights = render.get_lights(extended_view, edges[0], bk_objects) out, last_frame = render.render_map( server.map_, server.slice_heights, edges, edges_y, objects, bk_objects, sky_colour, day, lights, last_frame, settings.get('fancy_lights') ) crafting_grid = render.render_grid( player.CRAFT_TITLE, crafting, crafting_list, height, crafting_sel ) inv_grid = render.render_grid( player.INV_TITLE, not crafting, server.inv, height, inv_sel ) label = (player.label(crafting_list, crafting_sel) if crafting else player.label(server.inv, inv_sel)) out += render.render_grids( [ [inv_grid, crafting_grid], [[label]] ], width, height ) print(out) in_game_log('({}, {})'.format(x, y), 0, 0) else: df = 0 # Respawn player if dead if not alive and df: alive = True server.respawn() if dt and server.chunk_loaded(x): if not settings.get('flight'): # Player falls when no solid block below it if jump > 0: # Countdown till fall jump -= 1 elif not terrain.is_solid(server.map_[x][y+1]): # Fall y += 1 server.pos = x, y server.redraw = True new_blocks = process_events(events, server.map_) if new_blocks: server.set_blocks(new_blocks) # If no block below, kill player try: block = server.map_[x][y+1] except IndexError: alive = False # Receive input if a key is pressed char = str(nbi.char()).lower() inp = char if char in 'wasdkjliuo-=' else None # Input Frame if time() >= (1/IPS) + last_inp and alive and inp: if time() >= (1/MPS) + last_move: # Update player position dx, dy, jump = player.get_pos_delta( str(inp), server.map_, x, y, jump, settings.get('flight')) y += dy x += dx last_move = time() new_blocks, inv, inv_sel, new_events, dinv = \ player.cursor_func( str(inp), server.map_, x, y, cursor, inv_sel, server.inv ) if dinv: server.inv = inv if new_blocks: server.set_blocks(new_blocks) events += new_events dcraft, dcraftC, dcraftN = False, False, False if dinv: crafting = False if crafting: # Craft if player pressed craft inv, inv_sel, crafting_list, dcraftC = \ player.crafting(str(inp), server.inv, inv_sel, crafting_list, crafting_sel) if dcraftC: server.inv = inv # Increment/decrement craft no. crafting_list, dcraftN = \ player.craft_num(str(inp), server.inv, crafting_list, crafting_sel) dcraft = dcraftC or dcraftN # Update crafting list if dinv or dcraft: crafting_list, crafting_sel = \ player.get_crafting(server.inv, crafting_list, crafting_sel, dcraftC) if not len(crafting_list): crafting = False dc = player.move_cursor(inp) cursor = (cursor + dc) % 6 ds = player.move_sel(inp) if crafting: crafting_sel = ((crafting_sel + ds) % len(crafting_list) if len(crafting_list) else 0) else: inv_sel = ((inv_sel + ds) % len(server.inv) if len(server.inv) else 0) if any((dx, dy, dc, ds, dinv, dcraft)): server.pos = x, y server.redraw = True if dx or dy: c_hidden = True if dc: c_hidden = False last_inp = time() inp = None if char in 'c': server.redraw = True crafting = not crafting and len(crafting_list) # Hard pause if DEBUG and char in '\n': input() char = '0' # Pause game if char in ' \n': server.pos = x, y server.redraw = True last_frame = {} if ui.pause(server, settings) == 'exit': server.logout() dt = server.dt()