Files

111 lines
2.6 KiB
GDScript

# Original exercise: commands own all resource changes; UI only requests commands.
extends RefCounted
var stock: int = 0
var coins: int = 0
var workers: int = 0
var capacity: int = 10
var heat: int = 0
var crafted: int = 0
var chapter: int = 0
var elapsed: float = 0.0
var cooling_elapsed: float = 0.0
func collect() -> bool:
if stock >= capacity:
return false
stock += 1
return true
func sell() -> bool:
if stock == 0:
return false
coins += stock
stock = 0
return true
func craft_cost() -> int:
return 6 + chapter * 2
func craft() -> bool:
if stock < craft_cost() or heat > 2:
return false
stock -= craft_cost()
coins += 9 + chapter * 4
heat += 2
crafted += 1
return true
func hire() -> bool:
if coins < 7 or workers >= 3:
return false
coins -= 7
workers += 1
return true
func expand() -> bool:
if coins < 4 or capacity >= 30:
return false
coins -= 4
capacity += 10
return true
func transform() -> bool:
if crafted < 3 or chapter >= 2:
return false
chapter += 1
crafted = 0
stock = 0
heat = 0
elapsed = 0.0
cooling_elapsed = 0.0
return true
func advance(delta: float) -> void:
# This lab has no offline progress. Clamp a frame stall rather than fast-forwarding.
if not is_finite(delta) or delta <= 0.0:
return
delta = minf(delta, 1.0)
elapsed += delta
cooling_elapsed += delta
while elapsed >= 1.0:
elapsed -= 1.0
stock = mini(capacity, stock + workers)
while cooling_elapsed >= 5.0:
cooling_elapsed -= 5.0
heat = maxi(0, heat - 1)
func snapshot() -> Dictionary:
return {"version": 1, "stock": stock, "coins": coins, "workers": workers,
"capacity": capacity, "heat": heat, "crafted": crafted, "chapter": chapter}
func restore(value: Variant) -> bool:
# Validate the complete payload before committing any field.
if not value is Dictionary or value.get("version") != 1:
return false
var bounds: Dictionary = {"stock": [0, 30], "coins": [0, 1000000],
"workers": [0, 3], "capacity": [10, 30], "heat": [0, 4],
"crafted": [0, 1000000], "chapter": [0, 2]}
for key in bounds:
if not value.has(key):
return false
var number: Variant = value[key]
if not (number is int or number is float):
return false
if not is_finite(float(number)) or float(number) != floor(float(number)):
return false
if number < bounds[key][0] or number > bounds[key][1]:
return false
if value.stock > value.capacity or int(value.capacity) % 10 != 0:
return false
stock = int(value.stock)
coins = int(value.coins)
workers = int(value.workers)
capacity = int(value.capacity)
heat = int(value.heat)
crafted = int(value.crafted)
chapter = int(value.chapter)
elapsed = 0.0
cooling_elapsed = 0.0
return true