Debian Codegraph @

CorsixTH/Lua/hospital.lua

raw
1 --[[ Copyright (c) 2009 Peter "Corsix" Cawley
2
3 Permission is hereby granted, free of charge, to any person obtaining a copy of
4 this software and associated documentation files (the "Software"), to deal in
5 the Software without restriction, including without limitation the rights to
6 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
7 of the Software, and to permit persons to whom the Software is furnished to do
8 so, subject to the following conditions:
9
10 The above copyright notice and this permission notice shall be included in all
11 copies or substantial portions of the Software.
12
13 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19 SOFTWARE. --]]
20
21 corsixth.require("announcer")
22
23 class "Hospital"
24
25 ---@type Hospital
26 local Hospital = _G["Hospital"]
27
28 function Hospital:Hospital(world, avail_rooms, name)
29 self.world = world
30 local level_config = world.map.level_config
31 local level = world.map.level_number
32 local balance, interest_rate_numerator, reputation, overdraft_differential_numerator
33
34 if level_config.towns and level_config.towns[level] then
35 balance = level_config.towns[level].StartCash
36 interest_rate_numerator = level_config.towns[level].InterestRate
37 reputation = level_config.towns[level].StartRep
38 overdraft_differential_numerator = level_config.towns[level].OverdraftDiff
39 elseif level_config.town then
40 balance = level_config.town.StartCash
41 interest_rate_numerator = level_config.town.InterestRate
42 reputation = level_config.town.StartRep
43 overdraft_differential_numerator = level_config.town.OverdraftDiff
44 end
45
46 self.name = name or "PLAYER"
47 -- When playing in free build mode you don't care about money.
48 self.balance = not world.free_build_mode and balance or 0
49 self.loan = 0
50 self.acc_loan_interest = 0
51 self.acc_research_cost = 0
52 self.acc_overdraft = 0
53 self.acc_heating = 0
54
55 -- The sum of all material values (tiles, rooms, objects).
56 -- Initial value: hospital tile count * tile value + 20000
57 self.value = world.map:getParcelPrice(self:getPlayerIndex()) + 20000
58
59 self.player_salary = 10000
60 self.salary_offer = 0
61
62
63 self.handymanTasks = {}
64 -- Represents the "active" epidemic non-nil if
65 -- an epidemic is happening currently in the hospital
66 -- Only one epidemic is ever "active"
67 self.epidemic = nil
68
69 -- The pool of epidemics which may happen in the future.
70 -- Epidemic in this table continue in the background its
71 -- patients infecting each other. Epidemics are chosen from
72 -- this pool to become the "active" epidemic
73 self.future_epidemics_pool = {}
74 -- How many epidemics can exist simultaneously counting current and future
75 -- epidemics. If epidemic_limit = 1 then only one epidemic can exist at a
76 -- time either in the futures pool or as a current epidemic.
77 self.concurrent_epidemic_limit = level_config.gbv.EpidemicConcurrentLimit or 1
78 -- For Cheat - flag determines possibility of epidemics
79 self.epidemics_disabled = false
80
81 -- Initial values
82 self.interest_rate = interest_rate_numerator / 10000
83 self.inflation_rate = 0.045
84 self.overdraft_interest_rate = self.interest_rate + overdraft_differential_numerator / 10000
85 self.salary_incr = level_config.gbv.ScoreMaxInc or 300
86 self.sal_min = level_config.gbv.ScoreMaxInc / 6 or 50
87 self.reputation_min = 0
88 self.reputation_max = 1000
89 self.reputation = math.min(math.max(reputation, self.reputation_min), self.reputation_max)
90
91 local difficulty = self.world.map:getDifficulty()
92 -- Price distortion level under which the patients might consider the
93 -- treatment to be under-priced.
94 local under_priced_thresholds = {-0.3, -0.4, -0.5}
95 self.under_priced_threshold = under_priced_thresholds[difficulty]
96
97 -- Price distortion level over which the patients might consider the
98 -- treatment to be over-priced.
99 local over_priced_thresholds = {0.4, 0.3, 0.2}
100 self.over_priced_threshold = over_priced_thresholds[difficulty]
101
102 -- (int) Number of days until the next heating or vomit wave disaster.
103 -- TODO: Implement the vomit wave.
104 self.disasterless_days = self:daysUntilNextDisaster()
105
106 -- Heating system variables.
107 self.heating = {
108 radiator_heat = 0.5, -- (float) [0..1] fraction of heating by a radiator.
109 saved_radiator_heat = nil, -- (float) Saved radiator heat when boiler has broken down.
110 boiler_repair_count = nil, -- (int) Number of items to repair.
111 heating_broke = false -- (bool) Whether the heating system is broken down currently.
112 }
113
114 -- Number of tile objects of each category in the hospital.
115 self.tile_object_counts = {
116 extinguisher = 0,
117 radiator = 0,
118 plant = 0,
119 reception_desk = 0,
120 bench = 0,
121 general = 0,
122 }
123 self:buildReceptionDesksCache()
124
125 self.num_visitors = 0 -- Counts patients only
126 self.num_deaths = 0
127 self.num_deaths_this_year = 0
128 self.num_cured = 0
129 self.not_cured = 0
130 self.num_explosions = 0
131 self.vip_declined = 0
132 self.num_vips = 0 -- used to check if it's the user's first vip
133 self.percentage_cured = 0
134 self.percentage_killed = 0
135 self.population = 0.25 -- TODO: Percentage showing how much of
136 -- the total population that goes to the player's hospital,
137 -- used for one of the goals. Change when competitors are there.
138
139 -- Statistics used in the graph dialog. Each entry is the month, inside it
140 -- is "money in", "money out", wages, balance, visitors, cures, deaths, reputation
141 -- statistic[i] shows what the values were when going from month i - 1 to i.
142 self.statistics = {
143 {
144 money_in = 0,
145 money_out = 0,
146 wages = 0,
147 balance = balance,
148 visitors = 0,
149 cures = 0,
150 deaths = 0,
151 reputation = self.reputation
152 }
153 }
154 self.money_in = 0
155 self.money_out = 0
156
157 -- Other statistics, back to zero each year
158 self.has_impressive_reputation = true
159 self:unconditionalChangeReputation(0) -- Reset self.has_impressive_reputation
160
161 self.sodas_sold = 0
162 self.num_vips_ty = 0 -- used to count how many VIP visits in the year for an award
163 self.pleased_vips_ty = 0
164 self.num_cured_ty = 0
165 self.not_cured_ty = 0
166 self.num_visitors_ty = 0
167
168 self.ownedPlots = {1} -- Plots owned by the hospital
169 self.ratholes = {} -- List of table {x, y, wall, parcel, optional object} for ratholes in the hospital corridors.
170 self.is_in_world = true -- Whether the hospital is in this world (AI hospitals are not)
171 self.opened = false -- Whether the hospital is opened (timer was cleared or ended).
172 self.transactions = {}
173 self.staff = {}
174 self.patients = {}
175 self.debug_patients = {} -- right-click-commandable patients for testing
176 self.disease_casebook = {}
177 self.discovered_diseases = {} -- a list
178
179 -- Create a cheats instance for each hospital. AIHospitals don't know how to cheat (we hope!)
180 self.hosp_cheats = Cheats(self)
181
182 -- Make a table containing available rooms for the level, and its discovery status (room, discovery_status)
183 -- Index is the room's id e.g. gp
184 self.room_discoveries = {}
185 for _, avail_room in ipairs(avail_rooms) do
186 self.room_discoveries[avail_room.room.id] = {
187 room = avail_room.room,
188 is_discovered = avail_room.is_discovered or false
189 }
190 end
191
192 local gbv = level_config.gbv
193 self.policies = {
194 staff_allowed_to_move = true,
195 send_home = 0.1,
196 guess_cure = 0.9,
197 stop_procedure = 1, -- Note that this is between 1 and 2 ( = 100% - 200%)
198 goto_staffroom = gbv.Tired / 1000, -- Defaults to 0.6 on normal difficulty
199 grant_wage_increase = TheApp.config.grant_wage_increase,
200 }
201
202 -- Semi-randomly select three insurance companies to use, only different by name right now.
203 -- The companies in the first quarter of the list are more likely to be selected
204 self.insurance = {}
205 -- Make a local writeable copy table of the translated company names.
206 local companies = {}
207 for no, local_name in ipairs(_S.insurance_companies) do
208 companies[no] = local_name
209 end
210 while #self.insurance < 3 and #companies > 0 do
211 local num = math.random(1, 2) == 1 and math.random(1, math.ceil(#companies / 4)) or
212 math.random(1, #companies)
213 self.insurance[#self.insurance + 1] = companies[num]
214 table.remove(companies, num)
215 end
216
217 -- A list of how much each insurance company owes you. The first entry for
218 -- each company is the current month's dept, the second the previous
219 -- month and the third the month before that.
220 -- All payment that goes through an insurance company a given month is paid two
221 -- months later. For example diagnoses in April are paid the 1st of July
222 self.insurance_balance = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}
223
224 -- Initialize diseases
225 local diseases = TheApp.diseases
226 local expertise = level_config.expertise
227 for _, disease in ipairs(diseases) do
228 local disease_available = true
229 local drug_effectiveness = 95
230 local drug = disease.treatment_rooms and disease.treatment_rooms[1] == "pharmacy" or nil
231 local drug_cost = 100
232 if expertise then
233 disease_available = expertise[disease.expertise_id].Known == 1
234 -- This means that the config is available
235 drug_effectiveness = gbv.StartRating
236 drug_cost = gbv.StartCost
237 end
238 if world.available_diseases[disease.id] or disease.pseudo then
239 local info = {
240 reputation = not disease.pseudo and 500 or nil,
241 price = 1.0, -- user-set multiplier between 0.5 and 2.0
242 money_earned = 0,
243 recoveries = 0,
244 fatalities = 0,
245 turned_away = 0,
246 disease = disease,
247 discovered = disease_available,
248 concentrate_research = false,
249 cure_effectiveness = drug and drug_effectiveness or 100,
250 -- This will only work as long as there's only one treatment room.
251 drug = drug,
252 drug_cost = drug and drug_cost,
253 psychiatrist = disease.treatment_rooms and disease.treatment_rooms[1] == "psych" or nil,
254 machine = disease.requires_machine,
255 -- This assumes we always have the ward then the operating_theatre as treatment rooms.
256 surgeon = disease.treatment_rooms and disease.treatment_rooms[2] == "operating_theatre" or nil,
257 researcher = disease.requires_researcher, -- TODO: Fix when aliens are in the game.
258 pseudo = disease.pseudo, -- Diagnosis is pseudo
259 }
260 self.disease_casebook[disease.id] = info
261 if disease_available and not disease.pseudo then
262 self.discovered_diseases[#self.discovered_diseases + 1] = disease.id
263 end
264 end
265 end
266 self.research = ResearchDepartment(self)
267
268 -- Initialize build cost for all available rooms.
269 for _, avail_room in ipairs(avail_rooms) do
270 self.research.research_progress[avail_room.room] = {
271 -- In free build mode, everything is freely available.
272 build_cost = not self.free_build_mode and avail_room.build_cost or 0,
273 }
274 end
275 end
276
277 --! Checks if a room has been discovered
278 --!param room_id (string) The name of the room
279 --!return (boolean) true if discovered, otherwise false
280 function Hospital:isRoomDiscovered(room_id)
281 return self.room_discoveries[room_id].is_discovered
282 end
283
284 --! Update the loaded game with version 'old' to the version 'new'.
285 --!param old Version of the loaded game.
286 --!param new Version of the code being executed.
287 function Hospital:afterLoad(old, new)
288 if old < 34 then
289 -- New variable
290 self.acc_overdraft = 0
291 end
292 if old < 35 then
293 -- Define build costs for rooms once again.
294 local cfg_objects = self.world.map.level_config.objects
295 local cfg_rooms = self.world.map.level_config.rooms
296 for _, room in ipairs(TheApp.rooms) do
297 -- Sum up the build cost of the room
298 local build_cost = cfg_rooms[room.level_config_id].Cost
299 for name, no in pairs(room.objects_needed) do
300 -- Add cost for this object.
301 build_cost = build_cost + cfg_objects[TheApp.objects[name].thob].StartCost * no
302 end
303 -- Now define the total build cost for the room.
304 self.research.research_progress[room] = {
305 build_cost = build_cost,
306 }
307 end
308 end
309 if old < 39 then
310 self.acc_heating = 0
311 end
312 if old < 40 then
313 self.statistics = {}
314 self.money_in = 0
315 self.money_out = 0
316 end
317 if old < 41 then
318 self.boiler_can_break = true
319 end
320
321 if old < 45 then
322 self.num_explosions = 0
323 self.num_vips = 0
324 end
325
326 if old < 50 then
327 self.num_vips_ty = 0
328 self.pleased_vips_ty = 0
329 self.num_cured_ty = 0
330 self.not_cured_ty = 0
331 self.num_visitors_ty = 0
332 end
333
334 if old < 52 then
335 self:initOwnedPlots()
336 self.handymanTasks = {}
337 end
338
339 if old < 54 then
340 local current = self.research.research_policy.specialisation.current
341 if current and not current.dummy and not current.thob and not current.drug then
342 for _, disease_entry in pairs(self.disease_casebook) do
343 if disease_entry.concentrate_research then
344 self.research:concentrateResearch(disease_entry.disease.id)
345 self.research:concentrateResearch(disease_entry.disease.id)
346 end
347 end
348 end
349 end
350
351 if old < 56 then
352 self.research_dep_built = false
353 end
354 if old < 84 then
355 self.vip_declined = 0
356 end
357
358 if old < 88 then
359 self.future_epidemics_pool = {}
360 self.concurrent_epidemic_limit = self.world.map.level_config.gbv.EpidemicConcurrentLimit or 1
361 end
362
363 if old < 107 then
364 self.reception_desks = nil
365 end
366
367 if old < 109 then
368 -- price distortion
369 self.under_priced_threshold = -0.4
370 self.over_priced_threshold = 0.3
371 end
372
373 if old < 111 then
374 self.initial_grace = nil
375 end
376
377 if old < 114 then
378 self.ratholes = {}
379 end
380
381 if old < 131 then
382 self.autopsy_discovered = nil
383 self.discover_autopsy_risk = nil
384 end
385
386 if old < 140 then
387 self.has_impressive_reputation = self.reputation_above_threshold and true or false
388 self.reputation_above_threshold = nil
389 self:unconditionalChangeReputation(0) -- Setup 'has_impressive_reputation'
390 end
391
392 if old < 142 then
393 self.disasterless_days = self:daysUntilNextDisaster()
394
395 self.heating = {
396 radiator_heat = self.radiator_heat or 0.5,
397 saved_radiator_heat = self.curr_setting or 0.5,
398 boiler_repair_count = self.boiler_countdown or 0,
399 heating_broke = self.heating_broke or false
400 }
401 self.radiator_heat = nil
402 self.curr_setting = nil
403 self.boiler_countdown = nil
404 self.boiler_can_break = nil -- Equivalent to self.opened.
405 self.heating_broke = nil
406 end
407
408 if old < 143 and new >= 143 then
409 if self:isPlayerHospital() then
410 setmetatable(self, PlayerHospital._metatable)
411 end
412
413 -- To avoid recursion, apply the remaining changes asif the game was
414 -- started from version 143.
415 self:afterLoad(143, new)
416 return
417 end
418
419 if old < 146 then
420 self.staff_room_msg = nil
421 self.toilet_msg = nil
422 self.bench_msg = nil
423 self.warmth_msg = nil
424 self.thirst_msg = nil
425 self.seating_warning = nil
426 self.cash_msg = nil
427 end
428
429 if old < 147 then
430 self.patientcount = nil
431 self.receptionist_msg = nil
432 end
433 if old < 148 then
434 self.msg_counter = nil
435 end
436 if old < 152 then
437 -- If old save has an emergency fax, or emergency active, of an undiscovered disease
438 -- make the disease discovered to prevent crashing (see #1754, #1799)
439 local em = self.emergency
440 if em and not self.disease_casebook[em.disease.id].discovered then
441 self.research:discoverDisease(em.disease)
442 end
443 end
444
445 if old < 154 then
446 -- We now use one table for our room discovery
447 self.room_discoveries = {}
448 -- Get the level start available rooms
449 local avail_rooms = self.world:getAvailableRooms()
450 for _, avail_room in ipairs(avail_rooms) do
451 self.room_discoveries[avail_room.room.id] = {
452 room = avail_room.room,
453 is_discovered = avail_room.is_discovered or false
454 }
455 end
456 -- Has the player discovered rooms since?
457 for _, room_new in pairs(self.room_discoveries) do
458 if self.discovered_rooms[room_new.room] then -- old system used rooms as keys
459 room_new.is_discovered = true
460 end
461 end
462 -- Clear old variables
463 self.discovered_rooms = nil
464 self.undiscovered_rooms = nil
465 end
466
467 if old < 155 then
468 self.overdraft_interest_rate = self.interest_rate + 0.02
469 end
470 if old < 159 then
471 self.receptionist_msg = nil
472 end
473
474 if old < 167 then
475 -- Count tile objects of this hospital from scratch.
476 self.tile_object_counts = {
477 extinguisher = 0,
478 radiator = 0,
479 plant = 0,
480 reception_desk = 0,
481 bench = 0,
482 general = 0,
483 }
484 local width, height = self.world.map.th:size()
485 for x = 1, width do
486 for y = 1, height do
487 local objects = self.world:getObjects(x, y)
488 if objects then
489 for _, object in ipairs(objects) do
490 if object.hospital == self then
491 self:addTileObject(object.object_type.count_category)
492 end
493 end
494 end
495 end
496 end
497 end
498
499 if old < 169 then
500 -- AIHospital previously did not have a cheats instance, now it should
501 if not self.hosp_cheats then self.hosp_cheats = Cheats(self) end
502 -- Move toggle cheat triggers to Cheats
503 self.hosp_cheats.active_cheats = {}
504 self.hosp_cheats.active_cheats["spawn_rate_cheat"] = self.spawn_rate_cheat
505 self.spawn_rate_cheat = nil
506 end
507 if old < 243 then
508 self:buildReceptionDesksCache()
509 end
510
511 -- Update other objects in the hospital (added in version 106).
512 if self.epidemic then self.epidemic:afterLoad(old, new) end
513 for _, future_epidemic in ipairs(self.future_epidemics_pool) do
514 future_epidemic:afterLoad(old, new)
515 end
516 self.research:afterLoad(old, new)
517 end
518
519 --! Count the number of patients in the hospital.
520 --!param max_count (optional integer) If provided, non-negative maximum count to return.
521 --!return The number of patients in the hospital, at most max_count is returned if provided.
522 function Hospital:countPatients(max_count)
523 local count = 0
524 for _, patient in ipairs(self.patients) do
525 -- Only count patients that are in the hospital.
526 local tx, ty = patient.tile_x, patient.tile_y
527 if tx and ty and self:isInHospital(tx, ty) then
528 count = count + 1
529 if max_count ~= nil and count >= max_count then break end
530 end
531 end
532 return count
533 end
534
535 --! Count number of sitting and standing patients in the hospital.
536 --!return (integer, integer) Number of sitting and number of standing patient in the hospital.
537 function Hospital:countSittingStanding()
538 local numberSitting = 0
539 local numberStanding = 0
540 for _, patient in ipairs(self.patients) do
541 local pat_action = patient:getCurrentAction()
542 if pat_action.name == "idle" and not patient:getRoom() then
543 numberStanding = numberStanding + 1
544 elseif pat_action.name == "use_object" and pat_action.object.object_type.id == "bench" then
545 numberSitting = numberSitting + 1
546 end
547 end
548 return numberSitting, numberStanding
549 end
550
551 --! Called each tick, also called 'hours'. Check hours_per_day in
552 --! date.lua to see how many times per day this is.
553 function Hospital:tick()
554 -- Add some random background sounds, ringing phones, coughing, belching etc.
555 --
556 -- TODO: Background noises of other hospitals are heard in multi-player,
557 -- TODO: decide where this should go.
558 if math.random(1, 100) == 3 then
559 -- Wait until there are some patients in the hospital and a room, otherwise you
560 -- will wonder who is coughing or who is the receptionist telephoning!
561 -- Opted for gp as you can't run the hospital without one.
562 if self:countRoomOfType("gp", 1) > 0 and self:countPatients(3) > 2 then
563 local sounds = {
564 "ispot001.wav", "ispot002.wav", "ispot003.wav", "ispot004.wav",
565 "ispot005.wav", "ispot006.wav", "ispot007.wav", "ispot008.wav",
566 "ispot009.wav", "ispot010.wav", "ispot011.wav", "ispot012.wav",
567 "ispot013.wav", "ispot014.wav", "ispot015.wav", "ispot016.wav",
568 "ispot017.wav", "ispot018.wav", "ispot019.wav", "ispot020.wav",
569 "ispot021.wav", "ispot022.wav", "ispot023.wav", "ispot024.wav",
570 "ispot025.wav"
571 } -- ispot026 and ispot027 are both toilet related sounds.
572
573 local sound_to_play = sounds[math.random(1, #sounds)]
574 if TheApp.audio:soundExists(sound_to_play) then
575 self.world.ui:playSound(sound_to_play)
576 end
577 end
578 end
579
580 self:manageEpidemics()
581 end
582
583 function Hospital:purchasePlot(plot_number)
584 local map = self.world.map
585 if map.th:isParcelPurchasable(plot_number, self:getPlayerIndex()) then
586 local cost = not self.world.free_build_mode and map:getParcelPrice(plot_number) or 0
587 if cost <= self.balance then
588 self.world:setPlotOwner(plot_number, self:getPlayerIndex())
589 table.insert(self.ownedPlots, plot_number)
590 -- Also make sure to apply transparency to the new walls, if required.
591 self.world.ui:applyTransparency()
592 self:spendMoney(cost, _S.transactions.buy_land, cost)
593 return true
594 else
595 -- Give visual warning that player doesn't have enough $ to build
596 self:adviseCannotAffordPlot()
597 end
598 end
599 return false
600 end
601
602 function Hospital:getPlayerIndex()
603 -- TODO: In multiplayer, return 2 or 3 or 4
604 return 1
605 end
606
607 --! Returns the heliport x and y coordinates or nil if none exist.
608 --!return (pair of integers, or nil) The x,y position of the tile with the heliport, if it exists.
609 function Hospital:getHeliportPosition()
610 local x, y = self.world.map.th:getHeliportTile(self:getPlayerIndex())
611 -- NB: Level 2 has a heliport tile set, but no heliport, so we ensure that
612 -- the specified tile is suitable by checking the spawn tile for
613 -- passability.
614 if y > 0 and self.world.map:getCellFlag(x, y, "passable") then
615 return x, y
616 end
617 end
618
619 --! Returns the tile on which patients should spawn when getting out of the helicopter.
620 --!return (pair of integers, or nil) The x,y position to use for spawning emergency patients from the heliport, if available.
621 function Hospital:getHeliportSpawnPosition()
622 local x, y = self:getHeliportPosition()
623 if x and y then
624 return x, y - 1
625 end
626 end
627
628 --[[ Test if a given map tile is part of this hospital.
629 !param x (integer) The 1-based X coordinate of the tile to test.
630 !param y (integer) The 1-based Y coordinate of the tile to test.
631 ]]
632 function Hospital:isInHospital(x, y)
633 local flags = self.world.map.th:getCellFlags(x, y)
634 return flags.hospital and flags.owner == self:getPlayerIndex()
635 end
636
637 --! Decide how many days the hospital functions within specification.
638 --!return (int) Number of disaster-free days in the hospital.
639 function Hospital:daysUntilNextDisaster()
640 local disaster_free_days = {300, 200, 150}
641 -- Original doesn't use random, see Github #490.
642 return disaster_free_days[self.world.map:getDifficulty()] + math.random(1, 21) - 11
643 end
644
645 --! Boiler should break down.
646 --!param broken_heat (0 or 1) Amount of heat to output due to being broken.
647 function Hospital:boilerBreakdown(broken_heat)
648 local heat_vars = self.heating
649
650 if not self.opened then return end -- Boiler cannot break if hospital is closed.
651 if heat_vars.heating_broke then return end -- Still broken, don't break it again.
652
653 local num_radiators = self:countRadiators()
654 if num_radiators == 0 then return end -- No radiators, don't bother to break the boiler.
655
656 local num_handyman = self:countStaffOfCategory("Handyman")
657 if num_radiators <= 8 * num_handyman then return end -- Enough handyman to maintain the heating system.
658
659 heat_vars.saved_radiator_heat = heat_vars.radiator_heat
660 heat_vars.radiator_heat = broken_heat
661 heat_vars.boiler_repair_count = math.random(10, 30)
662 heat_vars.heating_broke = true
663
664 -- Warn the player of the boiler's breakdown
665 self:adviseBoilerBreakdown(broken_heat)
666 end
667
668 --! Boiler broke down and work is done to get it fixed.
669 function Hospital:_fixBoiler()
670 local heat_vars = self.heating
671
672 if not heat_vars.heating_broke then return end -- Not broken, done!
673
674 -- Repair the boiler or radiators, more handy men speeds up repair, see also github #490
675 local num_radiators = self:countRadiators()
676 local num_handyman = self:countStaffOfCategory("Handyman")
677 if num_radiators < 5 * num_handyman then
678 heat_vars.boiler_repair_count = heat_vars.boiler_repair_count - 3
679 elseif num_radiators < 8 * num_handyman then
680 heat_vars.boiler_repair_count = heat_vars.boiler_repair_count - 2
681 else
682 heat_vars.boiler_repair_count = heat_vars.boiler_repair_count - 1
683 end
684
685 if heat_vars.boiler_repair_count <= 0 then
686 -- It's fixed, restore previous settings.
687 heat_vars.radiator_heat = heat_vars.saved_radiator_heat
688 heat_vars.heating_broke = false
689 if num_radiators > 0 then
690 -- Only tell the player about fix if there is at least one radiator.
691 self:giveAdvice({_A.boiler_issue.resolved})
692 end
693 end
694 end
695
696 --! Daily update of the ratholes.
697 --!param self (Hospital) hospital being updated.
698 local function dailyUpdateRatholes(self)
699 local map = self.world.map
700 local th = map.th
701
702 local wanted_holes = math.round(th:getLitterFraction(self:getPlayerIndex()) * 200)
703 if #self.ratholes < wanted_holes then -- Not enough holes, find a new spot
704 -- Try to find a wall in a corridor, and add it if possible.
705 -- Each iteration does a few probes at a random position, most tries will
706 -- fail on not being on a free (non-built) tile in a corridor with a wall
707 -- in the right hospital.
708 -- Doing more iterations speeds up finding a suitable location, less
709 -- iterations is reduces needed processor time.
710 -- "6 + 2 * difference" is an arbitrary value that seems to work nicely, 12
711 -- is an arbitrary upper limit on the number of tries.
712 for _ = 1, math.min(12, 6 + 2 * (wanted_holes - #self.ratholes)) do
713 local x = math.random(1, map.width)
714 local y = math.random(1, map.height)
715 local flags = th:getCellFlags(x, y)
716 if self:isInHospital(x, y) and flags.roomId == 0 and flags.buildable then
717 local walls = self:getWallsAround(x, y)
718 if #walls > 0 then
719 -- Found a wall, check it for not being used.
720 local wall = walls[math.random(1, #walls)]
721 local found = false
722 for _, hole in ipairs(self.ratholes) do
723 if hole.x == x and hole.y == y and hole.wall == wall.wall then
724 found = true
725 break
726 end
727 end
728
729 if not found then
730 self:addRathole(x, y, wall.wall, wall.parcel)
731 break
732 end
733 end
734 end
735 end
736 end
737 end
738
739 -- Called at the end of each day.
740 function Hospital:onEndDay()
741 local pay_this = self.loan*self.interest_rate/365 -- No leap years
742 self.acc_loan_interest = self.acc_loan_interest + pay_this
743 self.research:researchCost()
744
745 self.show_progress_screen_warnings = math.random(1, 3) -- used in progress report to limit warnings
746 if self.balance < 0 then
747 local overdraft_interest = self.overdraft_interest_rate
748 local overdraft = math.abs(self.balance)
749 local overdraft_payment = (overdraft*overdraft_interest)/365
750 self.acc_overdraft = self.acc_overdraft + overdraft_payment
751 end
752
753 -- Count receptionists.
754 self.receptionist_count = 0
755 for _, staff in ipairs(self.staff) do
756 if class.is(staff, Receptionist) then
757 self.receptionist_count = self.receptionist_count + 1
758 end
759 end
760
761 self:_fixBoiler() -- Boiler always needs work (especially if broken).
762
763 -- Do we have a disaster?
764 self.disasterless_days = self.disasterless_days - 1
765 if self.disasterless_days <= 0 then
766 self.disasterless_days = self:daysUntilNextDisaster()
767
768 local disaster_type = math.random(1, 3) -- TODO: Set to 3 until the vomit wave is implemented.
769 -- disaster_type == 1 is for skipping the disaster, nothing happens.
770 if disaster_type == 2 then
771 self:boilerBreakdown(1) -- max heat
772 elseif disaster_type == 3 then
773 self:boilerBreakdown(0) -- min heat
774 end
775 -- TODO: Implement vomit wave disaster for disaster_type == 4
776 end
777
778 -- Calculate heating cost daily. Divide the monthly cost by the number of days in that month
779 local num_radiators = self:countRadiators()
780 local heating_costs = (self.heating.radiator_heat * 10 * num_radiators * 7.50) / self.world:date():lastDayOfMonth()
781 self.acc_heating = self.acc_heating + heating_costs
782
783 if self:isPlayerHospital() then dailyUpdateRatholes(self) end
784 end
785
786 -- Called at the end of each month.
787 function Hospital:onEndMonth()
788 -- Spend wages
789 local wages = 0
790 for _, staff in ipairs(self.staff) do
791 wages = wages + staff.profile.wage
792 end
793 if wages ~= 0 then
794 self:spendMoney(wages, _S.transactions.wages)
795 end
796 -- Pay heating costs
797 if math.round(self.acc_heating) > 0 then
798 self:spendMoney(math.round(self.acc_heating), _S.transactions.heating)
799 self.acc_heating = 0
800 end
801 -- Pay interest on loans
802 if math.round(self.acc_loan_interest) > 0 then
803 self:spendMoney(math.round(self.acc_loan_interest), _S.transactions.loan_interest)
804 self.acc_loan_interest = 0
805 end
806 -- Pay overdraft charges
807 if math.round(self.acc_overdraft) > 0 then
808 self:spendMoney(math.round(self.acc_overdraft), _S.transactions.overdraft)
809 self.acc_overdraft = 0
810 end
811 -- Pay research costs
812 if math.round(self.acc_research_cost) > 0 then
813 self:spendMoney(math.round(self.acc_research_cost), _S.transactions.research)
814 self.acc_research_cost = 0
815 end
816 -- add to score each month
817 -- rate varies on some performance factors i.e. reputation above 500 increases the score
818 -- and the number of deaths will reduce the score.
819 local sal_inc = self.salary_incr / 10
820 local sal_mult = (self.reputation - 500) / (self.num_deaths + 1) -- added 1 so that you don't divide by 0
821 local month_incr = sal_inc + sal_mult
822 -- To ensure that you can't receive less than 50 or
823 -- more than 300 per month
824 if month_incr < self.sal_min then
825 month_incr = self.sal_min
826 elseif month_incr > self.salary_incr then
827 month_incr = self.salary_incr
828 end
829 self.player_salary = self.player_salary + math.ceil(month_incr)
830
831 -- TODO: do you get interest on the balance owed?
832 for i, company in ipairs(self.insurance_balance) do
833 -- Get the amount that is about to be paid to the player
834 local payout_amount = company[3]
835 if payout_amount > 0 then
836 local str = _S.transactions.insurance_colon .. " " .. self.insurance[i]
837 self:receiveMoney(payout_amount, str)
838 end
839 -- Shift the amounts to the left
840 table.remove(company, 3)
841 table.insert(company, 1, 0) -- The new month have no payments yet
842 end
843
844 -- Check for equipment getting available
845 self.research:checkAutomaticDiscovery(self.world:date():monthOfGame())
846
847 -- Add some interesting statistics.
848 local newMonth = self.world:date():monthOfGame() + 1
849 self.statistics[newMonth] = {
850 money_in = self.money_in,
851 money_out = self.money_out,
852 wages = wages,
853 balance = self.balance,
854 visitors = self.num_visitors,
855 cures = self.num_cured,
856 deaths = self.num_deaths,
857 reputation = self.reputation,
858 }
859 self.money_in = 0
860 self.money_out = 0
861 end
862
863 --! Returns whether this hospital is controlled by a real person or not.
864 function Hospital:isPlayerHospital()
865 return self == self.world:getLocalPlayerHospital()
866 end
867
868 --! Does the hospital have a reception desk
869 --!param is_staffed (bool) Does the desk need to be staffed
870 --!return (bool) Whether there is a reception desk in the hospital.
871 function Hospital:hasReceptionDesk(is_staffed)
872 return not not self:getReceptionDesks(is_staffed)[1]
873 end
874
875 --! Fetches a list of all reception desks
876 --!param is_staffed (bool) Do the desks need to be staffed
877 --!return (table) A list of relevant desks
878 function Hospital:getReceptionDesks(is_staffed)
879 return is_staffed and self.staffed_reception_desks or self.reception_desks
880 end
881
882 --! Collect the reception desks in the hospital into a list for the above function
883 function Hospital:buildReceptionDesksCache()
884 local reception_desks, staffed_desks = {}, {}
885 for _, obj_list in pairs(self.world.objects) do
886 for _, obj in ipairs(obj_list) do
887 if obj.hospital == self and obj.object_type.id == "reception_desk" and
888 not obj.picked_up then
889 reception_desks[#reception_desks + 1] = obj
890 if obj.receptionist or obj.reserved_for then
891 staffed_desks[#staffed_desks + 1] = obj
892 end
893 end
894 end
895 end
896 self.staffed_reception_desks = staffed_desks
897 self.reception_desks = reception_desks
898 end
899
900 --! Called at the end of each year
901 function Hospital:onEndYear()
902 self.sodas_sold = 0
903 self.num_vips_ty = 0
904 self.pleased_vips_ty = 0
905 self.num_cured_ty = 0
906 self.not_cured_ty = 0
907 self.num_visitors_ty = 0
908 self.num_deaths_this_year = 0
909
910 self.has_impressive_reputation = true
911 self:unconditionalChangeReputation(0) -- Reset self.has_impressive_reputation
912
913 -- On third year of level 3 there is the large increase to salary
914 -- this will replicate that. TODO: check other levels above 5 to
915 -- see if there are other large increases.
916 if self.world:date():year() == 3 and self.world.map.level_number == 3 then
917 -- adds the extra to salary in level 3 year 3
918 self.player_salary = self.player_salary + math.random(8000,20000)
919 end
920 end
921
922 -- Creates complete emergency with patients, what disease they have, what's needed
923 -- to cure them and the fax.
924 --!return (optional string) Textual reason for failure, else nil
925 function Hospital:createEmergency(emergency)
926 local random_disease = self.world.available_diseases[math.random(1, #self.world.available_diseases)]
927 local disease = TheApp.diseases[random_disease.id]
928 local number = math.random(2, disease.emergency_number)
929 if self:getHeliportSpawnPosition() and self:hasReceptionDesk(true) then
930 if not emergency then
931 -- Create a random emergency if parameters are not specified already.
932 emergency = {
933 disease = disease,
934 victims = number,
935 bonus = 1000,
936 percentage = 0.75,
937 killed_emergency_patients = 0,
938 cured_emergency_patients = 0,
939 }
940 end
941
942 -- If disease chosen isn't discovered, cancel emergency
943 if not self.disease_casebook[emergency.disease.id].discovered then
944 return "undiscovered_disease"
945 end
946
947 self.emergency = emergency
948 self:makeEmergencyStartFax()
949 return -- successfully created
950 end
951 return "no_heliport"
952 end
953
954 -- Called when the timer runs out during an emergency or when all emergency patients are cured or dead.
955 function Hospital:resolveEmergency()
956 local emer = self.emergency
957 local rescued_patients = emer.cured_emergency_patients
958 for _, patient in ipairs(self.emergency_patients) do
959 if patient and not patient.cured and not patient.dead
960 and not patient.going_home then
961 patient:setToDying()
962 end
963 end
964 local total = emer.victims
965 local max_bonus = emer.bonus * total
966 local emergency_success = rescued_patients/total >= emer.percentage
967 local earned = 0
968 if emergency_success then
969 earned = emer.bonus * rescued_patients
970 end
971 self:makeEmergencyEndFax(rescued_patients, total, max_bonus, earned)
972 if emergency_success then -- Reputation increased
973 self:changeReputation("emergency_success", emer.disease)
974 self:receiveMoney(earned, _S.transactions.emergency_bonus)
975 else -- Too few rescued, reputation hit
976 self:changeReputation("emergency_failed", emer.disease)
977 end
978
979 self.world:nextEmergency()
980 end
981
982 --! Determine if all of the patients in the emergency have been cured or killed.
983 --! If they have end the emergency timer.
984 function Hospital:checkEmergencyOver()
985 local killed = self.emergency.killed_emergency_patients
986 local cured = self.emergency.cured_emergency_patients
987 if killed + cured >= self.emergency.victims then
988 local window = self.world.ui:getWindow(UIWatch)
989 if window then
990 window:onCountdownEnd()
991 end
992 end
993 end
994
995 --[[ Creates a new epidemic by creating a new contagious patient with
996 a random disease - this is NOT typically how epidemics are started (mainly for cheat use)
997 see @Hospital:determineIfContagious() to see how epidemics are typically started]]
998 function Hospital:spawnContagiousPatient()
999 --[[ Gets the available non-visual disease in the current world
1000 @return non_visuals (table) table of available non-visual diseases or
1001 false if the patient cannot be spawned.
1002 @return message (optional string) The error message that may be caused by using cheats.]]
1003 if self.epidemics_disabled then return false, _S.misc.epidemics_off end
1004
1005 local function get_available_contagious_diseases()
1006 local contagious = {}
1007 for _, disease in ipairs(self.world.available_diseases) do
1008 if disease.contagious then
1009 contagious[#contagious + 1] = disease
1010 end
1011 end
1012 return contagious
1013 end
1014
1015 if self:hasReceptionDesk(true) then
1016 local patient = self.world:newEntity("Patient", 2, 1)
1017 local contagious_diseases = get_available_contagious_diseases()
1018 if #contagious_diseases > 0 then
1019 local disease = contagious_diseases[math.random(1,#contagious_diseases)]
1020 patient:setDisease(disease)
1021 --Move the first patient closer (FOR TESTING ONLY)
1022 local x,y = self:getHeliportSpawnPosition()
1023 if not x then
1024 local spawn_point = self.world.spawn_points[math.random(1, #self.world.spawn_points)]
1025 x, y = spawn_point.x, spawn_point.y
1026 end
1027 patient:setTile(x,y)
1028 patient:setHospital(self)
1029 self:addToEpidemic(patient)
1030 else
1031 return false, _S.misc.epidemic_no_diseases
1032 end
1033 else
1034 return false, _S.misc.epidemic_no_receptionist
1035 end
1036 end
1037
1038 function Hospital:countEpidemics()
1039 -- Count the current epidemic if it exists
1040 local epidemic_count = self.epidemic and 1 or 0
1041 epidemic_count = epidemic_count + #self.future_epidemics_pool
1042 return epidemic_count
1043 end
1044
1045 --[[ Make the active epidemic (if exists) and any future epidemics tick. If there
1046 is no current epidemic determines if any epidemic in the pool of future
1047 epidemics can become the active one. Also removes any epidemics from the
1048 future pool which have no infected patients and thus, will have no effect on
1049 the hospital. ]]
1050 function Hospital:manageEpidemics()
1051 --[[ Can the future epidemic be revealed to the player
1052 @param future_epidemic (Epidemic) the epidemic to attempt to reveal
1053 @return true if can be revealed false otherwise (boolean) ]]
1054 local function can_be_revealed(epidemic)
1055 return not self.world.ui:getWindow(UIWatch) and
1056 not self.epidemic and epidemic.ready_to_reveal
1057 end
1058
1059 local current_epidemic = self.epidemic
1060 if(current_epidemic) then
1061 current_epidemic:tick()
1062 end
1063
1064 if self.future_epidemics_pool then
1065 for i, future_epidemic in ipairs(self.future_epidemics_pool) do
1066 if future_epidemic:hasNoInfectedPatients() then
1067 table.remove(self.future_epidemics_pool,i)
1068 elseif can_be_revealed(future_epidemic) then
1069 self.epidemic = future_epidemic
1070 self.epidemic:revealEpidemic()
1071 table.remove(self.future_epidemics_pool,i)
1072 else
1073 future_epidemic:tick()
1074 end
1075 end
1076 end
1077 end
1078
1079 --! Cancel ongoing and future epidemics.
1080 --!param disease (table) Optional, if specified only epidemics of a certain disease
1081 -- will be cancelled.
1082 function Hospital:cancelEpidemics(disease)
1083 local function cancelEpidemic(epidemic)
1084 if disease and disease ~= epidemic.disease then return false end
1085 epidemic:cancelEpidemic()
1086 return true
1087 end
1088 -- Cancel ongoing epidemic
1089 if self.epidemic ~= nil then
1090 if cancelEpidemic(self.epidemic) then self.epidemic = nil end
1091 end
1092 -- Cancel not revealed epidemics
1093 if self.future_epidemics_pool then
1094 local future_epidemics = self.future_epidemics_pool
1095 for i=#future_epidemics, 1, -1 do
1096 if cancelEpidemic(future_epidemics[i]) then
1097 table.remove(self.future_epidemics_pool, i)
1098 end
1099 end
1100 end
1101 end
1102
1103 --[[ Determines if a patient is contagious and then attempts to add them the
1104 appropriate epidemic if so.
1105 @param patient (Patient) patient to determine if contagious]]
1106 function Hospital:determineIfContagious(patient)
1107 if self.epidemics_disabled or patient.is_emergency or not patient.disease.contagious then
1108 return false
1109 end
1110 -- ContRate treated like a percentage with ContRate% of patients with
1111 -- a disease having the contagious strain
1112 local level_config = self.world.map.level_config
1113 local disease = patient.disease
1114 local contRate = level_config.expertise[disease.expertise_id].ContRate or 0
1115
1116 -- The patient is potentially contagious as we do not yet know if there
1117 -- is a suitable epidemic which they can belong to
1118 local potentially_contagious = contRate > 0 and (math.random(1,contRate) == contRate)
1119 -- The patient isn't contagious if these conditions aren't passed
1120 local reduce_months = level_config.ReduceContMonths or 14
1121 local reduce_people = level_config.ReduceContPeepCount or 20
1122 local date_in_months = self.world:date():monthOfGame()
1123
1124 if potentially_contagious and date_in_months > reduce_months and
1125 self.num_visitors > reduce_people then
1126 self:addToEpidemic(patient)
1127 end
1128 end
1129
1130 --[[ Determines if there is a suitable epidemic the contagious patient can
1131 belong to and adds them to it if possible. N.B. a patient isn't actually
1132 contagious until they belong to an epidemic. So if it isn't possible to add a
1133 patient to an epidemic they are just treated as a normal patient.
1134 @param patient (Patient) patient to attempt to add to an epidemic ]]
1135 function Hospital:addToEpidemic(patient)
1136 local epidemic = self.epidemic
1137 -- Don't add a new contagious patient if the player is trying to cover up
1138 -- an existing epidemic - not really fair
1139 if epidemic and not epidemic.coverup_selected and
1140 (patient.disease == epidemic.disease) then
1141 epidemic:addContagiousPatient(patient)
1142 elseif self.future_epidemics_pool and
1143 not (epidemic and epidemic.coverup_selected) then
1144 local added = false
1145 for _, future_epidemic in ipairs(self.future_epidemics_pool) do
1146 if future_epidemic.disease == patient.disease then
1147 future_epidemic:addContagiousPatient(patient)
1148 added = true
1149 break
1150 end
1151 end
1152
1153 if not added then
1154 -- Make a new epidemic as one doesn't exist with this disease, but only if
1155 -- we haven't reach the concurrent epidemic limit
1156 if self:countEpidemics() < self.concurrent_epidemic_limit then
1157 local new_epidemic = Epidemic(self, patient)
1158 self.future_epidemics_pool[#self.future_epidemics_pool + 1] = new_epidemic
1159 end
1160 end
1161 end
1162 end
1163
1164
1165 function Hospital:spawnPatient()
1166 self.world:spawnPatient(self)
1167 end
1168
1169 local debug_n
1170 function Hospital:getDebugPatient()
1171 if not debug_n or debug_n >= #self.debug_patients then
1172 debug_n = 1
1173 else
1174 debug_n = debug_n + 1
1175 end
1176 return self.debug_patients[debug_n]
1177 end
1178
1179 --[[ Returns how much a given object currently costs to purchase. The cost
1180 may be affected by research progress.
1181
1182 !param name (string) The name (id) of the object to investigate.
1183 ]]
1184 function Hospital:getObjectBuildCost(name)
1185 -- Everything is free in free build mode.
1186 if self.world.free_build_mode then return 0 end
1187
1188 local progress = self.research.research_progress
1189 local cfg_objects = self.world.map.level_config.objects
1190 local obj_def = TheApp.objects[name]
1191 -- Get how much this item costs at the start of the level.
1192 local obj_cost = cfg_objects[obj_def.thob].StartCost
1193 -- Some objects might have got their cost reduced by research.
1194 if progress[obj_def] then
1195 obj_cost = progress[obj_def].cost
1196 end
1197 return obj_cost
1198 end
1199
1200 --[[ Lowers the player's money by the given amount and logs the transaction.
1201
1202 !param amount (integer) The (positive) amount to spend.
1203 !param reason (string) A string that shows what happened. Should be one of the strings
1204 in _S.transactions.
1205 !param changeValue (integer) The (positive) amount the hospital value should be increased
1206 ]]
1207 function Hospital:spendMoney(amount, reason, changeValue)
1208 if not self.world.free_build_mode then
1209 self.balance = self.balance - amount
1210 self:logTransaction({spend = amount, desc = reason})
1211 self.money_out = self.money_out + amount
1212 if changeValue then
1213 self.value = self.value + changeValue
1214 end
1215 end
1216 end
1217
1218 --[[ Increases the player's money by the given amount and logs the transaction.
1219
1220 !param amount (integer) The (positive) amount to receive.
1221 !param reason (string) A string that tells what happened. Should be one of the strings
1222 in _S.transactions.
1223 !param changeValue (integer) The (positive) amount the hospital value should be decreased
1224 ]]
1225 function Hospital:receiveMoney(amount, reason, changeValue)
1226 if not self.world.free_build_mode then
1227 self.balance = self.balance + amount
1228 self:logTransaction({receive = amount, desc = reason})
1229 self.money_in = self.money_in + amount
1230 if changeValue then
1231 self.value = self.value - changeValue
1232 end
1233 end
1234 end
1235
1236 --[[ Determines how much the player should receive after a patient is treated in a room.
1237
1238 !param patient (Patient) The patient that just got treated.
1239 ]]
1240 function Hospital:receiveMoneyForTreatment(patient)
1241 if not self.world.free_build_mode then
1242 local disease_id = patient:getTreatmentDiseaseId()
1243 if disease_id == nil then return end
1244 local casebook = self.disease_casebook[disease_id]
1245 local reason
1246 if casebook.pseudo then
1247 reason = _S.transactions.treat_colon .. " " .. casebook.disease.name
1248 else
1249 reason = _S.transactions.cure_colon .. " " .. casebook.disease.name
1250 end
1251 local amount = patient.pay_amount or 0
1252 amount = amount > 0 and amount or self:getTreatmentPrice(disease_id)
1253
1254 -- 25% of the payments now go through insurance
1255 if patient.insurance_company then
1256 self:addInsuranceMoney(patient.insurance_company, amount)
1257 else
1258 -- patient is paying normally (but still, he could feel like it's
1259 -- under- or over-priced and it could impact happiness and reputation)
1260 self:computePriceLevelImpact(patient, casebook)
1261 self:receiveMoney(amount, reason)
1262 end
1263 casebook.money_earned = casebook.money_earned + amount
1264 patient.world:newFloatingDollarSign(patient, amount)
1265 patient.pay_amount = 0
1266 end
1267 end
1268
1269 --! Sell a soda to a patient for the price in the level config (default $20).
1270 --!param patient (patient) The patient buying the soda.
1271 function Hospital:sellSodaToPatient(patient)
1272 local soda_price = self.world.map.level_config.gbv.SodaPrice
1273 self:receiveMoneyForProduct(patient, soda_price, _S.transactions.drinks)
1274 self.sodas_sold = self.sodas_sold + 1
1275 end
1276
1277 --! Function to determine the price for a treatment, modified by reputation and percentage
1278 -- Treatment charge should never be less than the starting price if reputation falls below 500
1279 function Hospital:getTreatmentPrice(disease)
1280 local reputation = self.disease_casebook[disease].reputation or self.reputation
1281 local percentage = self.disease_casebook[disease].price
1282 local raw_price = self.disease_casebook[disease].disease.cure_price
1283 if reputation >= 500 then
1284 return math.ceil(raw_price * (reputation / 500) * percentage)
1285 else
1286 return math.ceil(raw_price * percentage)
1287 end
1288 end
1289
1290 function Hospital:addInsuranceMoney(company, amount)
1291 local old_balance = self.insurance_balance[company][1]
1292 self.insurance_balance[company][1] = old_balance + amount
1293 end
1294
1295 function Hospital:receiveMoneyForProduct(patient, amount, reason)
1296 patient.world:newFloatingDollarSign(patient, amount)
1297 self:receiveMoney(amount, reason)
1298 end
1299
1300 --! Pay drug if drug has been purchased to treat a patient.
1301 --!param disease_id Disease that was treated.
1302 function Hospital:paySupplierForDrug(disease_id)
1303 local drug_amount = self.disease_casebook[disease_id].drug_cost or 0
1304 if drug_amount ~= 0 then
1305 local str = _S.drug_companies[math.random(1, 5)]
1306 self:spendMoney(drug_amount, _S.transactions.drug_cost .. ": " .. str)
1307 end
1308 end
1309
1310 --[[ Add a transaction to the hospital's transaction log.
1311 !param transaction (table) A table containing a string field called `desc`, and
1312 at least one of the following integer fields: `spend`, `receive`.
1313 ]]
1314 function Hospital:logTransaction(transaction)
1315 transaction.balance = self.balance
1316 transaction.day = self.world:date():dayOfMonth()
1317 transaction.month = self.world:date():monthOfYear()
1318 while #self.transactions > 20 do
1319 self.transactions[#self.transactions] = nil
1320 end
1321 table.insert(self.transactions, 1, transaction)
1322 end
1323
1324 --! Initialize hospital staff from the level config.
1325 function Hospital:initStaff()
1326 local level_config = self.world.map.level_config
1327 if level_config.start_staff then
1328 for _, conf in ipairs(level_config.start_staff) do
1329 local profile
1330 local skill = 0
1331 local added_staff = true
1332 if conf.Skill then
1333 skill = conf.Skill / 100
1334 end
1335
1336 if conf.Nurse == 1 then
1337 profile = StaffProfile(self.world, "Nurse", _S.staff_class["nurse"])
1338 profile:init(skill)
1339 elseif conf.Receptionist == 1 then
1340 profile = StaffProfile(self.world, "Receptionist", _S.staff_class["receptionist"])
1341 profile:init(skill)
1342 elseif conf.Handyman == 1 then
1343 profile = StaffProfile(self.world, "Handyman", _S.staff_class["handyman"])
1344 profile:init(skill)
1345 elseif conf.Doctor == 1 then
1346 profile = StaffProfile(self.world, "Doctor", _S.staff_class["doctor"])
1347
1348 local shrink = 0
1349 local rsch = 0
1350 local surg = 0
1351 local jr, cons
1352
1353 if conf.Shrink == 1 then shrink = 1 end
1354 if conf.Surgeon == 1 then surg = 1 end
1355 if conf.Researcher == 1 then rsch = 1 end
1356
1357 if conf.Junior == 1 then jr = 1
1358 elseif conf.Consultant == 1 then cons = 1
1359 end
1360 profile:initDoctor(shrink,surg,rsch,jr,cons,skill)
1361 else
1362 added_staff = false
1363 end
1364 if added_staff then
1365 local staff = self.world:newEntity(profile.humanoid_class, 2, 2)
1366 staff:setProfile(profile)
1367
1368 -- Identify a safe starting place and
1369 -- try to place the staff member randomly near it or on it
1370 local map = self.world.map.th
1371 local map_x_length, map_y_length = map:size()
1372 local map_offset = 10
1373 local x, y = map:getCameraTile(self:getPlayerIndex())
1374 -- Make sure the random numbers (x_attempt, y_attempt) will be safely within the map
1375 local x_safe = math.max(map_offset + 1, math.min(x, map_x_length - map_offset))
1376 local y_safe = math.max(map_offset + 1, math.min(y, map_y_length - map_offset))
1377 local x_attempt, y_attempt
1378 local attempts = 0
1379 repeat
1380 x_attempt = x_safe + math.random(-map_offset, map_offset)
1381 y_attempt = y_safe + math.random(-map_offset, map_offset)
1382 attempts = attempts + 1
1383 until attempts > 100 or self:isInHospital(x_attempt, y_attempt)
1384 if attempts <= 100 then
1385 staff:setTile(x_attempt, y_attempt)
1386 elseif self:isInHospital(x, y) then
1387 staff:setTile(x, y)
1388 else
1389 staff:setTile(map_x_length / 2, map_y_length / 2)
1390 end
1391 staff:onPlaceInCorridor()
1392 self.staff[#self.staff + 1] = staff
1393 staff:setHospital(self)
1394 end
1395 end
1396 end
1397 end
1398
1399
1400 function Hospital:addStaff(staff)
1401 self.staff[#self.staff + 1] = staff
1402 -- Cost of hiring staff:
1403 self:spendMoney(staff.profile.wage, _S.transactions.hire_staff .. ": "
1404 .. staff.profile:getFullName())
1405 self:notifyOfStaffChange(staff)
1406 end
1407
1408 function Hospital:addPatient(patient)
1409 self.patients[#self.patients + 1] = patient
1410 -- Add to the hospital's visitor count
1411 self.num_visitors = self.num_visitors + 1
1412 self.num_visitors_ty = self.num_visitors_ty + 1
1413
1414 -- Decide if the patient belongs in an epidemic
1415 self:determineIfContagious(patient)
1416 end
1417
1418 --! Humanoid has died, record the incident.
1419 --!param patient The deceased.
1420 function Hospital:humanoidDeath(patient)
1421 self:msgKilled()
1422
1423 if not patient.is_debug then
1424 local case = self.disease_casebook[patient.disease.id]
1425 case.fatalities = case.fatalities + 1
1426 end
1427 self.num_deaths = self.num_deaths + 1
1428 self.num_deaths_this_year = self.num_deaths_this_year + 1
1429
1430 self:changeReputation("death", patient.disease)
1431 self:updatePercentages()
1432
1433 if patient.is_emergency then
1434 self.emergency.killed_emergency_patients = self.emergency.killed_emergency_patients + 1
1435 end
1436 end
1437
1438 --! Remove all tasks assigned to Handyman
1439 --!param handyman (object) target handyman
1440 function Hospital:unassignHandymanTasks(handyman)
1441 local tasks = self:findAssignedTasksToHandyman(handyman)
1442 for _, task in ipairs(tasks) do
1443 task.assignedHandyman = nil
1444 end
1445 end
1446
1447 --! Checks if the hospital employs staff of a given category.
1448 --!param category (string) A humanoid_class or one of the specialists, i.e.
1449 --! "Doctor", "Nurse", "Handyman", "Receptionist", "Psychiatrist",
1450 --! "Surgeon", "Researcher", "Junior" or "Consultant"
1451 --!param max_count (optional integer) If provided, non-negative maximum count to return.
1452 --! returns Number of that type employed, at most max_count is returned if provided.
1453 function Hospital:countStaffOfCategory(category, max_count)
1454 local result = 0
1455 for _, staff in ipairs(self.staff) do
1456 if staff:fulfillsCriterion(category) then
1457 result = result + 1
1458 end
1459 if max_count ~= nil and result >= max_count then break end
1460 end
1461 return result
1462 end
1463
1464 --! Checks if the hospital has a room of a given type.
1465 --!param type (string) A room_info.id, e.g. "ward".
1466 --!param max_count (optional integer) If provided, non-negative maximum count to return.
1467 --! Returns Number of that type found, at most max_count is returned if provided.
1468 function Hospital:countRoomOfType(type, max_count)
1469 -- Check how many rooms there are.
1470 local result = 0
1471 for _, room in pairs(self.world.rooms) do
1472 if room.hospital == self and room.room_info.id == type and room.is_active then
1473 result = result + 1
1474 if max_count ~= nil and result >= max_count then break end
1475 end
1476 end
1477 return result
1478 end
1479
1480 --! Update tile object counts for adding an object.
1481 --! See also 'Hospital:removeTileObject'
1482 --!param object_category Category of the tile object.
1483 function Hospital:addTileObject(object_category)
1484 if object_category then
1485 local current_count = self.tile_object_counts[object_category]
1486 self.tile_object_counts[object_category] = current_count + 1
1487 end
1488 end
1489
1490 --! Update tile object counts for removing an object.
1491 --! See also 'Hospital:addTileObject'
1492 --!param object_category Category of the tile object.
1493 function Hospital:removeTileObject(object_category)
1494 if object_category then
1495 local current_count = self.tile_object_counts[object_category]
1496 self.tile_object_counts[object_category] = current_count - 1
1497 end
1498 end
1499
1500 --! Get the number of reception desks in the hospital.
1501 --!return (int) Number of reception desks in the hospital.
1502 function Hospital:countReceptionDesks()
1503 return self.tile_object_counts["reception_desk"]
1504 end
1505
1506 --! Get the number of radiators in the hospital.
1507 --!return (int) Number of radiators in the hospital.
1508 function Hospital:countRadiators()
1509 return self.tile_object_counts["radiator"]
1510 end
1511
1512 --! Get the number of plants in the hospital.
1513 --!return (int) Number of plants in the hospital.
1514 function Hospital:countPlants()
1515 return self.tile_object_counts["plant"]
1516 end
1517
1518 --! Get the number of fire extinguishers in the hospital.
1519 --!return (int) Number of fire extinguishers in the hospital.
1520 function Hospital:countFireExtinguishers()
1521 return self.tile_object_counts["extinguisher"]
1522 end
1523
1524 --! Get the number of general objects in the hospital.
1525 --!return (int) Number of general objects in the hospital.
1526 function Hospital:countGeneralObjects()
1527 return self.tile_object_counts["general"]
1528 end
1529
1530 --! A new object has been placed in the hospital.
1531 --!param entity (Entity) The entity that was just placed.
1532 --!param id (string) That entity's id.
1533 function Hospital:objectPlaced(entity, id)
1534 -- If it is a bench we're placing, notify queueing patients in the vicinity
1535 if id == "bench" then
1536 local notify_distance = 6
1537 local w, h = self.world.map.th:size()
1538 for tx = math.max(1, entity.tile_x - notify_distance), math.min(w, entity.tile_x + notify_distance) do
1539 for ty = math.max(1, entity.tile_y - notify_distance), math.min(h, entity.tile_y + notify_distance) do
1540 if self:isInHospital(tx, ty) then -- Only patients of this hospital should be warned.
1541 for _, patient in ipairs(self.world.entity_map:getHumanoidsAtCoordinate(tx, ty)) do
1542 if class.is(patient, Patient) then
1543 patient:notifyNewObject(id)
1544 end
1545 end
1546 end
1547 end
1548 end
1549 return
1550 end
1551
1552 if id == "reception_desk" then
1553 self:msgReceptionDesk()
1554 return
1555 end
1556
1557 if id == "plant" then
1558 self:advisePlants(true)
1559 return
1560 end
1561
1562 if id == "gates_to_hell" then
1563 self:showGatesToHell(entity)
1564 return
1565 end
1566 end
1567
1568 --! Remove the first entry with a given value from a table.
1569 --! Only works reliably for lists.
1570 --!param t Table to search for the value, and update.
1571 --!param value Value to search and remove.
1572 --!return Whether the value was removed.
1573 local function RemoveByValue(t, value)
1574 for i, v in ipairs(t) do
1575 if v == value then
1576 table.remove(t, i)
1577 return true
1578 end
1579 end
1580 return false
1581 end
1582
1583 --! Remove a staff member from the hospital staff.
1584 --!param staff (Staff) Staff member to remove.
1585 function Hospital:removeStaff(staff)
1586 RemoveByValue(self.staff, staff)
1587 -- update all messages for waiting patients
1588 self:notifyOfStaffChange(staff)
1589 end
1590
1591 --! Remove a patient from the hospital.
1592 -- Also if a debug patient, they are also removed from the debug list.
1593 --!param patient (Patient) Patient to remove.
1594 function Hospital:removePatient(patient)
1595 if patient.is_debug then self:removeDebugPatient(patient) end
1596 RemoveByValue(self.patients, patient)
1597 end
1598
1599 --! Remove a debug patient from the debug list.
1600 --!param patient (Patient) Patient to remove
1601 function Hospital:removeDebugPatient(patient)
1602 RemoveByValue(self.debug_patients, patient)
1603 end
1604
1605 -- TODO: This should depend on difficulty and level
1606 local reputation_changes = {
1607 ["cured"] = 1, -- a patient was successfully treated
1608 ["death"] = -4, -- a patient died due to bad treatment or waiting too long
1609 ["kicked"] = -3, -- firing a staff member OR sending a patient home
1610 ["emergency_success"] = 15,
1611 ["emergency_failed"] = -20,
1612 ["over_priced"] = -2,
1613 ["under_priced"] = 1,
1614 ["room_crash"] = -50,
1615 }
1616
1617 --! Normally reputation is changed based on a reason, and the affected
1618 --! disease also has its own reputation meter.
1619 --!param reason (string) The reason for changing reputation, for example "cured" or "death".
1620 --!param disease The disease, if any, that should be affected.
1621 --!param valueChange (integer) In some cases, for example at year end, the amount varies a lot.
1622 -- Then it is specified here.
1623 function Hospital:changeReputation(reason, disease, valueChange)
1624 local amount
1625 if reason == "autopsy_discovered" then
1626 local rep_hit_perc = self.world.map.level_config.gbv.AutopsyRepHitPercent
1627 amount = rep_hit_perc and math.floor(-self.reputation * rep_hit_perc / 100) or -70
1628 elseif valueChange then
1629 amount = valueChange
1630 else
1631 amount = reputation_changes[reason]
1632 end
1633 if self:isReputationChangeAllowed(amount) then
1634 self:unconditionalChangeReputation(amount)
1635 end
1636 if disease then
1637 local casebook = self.disease_casebook[disease.id]
1638 casebook.reputation = casebook.reputation + amount
1639 end
1640 end
1641
1642 --! Unconditionally change the reputation.
1643 --! In most cases, the better entry point for changing reputation
1644 --! is 'Hospital:changeReputation'.
1645 --!param valueChange (integer) Amount of change.
1646 function Hospital:unconditionalChangeReputation(valueChange)
1647 self.reputation = self.reputation + valueChange
1648
1649 if self.reputation < self.reputation_min then
1650 self.reputation = self.reputation_min
1651 elseif self.reputation > self.reputation_max then
1652 self.reputation = self.reputation_max
1653 end
1654
1655 -- Check if criteria for trophy is still met
1656 if self.has_impressive_reputation then
1657 local level_config = self.world.map.level_config
1658 if level_config.awards_trophies then
1659 local min_repuration = level_config.awards_trophies.Reputation
1660 self.has_impressive_reputation = min_repuration < self.reputation
1661 return
1662 end
1663 self.has_impressive_reputation = false
1664 end
1665 end
1666
1667 --! Decide whether a reputation change is effective or not. As we approach 1000,
1668 --! a gain is less likely. As we approach 0, a loss is less likely.
1669 --! Under 500, a gain is always effective. Over 500, a loss is always effective.
1670 --!param amount (int): The amount of reputation change.
1671 function Hospital:isReputationChangeAllowed(amount)
1672 if (amount > 0 and self.reputation <= 500) or (amount < 0 and self.reputation >= 500) or (amount == 0) then
1673 return true
1674 else
1675 return math.random() <= self:getReputationChangeLikelihood()
1676 end
1677 end
1678
1679 --! Compute the likelihood for a reputation change to be effective.
1680 --! Likelihood gets smaller as hospital reputation gets closer to extreme values.
1681 --!return (float) Likelihood of a reputation change.
1682 function Hospital:getReputationChangeLikelihood()
1683 -- The result follows a quadratic function, for a curved and smooth evolution.
1684 -- If reputation == 500, the result is 100%.
1685 -- Between [380-720], the result is still over 80%.
1686 -- At 100 or 900, it's under 40%.
1687 -- At 0 or 1000, it's 0%.
1688 --
1689 -- The a, b and c coefficients have been computed to include points
1690 -- (x=0, y=1), (x=500, y=0) and (x=1000, y=1) where x is the current
1691 -- reputation and y the likelihood of the reputation change to be
1692 -- refused, based a discriminant (aka "delta") == 0
1693 local a = 0.000004008
1694 local b = 0.004008
1695 local c = 1
1696
1697 local x = self.reputation
1698
1699 -- The result is "reversed" for more readability
1700 return 1 - (a * x * x - b * x + c)
1701 end
1702
1703 --! Update the 'cured' counts of the hospital.
1704 --!param patient Patient that was cured.
1705 function Hospital:updateCuredCounts(patient)
1706 if not patient.is_debug then
1707 self:changeReputation("cured", patient.disease)
1708 end
1709
1710 self.num_cured = self.num_cured + 1
1711 self.num_cured_ty = self.num_cured_ty + 1
1712
1713 local casebook = self.disease_casebook[patient.disease.id]
1714 casebook.recoveries = casebook.recoveries + 1
1715
1716 if patient.is_emergency then
1717 self.emergency.cured_emergency_patients = self.emergency.cured_emergency_patients + 1
1718 end
1719
1720 self:msgCured()
1721 end
1722
1723 --! Update the 'not cured' counts of the hospital.
1724 --!param patient Patient that was not cured.
1725 --!param reason (string) the reason why the patient is not cured.
1726 --! -"kicked": Patient goes home early (manually sent, no treatment room, etc).
1727 --! -"over_priced": Patient considers the price too high.
1728 function Hospital:updateNotCuredCounts(patient, reason)
1729 if patient.is_debug then return end
1730
1731 self:changeReputation(reason, patient.disease)
1732 self.not_cured = self.not_cured + 1
1733 self.not_cured_ty = self.not_cured_ty + 1
1734
1735 if reason == "kicked" then
1736 local casebook = self.disease_casebook[patient.disease.id]
1737 casebook.turned_away = casebook.turned_away + 1
1738 end
1739
1740 -- though not killed allows timer to close early
1741 if patient.is_emergency then
1742 self.emergency.killed_emergency_patients = self.emergency.killed_emergency_patients + 1
1743 end
1744 end
1745
1746 function Hospital:updatePercentages()
1747 local killed = self.num_deaths / (self.num_cured + self.num_deaths) * 100
1748 self.percentage_killed = math.round(killed)
1749 local cured = self.num_cured / (self.num_cured + self.not_cured + self.num_deaths) * 100
1750 self.percentage_cured = math.round(cured)
1751 end
1752
1753 --! Compute average of an attribute for all patients in the hospital.
1754 --!param attribute (str) Name of the attribute.
1755 --!param default_value Value to return if there are not enough patients.
1756 --!param min_count (number) Minimal number of sampled patients, 4 by default.
1757 --!return Average value of the attribute for all hospital patients, compensated
1758 -- towards the default if there are not enough patients in the hospital.
1759 function Hospital:getAveragePatientAttribute(attribute, default_value, min_count)
1760 if type(min_count) ~= "number" or min_count < 1 then min_count = 4 end
1761
1762 return self:_getAverageHumanoidsAttribute(self.patients, attribute, default_value,
1763 min_count)
1764 end
1765
1766 --! Compute average of an attribute for all staff in the hospital.
1767 --!param attribute (str) Name of the attribute.
1768 --!param default_value Value to return if there is no staff.
1769 --!return Average value of the attribute for all staff, or the default value.
1770 function Hospital:getAverageStaffAttribute(attribute, default_value)
1771 return self:_getAverageHumanoidsAttribute(self.staff, attribute, default_value, 1)
1772 end
1773
1774 --! Compute average of an attribute for all given humanoids.
1775 --!param humanoids The collection of humanoids to query.
1776 --!param attribute (str) Name of the attribute.
1777 --!param default_value (any type) Value to return if there are not enough humanoids.
1778 --!param min_count (number) Minimal number of sampled humanoids required, 4 by
1779 -- default. If less humanoids are available than the minimal count, additional
1780 -- fake humanoids are 'counted' with the default value of the attribute if
1781 -- possible. Use 1 as min_count to avoid compensating.
1782 --!return Average value of the attribute for all humanoids, possibly compensated
1783 -- towards the default if there are not enough humanoids in the hospital.
1784 function Hospital:_getAverageHumanoidsAttribute(humanoids, attribute,
1785 default_value, min_count)
1786 assert(type(min_count) == "number" and min_count >= 1)
1787
1788 -- Sum the attribute for all humanoids.
1789 local sum = 0
1790 local count = 0
1791 for _, hum in ipairs(humanoids) do
1792 local tx, ty = hum.tile_x, hum.tile_y
1793 -- Skip counting the humanoid if they don't have the attribute (eg Alien).
1794 if tx and ty and self:isInHospital(tx, ty) and hum.attributes[attribute] then
1795 sum = sum + hum.attributes[attribute]
1796 count = count + 1
1797 end
1798 end
1799
1800 -- Handle compensation for not enough humanoids.
1801 if count < min_count then
1802 -- Skip compensating if the default is not a number.
1803 if type(default_value) ~= "number" then return default_value end
1804
1805 -- Add fake humanoids until the min_count is satisfied. This gives a more
1806 -- gradual change towards the real average as more humanoids become available.
1807 while count < min_count do
1808 sum = sum + default_value
1809 count = count + 1
1810 end
1811 end
1812
1813 return sum / count
1814 end
1815
1816 --! Checks if the requirements for the given disease are met in the hospital and returns the ones missing.
1817 --!param disease (String) The disease to check the requirements for
1818 --! returns false if all requirements are met, else a table in the form
1819 --! { rooms = {[room1], [room2], ...}, staff = {[humanoid_class] = [amount_needed] or nil} }
1820 --! i.e. a list of rooms (ordered the same as disease.treatment_rooms), and a set of humanoid_classes with
1821 --! the needed amount of that class as the value
1822 function Hospital:checkDiseaseRequirements(disease)
1823 -- Copy rooms list from disease but leave out the ones that are present in the hospital
1824 -- Get required staff from all rooms required by the disease, if not already present in hospital
1825 local rooms = {}
1826 local staff = {}
1827 local any = false
1828 for _, room_id in ipairs(self.world.available_diseases[disease].treatment_rooms) do
1829 local found = self:countRoomOfType(room_id, 1) > 0
1830 if not found then
1831 rooms[#rooms + 1] = room_id
1832 any = true
1833 end
1834
1835 -- Get staff for room
1836 for staff_class, amount in pairs(TheApp.rooms[room_id].required_staff) do
1837 local available = self:countStaffOfCategory(staff_class)
1838 if available < amount then
1839 -- Don't add up the staff requirements of different rooms, but take the maximum
1840 staff[staff_class] = math.max(staff[staff_class] or 0, amount - available)
1841 any = true
1842 end
1843 end
1844 end
1845 -- False if no rooms and no staff were added
1846 return any and {rooms = rooms, staff = staff}
1847 end
1848
1849 --! Get the set of walls around a tile position.
1850 --!param x (int) X position of the queried tile.
1851 --!param y (int) Y position of the queried tile.
1852 --!return (table {wall, parcel}) The walls around the given position.
1853 function Hospital:getWallsAround(x, y)
1854 local map = self.world.map
1855 local th = map.th
1856
1857 local _, nw, ww
1858 local walls = {} -- List of {wall="north"/"west"/"south"/"east", parcel}
1859 local flags = th:getCellFlags(x, y)
1860
1861 _, nw, ww = th:getCell(x, y) -- floor, north wall, west wall
1862 if ww ~= 0 then
1863 walls[#walls + 1] = {wall = "west", parcel = flags.parcelId}
1864 end
1865 if nw ~= 0 then
1866 walls[#walls + 1] = {wall = "north", parcel = flags.parcelId}
1867 end
1868
1869 if x ~= map.width then
1870 _, _, ww = th:getCell(x + 1, y)
1871 if ww ~= 0 then
1872 walls[#walls + 1] = {wall = "east", parcel = flags.parcelId}
1873 end
1874 end
1875
1876 if y ~= map.height then
1877 _, nw, _ = th:getCell(x, y + 1)
1878 if nw ~= 0 then
1879 walls[#walls + 1] = {wall = "south", parcel = flags.parcelId}
1880 end
1881 end
1882
1883 return walls
1884 end
1885
1886 --! Test for the given position to be inside the given rectangle.
1887 --!param x (int) X position to test.
1888 --!param y (int) Y position to test.
1889 --!param rect (table x, y, width, height) Rectangle to check against.
1890 --!return (bool) Whether the position is inside the rectangle.
1891 local function isInside(x, y, rect)
1892 return x >= rect.x and x < rect.x + rect.width and y >= rect.y and y < rect.y + rect.height
1893 end
1894
1895 --! Find all ratholes that match the `to_match` criteria.
1896 --!param holes (list ratholes) Currently existing holes.
1897 --!param to_match (table) For each direction a rectangle with matching tile positions.
1898 --!return (list) Matching ratholes.
1899 local function findMatchingRatholes(holes, to_match)
1900 local matched = {}
1901 for _, hole in ipairs(holes) do
1902 if isInside(hole.x, hole.y, to_match[hole.wall]) then table.insert(matched, hole) end
1903 end
1904 return matched
1905 end
1906
1907 --! Remove the ratholes that use the walls of the provided room.
1908 --!param room (Room) Room being de-activated.
1909 function Hospital:removeRatholesAroundRoom(room)
1910 local above_rect = {x = room.x, width = room.width, y = room.y - 1, height = 1}
1911 local below_rect = {x = room.x, width = room.width, y = room.y +room.height, height = 1}
1912 local left_rect = {x = room.x - 1, width = 1, y = room.y, height = room.height}
1913 local right_rect = {x = room.x + room.width, width = 1, y = room.y, height = room.height}
1914
1915 local to_delete = {east = left_rect, west = right_rect, south = above_rect, north = below_rect}
1916
1917 local remove_holes = findMatchingRatholes(self.ratholes, to_delete)
1918 for _, hole in ipairs(remove_holes) do self:removeRathole(hole) end
1919 end
1920
1921 -- Add a rathole to the room.
1922 --!param x (int) X position of the tile containing the rathole.
1923 --!param y (int) Y position of the tile containing the rathole.
1924 --!param wall (string) Wall containing the hole (north, west, south, east)
1925 --!param parcel (int) Parcel number of the xy position.
1926 function Hospital:addRathole(x, y, wall, parcel)
1927 for _, rathole in ipairs(self.ratholes) do
1928 if rathole.x == x and rathole.y == y and rathole.wall == wall then return end
1929 end
1930
1931 local hole = {x = x, y = y, wall = wall, parcel = parcel}
1932 if wall == "north" or wall == "west" then
1933 -- Only add a rat-hole graphics object for the visible holes.
1934 hole["object"] = self.world:newObject("rathole", hole.x, hole.y, hole.wall)
1935 end
1936 table.insert(self.ratholes, hole)
1937 end
1938
1939 --! Remove the provided rathole.
1940 --!param hole (table{x, y, wall, optional object}) Hole to remove.
1941 function Hospital:removeRathole(hole)
1942 for i, rathole in ipairs(self.ratholes) do
1943 if rathole.x == hole.x and rathole.y == hole.y and rathole.wall == hole.wall then
1944 table.remove(self.ratholes, i)
1945 if rathole.object then
1946 self.world:destroyEntity(rathole.object)
1947 end
1948
1949 break
1950 end
1951 end
1952 end
1953
1954 --! Remove any rathole from the given position.
1955 --!param x X position of the tile that should not have ratholes.
1956 --!param y Y position of the tile that should not have ratholes.
1957 function Hospital:removeRatholeXY(x, y)
1958 for i = #self.ratholes, 1, -1 do
1959 local rathole = self.ratholes[i]
1960 if rathole.x == x and rathole.y == y then
1961 table.remove(self.ratholes, i)
1962 if rathole.object then self.world:destroyEntity(rathole.object) end
1963 end
1964 end
1965 end
1966
1967 --! Adds a handyman task
1968 --!param object The object needing attention
1969 --!param taskType The handyman task type: repairing, watering, cleaning
1970 --!param priority Task priority: 1 is low, 2 is high
1971 --!param x coordinate
1972 --!param y coordinate
1973 --!param call The call added to the dispatcher
1974 function Hospital:addHandymanTask(object, taskType, priority, x, y, call)
1975 local parcelId = self.world.map.th:getCellFlags(x, y).parcelId
1976 local subTable = self:findHandymanTaskSubtable(taskType)
1977 table.insert(subTable, {["object"] = object, ["priority"] = priority, ["tile_x"] = x, ["tile_y"] = y, ["parcelId"] = parcelId, ["call"] = call})
1978 end
1979
1980 --! Queries the priority of an existing handyman task
1981 --!param taskIndex (integer) Number of task
1982 --!param taskType The handyman task type: repairing, watering, cleaning
1983 --!return Priority of task
1984 function Hospital:getHandymanTaskPriority(taskIndex, taskType)
1985 local subTable = self:findHandymanTaskSubtable(taskType)
1986 return subTable[taskIndex].priority
1987 end
1988
1989 function Hospital:modifyHandymanTaskPriority(taskIndex, newPriority, taskType)
1990 if taskIndex ~= -1 then
1991 local subTable = self:findHandymanTaskSubtable(taskType)
1992 subTable[taskIndex].priority = newPriority
1993 end
1994 end
1995
1996 function Hospital:removeHandymanTask(taskIndex, taskType)
1997 if taskIndex ~= -1 then
1998 local subTable = self:findHandymanTaskSubtable(taskType)
1999 local task = subTable[taskIndex]
2000 table.remove(subTable, taskIndex)
2001 if task.assignedHandyman then
2002 if task.object.ticks ~= true then
2003 task.assignedHandyman:releaseHandymanFromTask(true)
2004 task.assignedHandyman = nil
2005 end
2006 end
2007 end
2008 end
2009
2010 function Hospital:findHandymanTaskSubtable(taskType)
2011 for i = 1, #self.handymanTasks do
2012 if self.handymanTasks[i].taskType == taskType then
2013 return self.handymanTasks[i].subTable
2014 end
2015 end
2016 table.insert(self.handymanTasks, {["taskType"] = taskType, ["subTable"] = {}})
2017 return self:findHandymanTaskSubtable(taskType)
2018 end
2019
2020 --! Search all tasks assigned to a handyman, if any.
2021 --!param handyman The handyman instance to check for assigned tasks.
2022 --!return table of all assigned tasks.
2023 function Hospital:findAssignedTasksToHandyman(handyman)
2024 local assigned_tasks = {}
2025 for i = 1, #self.handymanTasks do
2026 for j = 1, #self.handymanTasks[i].subTable do
2027 if self.handymanTasks[i].subTable[j].assignedHandyman == handyman then
2028 table.insert(assigned_tasks, self.handymanTasks[i].subTable[j])
2029 end
2030 end
2031 end
2032 return assigned_tasks
2033 end
2034
2035 function Hospital:assignHandymanToTask(handyman, task_index, task_type)
2036 if task_index ~= -1 then
2037 local subtable = self:findHandymanTaskSubtable(task_type)
2038 local task_object = subtable[task_index]
2039 local former_handyman = task_object.assignedHandyman
2040 if former_handyman then
2041 former_handyman:releaseHandymanFromTask(true)
2042 end
2043 handyman.task = task_object
2044 task_object.assignedHandyman = handyman
2045 return task_object
2046 end
2047 return nil
2048 end
2049
2050 --! Function for search a new task for a handyman.
2051 --!param handyman (object) handyman instance for which we want to find a task.
2052 --!param task_type (string) handyman task type: repairing, watering, cleaning.
2053 --!return index (int) index of the found task.
2054 function Hospital:searchForHandymanTask(handyman, task_type)
2055 local subTable = self:findHandymanTaskSubtable(task_type)
2056
2057 -- if a distance is smaller than this value stop the search to
2058 -- save performance
2059 local thresholdForStopping = 3
2060
2061 -- information about the best task found so far
2062 local dist = 0
2063 local index = -1
2064 local priority = 0
2065 local multiplier = 1
2066 local first_attempt = true
2067
2068 if handyman.profile.is_consultant then
2069 multiplier = 0.5
2070 elseif handyman.profile.is_junior then
2071 multiplier = 2
2072 end
2073 if not handyman.parcelNr then
2074 handyman.parcelNr = 0
2075 end
2076 for task_index, task_candidate in ipairs(subTable) do
2077 local v = task_candidate
2078 local distance = self.world:getPathDistance(v.tile_x, v.tile_y, handyman.tile_x, handyman.tile_y)
2079 local found_suitable_task = true
2080 if not first_attempt and v.priority < priority then
2081 found_suitable_task = false
2082 end
2083 if not v.parcelId then
2084 v.parcelId = self.world.map.th:getCellFlags(v.tile_x, v.tile_y).parcelId
2085 end
2086 -- Check that the task is in the plot to which the handyman is assigned to. If he assigned to plot.
2087 if handyman.parcelNr ~= 0 and handyman.parcelNr ~= v.parcelId then
2088 found_suitable_task = false
2089 end
2090 -- Check that a route can be built to this task
2091 if distance == false then
2092 found_suitable_task = false
2093 end
2094
2095 if found_suitable_task then
2096 -- Handymen can take over other handymen tasks. If there any handyman that goes to water
2097 -- a plant in the other side of the hospital and later a second handyman near that plant becomes
2098 -- available for a new task and also chooses task to water that plant, then that second handyman
2099 -- will take away this task from first handymen to himself. The first handymen will be released
2100 -- from this task.
2101 if v.assignedHandyman then
2102 -- Another handyman is already assigned to this task
2103 -- Let's check if we can take this task away from him.
2104 if v.assignedHandyman.fired then
2105 v.assignedHandyman:unassignTask()
2106 elseif not v.assignedHandyman.hospital then
2107 -- This should normally never be the case. If the handyman doesn't belong to a hsopital
2108 -- then they should not have any tasks assigned to them however it was previously possible
2109 -- We need to tidy up to make sure the task can be reassigned.
2110 print("Warning: Orphaned handyman is still assigned a task. Removing.")
2111 v.assignedHandyman:unassignTask()
2112 else
2113 -- Check if handyman are closer to the task than the assigned handyman.
2114 local assignedDistance = self.world:getPathDistance(v.tile_x, v.tile_y, v.assignedHandyman.tile_x, v.assignedHandyman.tile_y)
2115 if assignedDistance ~= false then
2116 if v.assignedHandyman.profile.is_consultant then
2117 assignedDistance = assignedDistance / 2
2118 elseif v.assignedHandyman.profile.is_junior then
2119 assignedDistance = assignedDistance * 2
2120 end
2121 distance = distance * multiplier
2122 if distance + 5 > assignedDistance then
2123 found_suitable_task = false
2124 else
2125 distance = distance / multiplier
2126 end
2127 elseif task_type == "repairing" and v.assignedHandyman:getRoom() == self.world:getRoom(v.tile_x, v.tile_y) then
2128 -- Don't take repair task from another handyman if that assigned handyman already in the target room.
2129 found_suitable_task = false
2130 end
2131 end
2132 end
2133
2134 if found_suitable_task then
2135 if first_attempt then
2136 if distance <= thresholdForStopping then
2137 return task_index
2138 end
2139 first_attempt, dist, index, priority = false, distance, task_index, v.priority
2140 elseif priority < v.priority or distance < dist then
2141 if distance < thresholdForStopping then
2142 return task_index
2143 end
2144 dist, index, priority = distance, task_index, v.priority
2145 end
2146 end
2147 end
2148
2149 end
2150 return index
2151 end
2152
2153 --! Find a handyman task by task type, position, and possibly the used object.
2154 --!param x (int) The X coordinate of the position.
2155 --!param y (int) The Y coordinate of the position.
2156 --!param taskType Type of the task.
2157 --!param obj (Object) If specified, the object used for doing the task.
2158 --! Since multiple litter objects may exist at the same tile, the object must be given when cleaning.
2159 function Hospital:getIndexOfTask(x, y, taskType, obj)
2160 local subTable = self:findHandymanTaskSubtable(taskType)
2161 for i, v in ipairs(subTable) do
2162 if v.tile_x == x and v.tile_y == y and (obj == nil or v.object == obj) then
2163 return i
2164 end
2165 end
2166 return -1
2167 end
2168
2169 --! Afterload function to initialize the owned plots.
2170 function Hospital:initOwnedPlots()
2171 self.ownedPlots = {}
2172 for _, v in ipairs(self.world.entities) do
2173 if v.tile_x and v.tile_y then
2174 local parcel = self.world.map.th:getCellFlags(v.tile_x, v.tile_y).parcelId
2175 local isAlreadyContained = false
2176 for _, v2 in ipairs(self.ownedPlots) do
2177 if parcel == v2 then
2178 isAlreadyContained = true
2179 break
2180 end
2181 end
2182 if isAlreadyContained == false and parcel ~= 0 and self.world.map.th:getPlotOwner(parcel) ~= 0 then
2183 table.insert(self.ownedPlots, parcel)
2184 end
2185 end
2186 end
2187 end
2188
2189 --! Function that returns true if the room for the given disease
2190 --! has not been researched yet.
2191 --!param disease (string): the disease to be checked.
2192 function Hospital:roomNotYetResearched(disease)
2193 local req = self:checkDiseaseRequirements(disease)
2194 if type(req) == "table" and #req.rooms > 0 then
2195 for _, room_id in ipairs(req.rooms) do
2196 if not self:isRoomDiscovered(room_id) then return true end
2197 end
2198 end
2199 return false
2200 end
2201
2202 --! Function that returns true if concentrating research on the disease is possible.
2203 --! @param disease (string): the disease to be checked.
2204 function Hospital:canConcentrateResearch(disease)
2205 local book = self.disease_casebook
2206 if not book[disease].pseudo and self:roomNotYetResearched(disease) then
2207 return true
2208 end
2209 if book[disease].drug then
2210 return book[disease].cure_effectiveness < 100
2211 end
2212 local room
2213 if book[disease].pseudo then
2214 room = book[disease].disease.id:sub(6)
2215 else
2216 room = book[disease].disease.treatment_rooms[#book[disease].disease.treatment_rooms]
2217 end
2218 local research_progress = self.research.research_progress
2219 local object_type
2220 for obj, _ in pairs(self.world.available_rooms[room].objects_needed) do
2221 if self.world.object_types[obj].default_strength then
2222 object_type = obj
2223 break
2224 end
2225 end
2226
2227 if object_type then
2228 local progress = research_progress[self.world.object_types[object_type]]
2229 return progress.start_strength < self.world.map.level_config.gbv.MaxObjectStrength
2230 end
2231 return false
2232 end
2233
2234 --! Change patient happiness and hospital reputation based on price distortion.
2235 --! The patient happiness is adjusted proportionally. The hospital reputation
2236 --! can only be affected when the distortion level reaches some threshold.
2237 --!param patient (patient) The patient paying the bill. His/her happiness level
2238 --! is adjusted.
2239 --!param casebook (object) Disease casebook entry. It's used to display the
2240 --! localised disease name when Adviser tells the warning message.
2241 function Hospital:computePriceLevelImpact(patient, casebook)
2242 local price_distortion = patient:getPriceDistortion(casebook)
2243 patient:changeAttribute("happiness", -(price_distortion / 2))
2244 if price_distortion < self.under_priced_threshold then
2245 if math.random(1, 100) == 1 then
2246 if casebook.price < 1 then
2247 self:advisePriceLevelImpact("under", casebook.disease.name)
2248 end
2249 self:changeReputation("under_priced")
2250 end
2251 elseif price_distortion > self.over_priced_threshold then
2252 if math.random(1, 100) == 1 then
2253 self:advisePriceLevelImpact("over", casebook.disease.name)
2254 self:changeReputation("over_priced")
2255 end
2256 elseif math.abs(price_distortion) <= 0.15 and math.random(1, 200) == 1 then
2257 -- When prices are well adjusted (i.e. abs(price distortion) <= 0.15)
2258 self:advisePriceLevelImpact("fair", casebook.disease.name)
2259 end
2260 end
2261
2262 --! Notify patients of a change to hospital staff members
2263 --!param staff (Staff) Changed staff member subject of notification
2264 function Hospital:notifyOfStaffChange(staff)
2265 for _, patient in pairs(self.patients) do
2266 patient:notifyOfStaffChange(staff)
2267 end
2268 end
2269
2270 --! Change the hospital value by an amount independent of a cost being incurred
2271 --!param changeValue (int) The amount the hospital value should change by
2272 function Hospital:changeValue(changeValue)
2273 self.value = self.value + changeValue
2274 end
2275
2276 --! Collect the hospital level settings relevant for the next hospital
2277 --!return campaign_data (table) Hospital campaign data
2278 function Hospital:getCampaignData()
2279 local campaign_data = {
2280 player_salary = self.player_salary,
2281 message_popup = self.message_popup,
2282 handyman_popup = self.handyman_popup,
2283 hospital_littered = self.hospital_littered,
2284 has_seen_pay_rise = self.has_seen_pay_rise,
2285 policies = self.policies,
2286 }
2287 return campaign_data
2288 end
2289
2290 --! Restore the hospital settings from the previous hospital
2291 --!param campaign_data (table) Hospital campaign data
2292 function Hospital:setCampaignData(campaign_data)
2293 for key, value in pairs(campaign_data) do
2294 self[key] = value
2295 end
2296 end
2297
2298 --! Finds a random room with significantly long queues
2299 --!return room or nil The chosen room in the hospital or nil for no room busy enough
2300 function Hospital:getRandomBusyRoom()
2301 local long_queue_rooms, active_rooms, total_queue = {}, 0, 0
2302 for _, room in pairs(self.world.rooms) do
2303 if room.is_active and room.door.queue then
2304 total_queue = total_queue + #room.door.queue
2305 active_rooms = active_rooms + 1
2306 if #room.door.queue > 7 then
2307 long_queue_rooms[#long_queue_rooms + 1] = room
2308 end
2309 end
2310 end
2311 if #long_queue_rooms == 0 then return end
2312
2313 local busy_threshold = 1.5 * total_queue / active_rooms
2314 local chosen_room = long_queue_rooms[math.random(1, #long_queue_rooms)]
2315 if #chosen_room.door.queue >= busy_threshold then return chosen_room end
2316 end
2317
2318 --! Open the hospital
2319 function Hospital:open()
2320 self.opened = true
2321 end
2322
2323 --! Check if the hospital is ready to accept patients
2324 function Hospital:canAcceptPatients()
2325 return self.opened and self:hasReceptionDesk(true)
2326 end
2327
2328 --! Has this hospital received any patients yet?
2329 function Hospital:hadPatients()
2330 return self.num_visitors > 0
2331 end
2332
2333 --! Reset the death counts. This is used by a cheat to reset key lose conditions.
2334 function Hospital:resetDeathCount()
2335 self.num_deaths = 0
2336 self.num_deaths_this_year = 0
2337 self.statistics.deaths = 0
2338 end
2339
2340 ---- Stubs section - these functions have nothing to do here, are overridden in a derived class.
2341
2342 --! Give advice to the user about the need to buy the first reception desk.
2343 function Hospital:msgNeedFirstReceptionDesk()
2344 end
2345
2346 --! Give advice to the user about having bought a reception desk.
2347 function Hospital:msgReceptionDesk()
2348 end
2349
2350 --! Give advice about having more desks.
2351 function Hospital:msgMultiReceptionDesks()
2352 end
2353
2354 --! Give advice to the user about maintenance of plants.
2355 function Hospital:advisePlants()
2356 end
2357
2358 --! Show the 'Gates to hell' animation.
2359 function Hospital:showGatesToHell(entity)
2360 end
2361
2362 --! Advises the player.
2363 function Hospital:giveAdvice(msgs, rnd_frac, stay_up)
2364 end
2365
2366 --! Give the user possibly a message about a cured patient.
2367 function Hospital:msgCured()
2368 end
2369
2370 --! Give the user possibly a message about a dead patient.
2371 function Hospital:msgKilled()
2372 end
2373
2374 function Hospital:adviseDiscoverDisease(disease)
2375 end
2376
2377 --! Select a relevant message to be displayed to the user
2378 function Hospital:adviseBoilerBreakdown()
2379 end
2380
2381 --! Announces a machine needing repair
2382 function Hospital:announceRepair(room)
2383 end
2384
2385 function Hospital:onSpawnVIP()
2386 end
2387
2388 --! Give visual warning that player doesn't have enough $ to build
2389 function Hospital:adviseCannotAffordPlot()
2390 end
2391
2392 --! Tell the player, through the advisor, about the impact of casebook prices
2393 function Hospital:advisePriceLevelImpact(judgment, name)
2394 end
2395
2396 --! Makes the raise request for a staff member
2397 function Hospital:makeRaiseRequest(amount, staff)
2398 end
2399
2400 --! Announce to the player that a staff member is leaving the hospital
2401 function Hospital:announceStaffLeave(staff)
2402 end
2403
2404 --! Makes the fax requesting player action for the patient who needs a diagnosis room
2405 function Hospital:makeNoTreatmentRoomFax(patient)
2406 end
2407
2408 --! Makes the fax requesting player action for the patient who needs a diagnosis room
2409 function Hospital:makeNoDiagnosisRoomFax(patient)
2410 end
2411
2412 --! Makes the fax at the start of an emergency
2413 function Hospital:makeEmergencyStartFax()
2414 end
2415
2416 --! Makes the fax at the end of an emergency
2417 function Hospital:makeEmergencyEndFax(rescued_patients, total, max_bonus, earned)
2418 end
2419
2420 --! Makes the fax which may spawn a VIP
2421 function Hospital:createVip()
2422 end
2423
2424 --! Remove any message (fax) relating to this humanoid
2425 function Hospital:removeMessage(humanoid)
2426 end
2427
2428 --! Called when the vip is out of the hospital grounds
2429 function Hospital:makeVipEndFax(vip_rating, name, cash_reward, vip_message)
2430 end
2431
2432 --! Play a sound file
2433 function Hospital:playSound(sound)
2434 end
2435
2436 --! The UI parts of earthquake ticks
2437 function Hospital:tickEarthquake(stage)
2438 end
2439
2440 --! Give advice that a patient is waiting for the player to build a GP's office
2441 function Hospital:adviseNoGPOffice()
2442 end