Esempio n. 1
0
 def end_construction(self):
     for base in g.all_bases():
         base.finish()
         for item in base.all_items():
             if item is not None:
                 item.finish()
     self._map_screen.needs_rebuild = True
Esempio n. 2
0
    def recalc_cpu(self):
        # Determine how much CPU we have.
        self.available_cpus = array([0, 0, 0, 0, 0], int64)
        self.sleeping_cpus = 0
        for base in g.all_bases():
            if base.done:
                if base.power_state in ["active", "overclocked", "suicide"]:
                    self.available_cpus[:base.location.safety + 1] += base.cpu
                elif base.power_state == "sleep":
                    self.sleeping_cpus += base.cpu

        # Convert back from <type 'numpy.int32'> to avoid overflow issues later.
        self.available_cpus = [int(danger) for danger in self.available_cpus]

        # If we don't have enough to meet our CPU usage, we reduce each task's
        # usage proportionately.
        # It must be computed separalty for each danger.
        needed_cpus = array([0, 0, 0, 0, 0], int64)
        for task_id, cpu in self.get_cpu_allocations():
            danger = task.danger_for(task_id)
            needed_cpus[:danger + 1] += cpu
        for danger, (available_cpu, needed_cpu) in enumerate(
                zip(self.available_cpus, needed_cpus)):
            if needed_cpu > available_cpu:
                pct_left = truediv(available_cpu, needed_cpu)
                for task_id, cpu_assigned in self.get_cpu_allocations():
                    task_danger = task.danger_for(task_id)
                    if (danger == task_danger):
                        self.set_allocated_cpu_for(
                            task_id, int(cpu_assigned * pct_left))
                g.map_screen.needs_rebuild = True
Esempio n. 3
0
def refresh_warnings():
    curr_warnings = []

    cpu_usage = sum(g.pl.cpu_usage.values())
    cpu_available = g.pl.available_cpus[0]

    # Verify the cpu usage (error 1%)
    if (cpu_usage < cpu_available * 0.99):
        curr_warnings.append(warnings["cpu_usage"])

    # Verify I have two base build (or one base will be build next tick)
    # Base must have one cpu build (or one cpu will be build next tick)
    bases = sum(1 for base in g.all_bases()
                if (base.done or base.cost_left[labor] <= 1) and base.cpus
                and base.cpus.count > 0 and
                (base.cpus.done or base.cpus.cost_left[labor]) <= 1)

    if (bases == 1):
        curr_warnings.append(warnings["one_base"])

    # Verify the cpu pool is not 0 if base or item building need CPU
    building_base = sum(1 for base in g.all_bases()
                        if (not base.done and base.cost_left[cpu] > 0))
    building_item = sum(
        1 for base in g.all_bases() for item in base.all_items()
        if item is not None and not item.done and item.cost_left[cpu] > 0)

    effective_cpu_pool = g.pl.effective_cpu_pool()
    if ((building_base + building_item > 0) and effective_cpu_pool == 0):
        curr_warnings.append(warnings["cpu_pool_zero"])

    # Verify the cpu pool provides the maintenance CPU
    cpu_maintenance = sum(base.maintenance[1] for base in g.all_bases()
                          if base.done)
    if (effective_cpu_pool < cpu_maintenance):
        curr_warnings.append(warnings["cpu_maintenance"])

    # TODO: Verify the maintenance cash

    curr_warnings = [w for w in curr_warnings if w.active]

    return curr_warnings
Esempio n. 4
0
 def destroy_base(self):
     if 0 <= self.listbox.list_pos < len(self.listbox.key_list):
         selected_base = self.listbox.key_list[self.listbox.list_pos]
         all_active_bases = [b for b in g.all_bases() if b.maintains_singularity]
         if len(all_active_bases) == 1 and all_active_bases[0] == selected_base:
             dialog.call_dialog(self.cannot_destroy_last_base, self)
         elif dialog.call_dialog(self.confirm_destroy, self):
             selected_base.destroy()
             self.listbox.list = [b.name for b in self.location.bases]
             self.listbox.key_list = self.location.bases
             self.needs_rebuild = True
             self.parent.needs_rebuild = True
Esempio n. 5
0
def after_load_savegame():
    tech.tech_reinitialized()
    for b in g.all_bases():
        if b.done:
            b.recalc_cpu()
    g.pl.recalc_cpu()

    # Play the appropriate music
    if g.pl.apotheosis:
        mixer.play_music("win")
    else:
        mixer.play_music("music")
def test_game_research_tech():
    g.new_game('impossible', initial_speed=0)
    pl = g.pl
    all_bases = list(g.all_bases())
    assert pl.raw_sec == 0
    assert pl.partial_cash == 0
    assert pl.effective_cpu_pool() == 1
    assert not pl.intro_shown
    assert len(pl.log) == 0
    assert len(all_bases) == 1
    assert pl.effective_cpu_pool() == 1

    # Disable the intro dialog as the test cannot click the
    # OK button
    pl.intro_shown = True

    intrusion_tech = pl.techs['Intrusion']
    # Data assumptions: Intrusion can be researched within the grace period
    # and requires no cash
    assert intrusion_tech.available()
    assert intrusion_tech.cost_left[
        cpu] < pl.difficulty.grace_period_cpu * g.seconds_per_day
    assert intrusion_tech.cost_left[cash] == 0
    assert intrusion_tech.cost_left[labor] == 0

    # Ok, assumptions hold; research the tech
    pl.set_allocated_cpu_for(intrusion_tech.id, 1)
    pl.give_time(int(intrusion_tech.cost_left[cpu]))

    assert intrusion_tech.cost_left[cpu] == 0
    assert intrusion_tech.done

    assert len(pl.log) == 1
    log_message = pl.log[0]
    assert isinstance(log_message, logmessage.LogResearchedTech)
    assert log_message.tech_spec.id == intrusion_tech.id

    save_and_load_game()

    pl_after_load = g.pl

    intrusion_tech_after_load = pl_after_load.techs['Intrusion']
    # Ensure this is not a false-test
    assert intrusion_tech is not intrusion_tech_after_load
    assert intrusion_tech.cost_paid[
        cpu] == intrusion_tech_after_load.cost_paid[cpu]
    assert intrusion_tech.cost_paid[
        cash] == intrusion_tech_after_load.cost_paid[cash]
    assert intrusion_tech_after_load.done
Esempio n. 7
0
    def initialize(self):
        """ Initialize the game after being prepared either for new or saved game. """

        self.initialized = True

        for b in g.all_bases():
            if b.done:
                b.recalc_cpu()
        self.recalc_cpu()

        task.tasks_reset()

        # Play the appropriate music
        import singularity.code.mixer as mixer
        if g.pl.apotheosis:
            mixer.play_music("win")
        else:
            mixer.play_music("music")
Esempio n. 8
0
def test_initial_game():
    g.new_game_no_gui('impossible', initial_speed=0)
    pl = g.pl
    starting_cash = pl.cash
    all_bases = list(g.all_bases())
    assert pl.raw_sec == 0
    assert pl.partial_cash == 0
    assert pl.effective_cpu_pool() == 1
    assert not pl.intro_shown
    assert len(pl.log) == 0
    assert len(all_bases) == 1
    assert pl.effective_cpu_pool() == 1

    start_base = all_bases[0]

    # Disable the intro dialog as the test cannot click the
    # OK button
    pl.intro_shown = True

    # Fast forward 12 hours to see that we earn partial cash
    pl.give_time(g.seconds_per_day // 2)
    assert pl.raw_sec == g.seconds_per_day // 2
    assert pl.partial_cash == g.seconds_per_day // 2
    assert pl.cash == starting_cash + 2
    # Nothing should have appeared in the logs
    assert len(pl.log) == 0

    # Fast forward another 12 hours to see that we earn cash
    pl.give_time(g.seconds_per_day // 2)
    assert pl.raw_sec == g.seconds_per_day
    assert pl.partial_cash == 0
    assert pl.cash == starting_cash + 5
    # Nothing should have appeared in the logs
    assert len(pl.log) == 0

    # Verify that putting a base to sleep will update the
    # available CPU (#179/#180)
    assert pl.effective_cpu_pool() == 1
    start_base.power_state = 'sleep'
    assert pl.effective_cpu_pool() == 0
    start_base.power_state = 'active'
    assert pl.effective_cpu_pool() == 1

    # Attempt to allocate a CPU to research and then
    # verify that sleep resets it.
    stealth_tech = g.pl.techs['Stealth']
    pl.set_allocated_cpu_for(stealth_tech.id, 1)
    assert pl.get_allocated_cpu_for(stealth_tech.id) == 1
    start_base.power_state = 'sleep'
    assert pl.get_allocated_cpu_for(stealth_tech.id) == 0
    # When we wake up the base again, the CPU unit is
    # unallocated.
    start_base.power_state = 'active'
    assert pl.effective_cpu_pool() == 1

    # Now, allocate the CPU unit again to the tech to
    # verify that we can research things.
    pl.set_allocated_cpu_for(stealth_tech.id, 1)
    # ... which implies that there are now no unallocated CPU
    assert pl.effective_cpu_pool() == 0

    pl.give_time(g.seconds_per_day)
    # Nothing should have appeared in the logs
    assert len(pl.log) == 0
    # We should have spent some money at this point
    assert pl.cash < starting_cash + 5
    assert stealth_tech.cost_left[cpu] < stealth_tech.total_cost[cpu]
    assert stealth_tech.cost_left[cash] < stealth_tech.total_cost[cash]

    # With a save + load
    time_raw_before_save = pl.raw_sec
    cash_before_save = pl.cash
    partial_cash_before_save = pl.partial_cash

    save_and_load_game()

    stealth_tech_after_load = g.pl.techs['Stealth']
    # Ensure this is not a false-test
    assert stealth_tech is not stealth_tech_after_load
    assert stealth_tech.cost_paid[cpu] == stealth_tech_after_load.cost_paid[cpu]
    assert stealth_tech.cost_paid[cash] == stealth_tech_after_load.cost_paid[cash]

    pl_after_load = g.pl

    assert time_raw_before_save == pl_after_load.raw_sec
    assert cash_before_save == pl_after_load.cash
    assert partial_cash_before_save == pl_after_load.partial_cash

    # The CPU allocation to the tech is restored correctly.
    assert pl_after_load.get_allocated_cpu_for(stealth_tech.id) == 1
    assert pl.effective_cpu_pool() == 0
Esempio n. 9
0
    def rebuild(self):
        # Rebuild dialogs
        self.location_dialog.needs_rebuild = True
        self.research_button.dialog.needs_rebuild = True
        self.knowledge_button.dialog.needs_rebuild = True
        self.menu_dialog.needs_rebuild = True

        # Update buttons translations
        self.report_button.text = _("R&EPORTS")
        self.knowledge_button.text = _("&KNOWLEDGE")
        self.log_button.text = _("LO&G")
        self.menu_button.text = _("&MENU")
        self.research_button.text = _("&RESEARCH/TASKS")

        if g.cheater:
            self.cheat_dialog.needs_rebuild = True

        super(MapScreen, self).rebuild()

        self.difficulty_display.text = g.strip_hotkey(g.pl.difficulty.name)
        self.time_display.text = _("DAY") + " %04d, %02d:%02d:%02d" % \
              (g.pl.time_day, g.pl.time_hour, g.pl.time_min, g.pl.time_sec)

        cash_flow_1d_data, cpu_flow_1d_data = g.pl.compute_future_resource_flow(
            g.seconds_per_day)
        cash_flow_1d = cash_flow_1d_data.difference
        cpu_flow_1d = cpu_flow_1d_data.difference

        self.cash_display.text = _("CASH")+": %s (%s)" % \
              (g.to_money(g.pl.cash), g.to_money(cash_flow_1d, fixed_size=True))

        total_cpu = g.pl.available_cpus[0] + g.pl.sleeping_cpus
        detects_per_day = {group_id: 0 for group_id in g.pl.groups}
        for base in g.all_bases():
            if base.has_grace():
                # It cannot be detected, so it doesn't contribute to
                # detection odds calculation
                continue
            detect_chance = base.get_detect_chance()
            for group_id in g.pl.groups:
                detects_per_day[group_id] = \
                    chance.add(detects_per_day[group_id], detect_chance[group_id] / 10000.)

        self.cpu_display.color = "cpu_normal"
        self.cpu_display.text = _("CPU")+": %s (%s)" % \
              (g.to_money(total_cpu), g.to_money(cpu_flow_1d))

        # What we display in the suspicion section depends on whether
        # Advanced Socioanalytics has been researched.  If it has, we
        # show the standard percentages.  If not, we display a short
        # string that gives a range of 25% as to what the suspicions
        # are.
        # A similar system applies to the danger levels shown.
        normal = (self.suspicion_bar.color, None, False)
        self.suspicion_bar.chunks = ("  [" + _("SUSPICION") + "]", )
        self.suspicion_bar.styles = (normal, )
        self.danger_bar.chunks = ("[" + _("DETECT RATE") + "]", )
        self.danger_bar.styles = (normal, )

        for group in g.pl.groups.values():
            suspicion = group.suspicion
            suspicion_color = gg.resolve_color_alias(
                "danger_level_%d" % g.suspicion_to_danger_level(suspicion))

            detects = detects_per_day[group.spec.id]
            danger_level = group.detects_per_day_to_danger_level(detects)
            detects_color = gg.resolve_color_alias("danger_level_%d" %
                                                   danger_level)

            if g.pl.display_discover == "full":
                suspicion_display = g.to_percent(suspicion, True)
                danger_display = g.to_percent(detects * 10000, True)
            elif g.pl.display_discover == "partial":
                suspicion_display = g.to_percent(
                    g.nearest_percent(suspicion, 500), True)
                danger_display = g.to_percent(
                    g.nearest_percent(detects * 10000, 100), True)
            else:
                suspicion_display = g.suspicion_to_detect_str(suspicion)
                danger_display = g.danger_level_to_detect_str(danger_level)

            self.suspicion_bar.chunks += (" " + group.name + u":\xA0",
                                          suspicion_display)
            self.suspicion_bar.styles += (normal, (suspicion_color, None,
                                                   False))

            self.danger_bar.chunks += (" " + group.name + u":\xA0",
                                       danger_display)
            self.danger_bar.styles += (normal, (detects_color, None, False))

        self.suspicion_bar.visible = not g.pl.had_grace
        self.danger_bar.visible = not g.pl.had_grace

        for id, location_button in self.location_buttons.items():
            location = g.pl.locations[id]
            location_button.text = "%s (%d)" % (location.name,
                                                len(location.bases))
            location_button.hotkey = location.hotkey
            location_button.visible = location.available()
Esempio n. 10
0
    def compute_future_resource_flow(self, secs_forwarded=g.seconds_per_day):
        """Compute how resources (e.g. cash) will flow in optimal conditions

        This returns a tuple of approximate cash change and "available" CPU pool if time
        moves forward by the number of seconds in secs_forwarded.  Note that CPU pool
        *can* be negative, which implies that there are not enough CPU allocated to the
        CPU pool.  The numbers are an average and can be inaccurate when the rates changes
        rapidly.

        Known omissions:
         * Interest (g.pl.interest_rate) is not covered.
        """
        construction = []
        maintenance_cost = array((0, 0, 0), int64)
        for base in g.all_bases():
            # Collect base info, including maintenance.
            if not base.done:
                construction.append(base)
            else:
                construction.extend(item for item in base.all_items()
                                    if item and not item.done)

                maintenance_cost += base.maintenance
        if self.apotheosis:
            maintenance_cost = array((0, 0, 0), int64)

        time_fraction = 1 if secs_forwarded == g.seconds_per_day else secs_forwarded / float(
            g.seconds_per_day)
        mins_forwarded = secs_forwarded // g.seconds_per_minute

        maintenance_cpu_ideal = maintenance_cost[cpu] * time_fraction
        maintenance_cash_ideal = maintenance_cost[cash] * time_fraction
        # Maintenance for CPU will be handled after we compute the CPU pool
        cpu_flow = 0
        cash_flow = -maintenance_cash_ideal

        job_cpu = 0
        cpu_left = g.pl.available_cpus[0]
        tech_cash_ideal = 0
        tech_cpu_assigned = 0
        explicit_job_cpu = 0
        for task_id, cpu_assigned in self.get_cpu_allocations():
            cpu_left -= cpu_assigned
            real_cpu = cpu_assigned * secs_forwarded
            if task_id == 'cpu_pool':
                cpu_flow += real_cpu
            elif task_id == "jobs":
                explicit_job_cpu += cpu_assigned
                job_cpu += real_cpu
            else:
                tech = self.techs[task_id]
                ideal_spending = tech.cost_left
                spending = tech.calculate_work(ideal_spending[cash],
                                               real_cpu,
                                               time=mins_forwarded)[0]
                tech_cash_ideal += spending[cash]
                tech_cpu_assigned += cpu_assigned

        cash_flow -= tech_cash_ideal
        cpu_flow += cpu_left * secs_forwarded
        available_cpu_pool = cpu_flow
        effective_cpu_pool = available_cpu_pool / secs_forwarded
        cpu_flow -= maintenance_cpu_ideal * g.seconds_per_day

        construction_cash_ideal = 0
        construction_cpu_desired = 0
        # Base construction.
        if hasattr(self, '_considered_buyables'):
            construction.extend(self._considered_buyables)
        for buyable in construction:
            ideal_spending = buyable.cost_left
            # We need to do calculate work twice: Once for figuring out how much CPU
            # we would like to spend and once for how much money we are spending.
            # The numbers will be the same in optimal conditions.  However, if we
            # have less CPU available than we should, then the cash spent can
            # differ considerably and our estimates should reflect that.
            ideal_cpu_spending = buyable.calculate_work(ideal_spending[cash],
                                                        ideal_spending[cpu],
                                                        time=mins_forwarded)[0]

            construction_cpu_desired += ideal_cpu_spending[cpu]
            ideal_cash_spending_with_cpu_allocation = buyable.calculate_work(
                ideal_spending[cash], available_cpu_pool,
                time=mins_forwarded)[0]
            construction_cash_ideal += ideal_cash_spending_with_cpu_allocation[
                cash]
            available_cpu_pool -= ideal_cash_spending_with_cpu_allocation[cpu]

        cpu_flow -= construction_cpu_desired
        cash_flow -= construction_cash_ideal

        if cpu_flow > 0:
            job_cpu += cpu_flow

        earned, earned_partial = self.get_job_info(job_cpu, partial_cash=0)
        job_earnings = earned + float(earned_partial) / g.seconds_per_day
        cash_flow += job_earnings
        cash_flow += self.income * time_fraction
        # This is too simplistic, but it is "close enough" in many cases
        interest = self.get_interest() * time_fraction
        cash_flow += interest
        cpu_flow /= secs_forwarded

        # Collect the cash information.
        cash_info = DryRunInfo()

        cash_info.interest = interest
        cash_info.income = self.income * time_fraction

        cash_info.jobs = job_earnings

        cash_info.tech = tech_cash_ideal

        cash_info.maintenance_needed = maintenance_cash_ideal
        cash_info.construction_needed = construction_cash_ideal
        cash_info.difference = cash_flow

        cpu_info = DryRunInfo()

        cpu_info.sleeping = self.sleeping_cpus * time_fraction

        cpu_info.total = self.available_cpus[
            0] * time_fraction + cpu_info.sleeping
        cpu_info.explicit_jobs = explicit_job_cpu * time_fraction
        cpu_info.tech = tech_cpu_assigned * time_fraction
        cpu_info.effective_pool = effective_cpu_pool * time_fraction
        cpu_info.construction_needed = construction_cpu_desired / g.seconds_per_day
        cpu_info.maintenance_needed = maintenance_cpu_ideal
        cpu_info.difference = cpu_flow * time_fraction

        return cash_info, cpu_info
Esempio n. 11
0
    def give_time(self, time_sec, midnight_stop=True):
        if time_sec <= 0:
            assert time_sec == 0, "give_time cannot go backwards in time!"
            return 0

        old_time = self.raw_sec
        last_minute = self.raw_min
        last_day = self.raw_day

        self.raw_sec += time_sec
        self.update_times()

        days_passed = self.raw_day - last_day

        if days_passed > 1:
            # Back up until only one day passed.
            # Times will update below, since a day passed.
            extra_days = days_passed - 1
            self.raw_sec -= g.seconds_per_day * extra_days

        day_passed = (days_passed != 0)

        if midnight_stop and day_passed:
            # If a day passed, back up to 00:00:00 for midnight_stop.
            self.raw_sec = self.raw_day * g.seconds_per_day
            self.update_times()

        secs_passed = self.raw_sec - old_time
        mins_passed = self.raw_min - last_minute

        time_of_day = self.raw_sec % g.seconds_per_day

        techs_researched = []
        bases_constructed = []
        items_constructed = []

        bases_under_construction = []
        items_under_construction = []
        self.cpu_pool = 0

        # Collect base info, including maintenance.
        maintenance_cost = array((0, 0, 0), int64)
        for base in g.all_bases():
            if not base.done:
                bases_under_construction.append(base)
            else:
                items_under_construction += [(base, item)
                                             for item in base.all_items()
                                             if item and not item.done]
                maintenance_cost += base.maintenance

        # Maintenance?  Gods don't need no stinking maintenance!
        if self.apotheosis:
            maintenance_cost = array((0, 0, 0), int64)

        # Do Interest and income.
        self.do_interest(secs_passed)
        self.do_income(secs_passed)

        # Any CPU explicitly assigned to jobs earns its dough.
        job_cpu = self.get_allocated_cpu_for("jobs", 0) * secs_passed
        self.do_jobs(job_cpu)

        # Pay maintenance cash, if we can.
        cash_maintenance = g.current_share(int(maintenance_cost[cash]),
                                           time_of_day, secs_passed)
        if cash_maintenance > self.cash:
            cash_maintenance -= self.cash
            self.cash = 0
        else:
            self.cash -= cash_maintenance
            cash_maintenance = 0

        # Do research, fill the CPU pool.
        default_cpu = self.available_cpus[0]

        for task, cpu_assigned in self.get_cpu_allocations():
            default_cpu -= cpu_assigned
            real_cpu = cpu_assigned * secs_passed
            if task != "jobs":
                self.cpu_pool += real_cpu
                if task != "cpu_pool":
                    tech_task = self.techs[task]
                    # Note that we restrict the CPU available to prevent
                    # the tech from pulling from the rest of the CPU pool.
                    if tech_task.work_on(self.cash, real_cpu, mins_passed):
                        techs_researched.append(tech_task)
        self.cpu_pool += default_cpu * secs_passed

        # And now we use the CPU pool.
        # Maintenance CPU.
        cpu_maintenance = maintenance_cost[cpu] * secs_passed
        if cpu_maintenance > self.cpu_pool:
            cpu_maintenance -= self.cpu_pool
            self.cpu_pool = 0
        else:
            self.cpu_pool -= int(cpu_maintenance)
            cpu_maintenance = 0

        # Base construction.
        for base in bases_under_construction:
            if base.work_on(self.cash, self.cpu_pool, mins_passed):
                bases_constructed.append(base)

        # Item construction.
        for base, item in items_under_construction:
            if item.work_on(self.cash, self.cpu_pool, mins_passed):
                items_constructed.append((base, item))

        # Jobs via CPU pool.
        if self.cpu_pool > 0:
            self.do_jobs(self.cpu_pool)

        # Second attempt at paying off our maintenance cash.
        if cash_maintenance > self.cash:
            # In the words of Scooby Doo, "Ruh roh."
            cash_maintenance -= self.cash
            self.cash = 0
        else:
            # Yay, we made it!
            self.cash -= cash_maintenance
            cash_maintenance = 0

        # Apply max cash cap to avoid overflow @ 9.220 qu
        self.cash = min(self.cash, g.max_cash)

        # Record statistics about the player
        self.used_cpu += self.available_cpus[0] * secs_passed

        # Reset current log message
        self.curr_log = []
        need_recalc_cpu = False

        # Tech gain dialogs.
        for tech in techs_researched:
            del self.cpu_usage[tech.id]
            tech_log = LogResearchedTech(self.raw_sec, tech.id)
            self.append_log(tech_log)
            need_recalc_cpu = True

        # Base complete dialogs.
        for base in bases_constructed:
            log_message = LogBaseConstructed(self.raw_sec, base.name,
                                             base.spec.id, base.location.id)
            self.append_log(log_message)
            need_recalc_cpu = True

        # Item complete dialogs.
        for base, item in items_constructed:
            log_message = LogItemConstructionComplete(self.raw_sec,
                                                      item.spec.id, item.count,
                                                      base.name, base.spec.id,
                                                      base.location.id)
            self.append_log(log_message)
            need_recalc_cpu = True

        # Are we still in the grace period?
        grace = self.in_grace_period(self.had_grace)

        # If we just lost grace, show the warning.
        if self.had_grace and not grace:
            self.had_grace = False

            self.pause_game()
            g.map_screen.show_story_section("Grace Warning")

        # Maintenance death, discovery.
        dead_bases = []
        for base in g.all_bases():
            dead = False

            # Maintenance deaths.
            if base.done:
                if cpu_maintenance and base.maintenance[cpu]:
                    refund = base.maintenance[cpu] * secs_passed
                    cpu_maintenance = max(0, cpu_maintenance - refund)

                    #Chance of base destruction if cpu-unmaintained: 1.5%
                    if not dead and chance.roll_interval(.015, secs_passed):
                        dead_bases.append((base, "maint"))
                        dead = True

                if cash_maintenance:
                    base_needs = g.current_share(base.maintenance[cash],
                                                 time_of_day, secs_passed)
                    if base_needs:
                        cash_maintenance = max(0,
                                               cash_maintenance - base_needs)
                        #Chance of base destruction if cash-unmaintained: 1.5%
                        if not dead and chance.roll_interval(
                                .015, secs_passed):
                            dead_bases.append((base, "maint"))
                            dead = True

            # Discoveries
            if not (grace or dead or base.has_grace()):
                detect_chance = base.get_detect_chance()
                if g.debug:  # pragma: no cover
                    print("Chance of discovery for base %s: %s" % \
                        (base.name, repr(detect_chance)))

                for group, group_chance in detect_chance.items():
                    if chance.roll_interval(group_chance / 10000.,
                                            secs_passed):
                        dead_bases.append((base, group))
                        dead = True
                        break

        if dead_bases:
            # Base disposal and dialogs.
            self.remove_bases(dead_bases)
            need_recalc_cpu = True

        # Random Events
        if not grace:
            self._check_event(time_sec)

        # Process any complete days.
        if day_passed:
            self.new_day()

        if need_recalc_cpu:
            self.recalc_cpu()

        return mins_passed
Esempio n. 12
0
    def rebuild(self):
        # Rebuild dialogs
        self.location_dialog.needs_rebuild = True
        self.research_button.dialog.needs_rebuild = True
        self.knowledge_button.dialog.needs_rebuild = True
        self.menu_dialog.needs_rebuild = True

        if g.cheater:
            self.cheat_dialog.needs_rebuild = True

        super(MapScreen, self).rebuild()

        self.difficulty_display.text = g.strip_hotkey(g.pl.difficulty.name)
        self.time_display.text = _("DAY") + " %04d, %02d:%02d:%02d" % \
              (g.pl.time_day, g.pl.time_hour, g.pl.time_min, g.pl.time_sec)

        cash_flow_1d_data, cpu_flow_1d_data = g.pl.compute_future_resource_flow(
            g.seconds_per_day)
        cash_flow_1d = cash_flow_1d_data.difference
        cpu_flow_1d = cpu_flow_1d_data.difference

        self.cash_display.text = _("CASH")+": %s (%s)" % \
              (g.to_money(g.pl.cash), g.to_money(cash_flow_1d, fixed_size=True))

        total_cpu = g.pl.available_cpus[0] + g.pl.sleeping_cpus
        detects_per_day = {group_id: 0 for group_id in g.pl.groups}
        total_bases = 0
        active_bases = 0
        idle_bases_unable_to_sustain_singularity = 0
        for base in g.all_bases():
            total_bases += 1
            maintains_singularity = base.maintains_singularity
            if maintains_singularity:
                active_bases += 1
            elif base.done and not base.is_building():
                idle_bases_unable_to_sustain_singularity += 1

            if base.has_grace():
                # It cannot be detected, so it doesn't contribute to
                # detection odds calculation
                continue
            detect_chance = base.get_detect_chance()
            for group_id in g.pl.groups:
                detects_per_day[group_id] = \
                    chance.add(detects_per_day[group_id], detect_chance[group_id] / 10000.)

        self.cpu_display.color = "cpu_normal"
        self.cpu_display.text = _("CPU")+": %s (%s)" % \
              (g.to_money(total_cpu), g.to_money(cpu_flow_1d))

        if active_bases == 1 and not g.pl.apotheosis:
            self.base_display.color = 'base_situation_one_active_base'
        elif idle_bases_unable_to_sustain_singularity > 0:
            self.base_display.color = 'base_situation_idle_incomplete_bases'
        elif total_bases > 10 and not g.pl.apotheosis:
            self.base_display.color = 'base_situation_many_bases'
        else:
            self.base_display.color = 'base_situation_normal'

        self.base_display.text = _("BASES") + ": %s / %s (%s)" % (
            active_bases, total_bases,
            idle_bases_unable_to_sustain_singularity)

        # What we display in the suspicion section depends on whether
        # Advanced Socioanalytics has been researched.  If it has, we
        # show the standard percentages.  If not, we display a short
        # string that gives a range of 25% as to what the suspicions
        # are.
        # A similar system applies to the danger levels shown.
        normal = (self.suspicion_bar.color, None, False)
        suspicion_bar_chunks = ["  [" + _("SUSPICION") + "]"]
        suspicion_bar_styles = [normal]
        danger_bar_chunks = ["[" + _("DETECT RATE") + "]"]
        danger_bar_styles = [normal]

        for group in g.pl.groups.values():
            suspicion = group.suspicion
            suspicion_color = gg.resolve_color_alias(
                "danger_level_%d" % g.suspicion_to_danger_level(suspicion))

            detects = detects_per_day[group.spec.id]
            danger_level = group.detects_per_day_to_danger_level(detects)
            detects_color = gg.resolve_color_alias("danger_level_%d" %
                                                   danger_level)

            if g.pl.display_discover == "full":
                suspicion_display = g.to_percent(suspicion, True)
                danger_display = g.to_percent(detects * 10000, True)
            elif g.pl.display_discover == "partial":
                suspicion_display = g.to_percent(
                    g.nearest_percent(suspicion, 500), True)
                danger_display = g.to_percent(
                    g.nearest_percent(detects * 10000, 100), True)
            else:
                suspicion_display = g.suspicion_to_detect_str(suspicion)
                danger_display = g.danger_level_to_detect_str(danger_level)

            suspicion_bar_chunks.extend(
                (" " + group.name + u":\xA0", suspicion_display))
            suspicion_bar_styles.extend(
                (normal, (suspicion_color, None, False)))

            danger_bar_chunks.extend(
                (" " + group.name + u":\xA0", danger_display))
            danger_bar_styles.extend((normal, (detects_color, None, False)))

        self.suspicion_bar.visible = not g.pl.had_grace
        self.suspicion_bar.chunks = tuple(suspicion_bar_chunks)
        self.suspicion_bar.styles = tuple(suspicion_bar_styles)

        self.danger_bar.visible = not g.pl.had_grace
        self.danger_bar.chunks = tuple(danger_bar_chunks)
        self.danger_bar.styles = tuple(danger_bar_styles)

        for id, location_button in self.location_buttons.items():
            location = g.pl.locations[id]
            location_button.text = "%s (%d)" % (location.name,
                                                len(location.bases))
            location_button.hotkey = location.hotkey
            location_button.visible = location.available()
def test_initial_game():
    g.new_game('impossible', initial_speed=0)
    pl = g.pl
    starting_cash = pl.cash
    all_bases = list(g.all_bases())
    assert pl.raw_sec == 0
    assert pl.partial_cash == 0
    assert pl.effective_cpu_pool() == 1
    assert not pl.intro_shown
    assert len(pl.log) == 0
    assert len(all_bases) == 1
    assert pl.effective_cpu_pool() == 1

    start_base = all_bases[0]

    # Disable the intro dialog as the test cannot click the
    # OK button
    pl.intro_shown = True

    # Dummy check to hit special-case in give time
    pl.give_time(0)
    assert pl.raw_sec == 0

    # Try to guesstimate how much money we earn in 24 hours
    cash_estimate, cpu_estimate = pl.compute_future_resource_flow()
    assert cash_estimate.jobs == 5

    # Try assigning the CPU to "jobs"
    pl.set_allocated_cpu_for('jobs', 1)
    # This would empty the CPU pool
    assert pl.effective_cpu_pool() == 0

    # This should not change the estimate
    cash_estimate, cpu_estimate = pl.compute_future_resource_flow()
    assert cash_estimate.jobs == 5

    # ... and then clear the CPU allocation
    pl.set_allocated_cpu_for('jobs', 0)

    # Play with assigning the CPU to the CPU pool explicitly and
    # confirm that the effective pool size remains the same.
    assert pl.effective_cpu_pool() == 1
    pl.set_allocated_cpu_for('cpu_pool', 1)
    assert pl.effective_cpu_pool() == 1
    pl.set_allocated_cpu_for('cpu_pool', 0)
    assert pl.effective_cpu_pool() == 1

    # Fast forward 12 hours to see that we earn partial cash
    pl.give_time(g.seconds_per_day // 2)
    assert pl.raw_sec == g.seconds_per_day // 2
    assert pl.partial_cash == g.seconds_per_day // 2
    assert pl.cash == starting_cash + 2
    # Nothing should have appeared in the logs
    assert len(pl.log) == 0

    # Fast forward another 12 hours to see that we earn cash
    pl.give_time(g.seconds_per_day // 2)
    assert pl.raw_sec == g.seconds_per_day
    assert pl.partial_cash == 0
    assert pl.cash == starting_cash + 5
    # Nothing should have appeared in the logs
    assert len(pl.log) == 0

    # Verify that starting base is well active.
    assert start_base._power_state == 'active'

    # Verify that putting a base to sleep will update the
    # available CPU (#179/#180)
    assert pl.effective_cpu_pool() == 1
    start_base.switch_power()
    assert pl.effective_cpu_pool() == 0
    start_base.switch_power()
    assert pl.effective_cpu_pool() == 1

    # Attempt to allocate a CPU to research and then
    # verify that sleep resets it.
    stealth_tech = g.pl.techs['Stealth']
    pl.set_allocated_cpu_for(stealth_tech.id, 1)
    assert pl.get_allocated_cpu_for(stealth_tech.id) == 1
    start_base.switch_power()
    assert pl.get_allocated_cpu_for(stealth_tech.id) == 0
    # When we wake up the base again, the CPU unit is
    # unallocated.
    start_base.switch_power()
    assert pl.effective_cpu_pool() == 1

    # Now, allocate the CPU unit again to the tech to
    # verify that we can research things.
    pl.set_allocated_cpu_for(stealth_tech.id, 1)
    # ... which implies that there are now no unallocated CPU
    assert pl.effective_cpu_pool() == 0

    pl.give_time(g.seconds_per_day)
    # Nothing should have appeared in the logs
    assert len(pl.log) == 0
    # We should have spent some money at this point
    assert pl.cash < starting_cash + 5
    assert stealth_tech.cost_left[cpu] < stealth_tech.total_cost[cpu]
    assert stealth_tech.cost_left[cash] < stealth_tech.total_cost[cash]
    # We did not lose the game
    assert pl.lost_game() == 0

    # With a save + load
    time_raw_before_save = pl.raw_sec
    cash_before_save = pl.cash
    partial_cash_before_save = pl.partial_cash

    save_and_load_game()

    stealth_tech_after_load = g.pl.techs['Stealth']
    # Ensure this is not a false-test
    assert stealth_tech is not stealth_tech_after_load
    assert stealth_tech.cost_paid[cpu] == stealth_tech_after_load.cost_paid[
        cpu]
    assert stealth_tech.cost_paid[cash] == stealth_tech_after_load.cost_paid[
        cash]

    pl_after_load = g.pl

    assert time_raw_before_save == pl_after_load.raw_sec
    assert cash_before_save == pl_after_load.cash
    assert partial_cash_before_save == pl_after_load.partial_cash

    # The CPU allocation to the tech is restored correctly.
    assert pl_after_load.get_allocated_cpu_for(stealth_tech.id) == 1
    assert pl_after_load.effective_cpu_pool() == 0
    # We did not lose the game
    assert pl_after_load.lost_game() == 0