File size: 20,030 Bytes
d7786d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
/* Trusted environment controller for the one-tile start.

   It applies the scenario configuration (onetile-config.js is concatenated ahead
   of this file, so CONFIG and applyOneTileConfig are already defined), records
   evidence, draws the objective panel, and blocks cheats and any direct editing
   of land rights once the clock starts.

   The run is three attempts, not one: a park that closes down can be started
   again from a pristine copy, and the in-game days every attempt burned are
   added up. That keeps a restart honest -- it costs exactly the time it cost --
   so the ledger of attempts lives in shared storage, which survives the park
   being reloaded, rather than in the park save.

   No gameplay help, no screenshot or model hooks. The only thing scored is
   whether the engine settles the objective, and how much in-game time had passed
   across every attempt when it did, so both clocks are stamped on every record. */
registerPlugin({name:"onetile-controller",version:"1.0.0",authors:["Task environment"],type:"local",licence:"MIT",targetApiVersion:122,main:function(){
 // The target is in the marker: a save from the 1,000-guest variant cannot be
 // handed to the calibrated task's grader and pass as its completion.
 var ORIGIN="onetile-v1-"+CONFIG.objective.guests+"guests-001";
 var TARGET_GUESTS=CONFIG.objective.guests;
 // Days at a rating below 700 the engine allows before it closes the park down
 // (obj.cpp, CheckGuestsAndRating). Panel copy only; the engine owns the rule.
 var RATING_GRACE_DAYS=29;
 // Attempts allowed in one run. The supervisor compiles the number in ahead of
 // this file, the same way the guest target arrives; a missing value would be a
 // broken install, so it is reported rather than defaulted away.
 var ATTEMPTS_ALLOWED=typeof ONETILE_ATTEMPTS_ALLOWED==="number"?ONETILE_ATTEMPTS_ALLOWED:0;
 var store=context.getParkStorage("onetile-v1");
 // Park storage dies with the park, and a restart loads a different park: the
 // attempt ledger has to outlive both, so it goes in shared storage.
 var LEDGER="onetile-v1.attempts";
 var attempt=0,priorDays=0;
 var initialized=false,configuring=false,applying=false,started=0,lastTime=0,elapsed=0,panel=null;
 var startTicks=0,inGameDays=0,lastDay=-1,lastMonth=-1;
 var peakGuests=0,peakRating=0,peakOwned=0,peakCash=0;
 var tiles={owned:0,forSale:0},days=[],outcome=null,blocked=0,finalSaved=false,baseline=null;

 function emit(x){x.schema=1;x.elapsed=Math.round(elapsed);x.parkOrigin=store.get("origin","");console.log("T39JSON "+JSON.stringify(x));}
 function note(text){park.postMessage({type:"blank",text:text});emit({kind:"notice",text:text});}
 function money(v){return context.formatString("{CURRENCY}",v);}
 function guestsInPark(){return park.guests;}

 // ---- the attempt ledger -------------------------------------------------
 // One entry per attempt, in order, each carrying the in-game days that attempt
 // burned. Written every in-game day so a crash cannot make a spent attempt look
 // free, and read back by a restarted park to find out which attempt it is.
 function ledger(){var l=context.sharedStorage.get(LEDGER,[]);return l&&l.length!==undefined?l:[];}
 function daysBefore(l,upto){var t=0;for(var i=0;i<upto&&i<l.length;i++)t+=l[i].inGameDays||0;return t;}
 function totalDays(){return priorDays+inGameDays;}
 function recordAttempt(result){
  var l=ledger();
  if(!l[attempt-1])l[attempt-1]={attempt:attempt,target:TARGET_GUESTS};
  l[attempt-1].inGameDays=inGameDays;l[attempt-1].result=result;
  context.sharedStorage.set(LEDGER,l);
 }
 function attemptsLeft(){return ATTEMPTS_ALLOWED-attempt;}
 // The save the next attempt is taken from. Short names, because the load dialog
 // truncates its name column at seven characters -- run-supervisor.py lays these
 // down under the same names and explains why.
 function restartFile(n){return (n===2?"2nd":n===3?"3rd":n+"th")+"-try.park";}

 // 2,500 surfaces is too much to walk every tick, so the count is refreshed on
 // the five-second reporting interval and read from the cache in between.
 function refreshTiles(){tiles=countOwnedTiles();
  if(tiles.owned>peakOwned)peakOwned=tiles.owned;
  return tiles;}

 function snapshot(kind){
  var rides=map.rides.filter(function(r){return r.classification==="ride";});
  var shops=map.rides.filter(function(r){return r.classification!=="ride";});
  return {kind:kind,elapsed:Math.round(elapsed),
   scenarioStatus:scenario.status,
   objectiveType:scenario.objective.type,objectiveGuests:scenario.objective.guests,
   guests:guestsInPark(),targetGuests:TARGET_GUESTS,peakGuests:peakGuests,
   rating:park.rating,peakRating:peakRating,
   ratingWarningDays:scenario.parkRatingWarningDays,ratingGraceDays:RATING_GRACE_DAYS,
   ownedTiles:tiles.owned,tilesForSale:tiles.forSale,peakOwnedTiles:peakOwned,parkSize:park.parkSize,
   cash:park.cash,peakCash:peakCash,loan:park.bankLoan,maxLoan:park.maxBankLoan,
   landPrice:park.landPrice,entranceFee:park.entranceFee,
   parkOpen:park.getFlag("open"),freeParkEntry:park.getFlag("freeParkEntry"),
   // Which attempt this is, and the time the earlier ones already spent: the
   // ranked figure is the total, not this attempt's share of it.
   attempt:attempt,attemptsAllowed:ATTEMPTS_ALLOWED,
   priorInGameDays:priorDays,totalInGameDays:totalDays(),
   // Both clocks, on every record: the reward is binary, the ranking is time.
   inGameDays:inGameDays,inGameTicks:date.ticksElapsed-startTicks,
   monthsElapsed:date.monthsElapsed,day:date.day,month:date.month,year:date.year,
   openRides:rides.filter(function(r){return r.status==="open";}).length,
   openShops:shops.filter(function(r){return r.status==="open";}).length,
   totalCustomers:rides.concat(shops).reduce(function(a,r){return a+r.totalCustomers;},0),
   blockedActions:blocked,
   rides:rides.map(function(r){return {id:r.id,name:r.name,type:r.type,status:r.status,excitement:r.excitement,intensity:r.intensity,totalCustomers:r.totalCustomers,totalProfit:r.totalProfit};}),
   shops:shops.map(function(r){return {id:r.id,name:r.name,type:r.type,status:r.status,totalCustomers:r.totalCustomers};})};
 }

 function recordOutcome(){
  if(outcome)return;
  if(scenario.status!=="completed"&&scenario.status!=="failed")return;
  refreshTiles();
  outcome={result:scenario.status==="completed"?"completed":"failed",
   // The speed metric. In-game days across every attempt are the ranked figure;
   // inGameDays is this attempt's share, ticks are the same clock at full
   // resolution, and the wall clock is a diagnostic only.
   attempt:attempt,attemptsAllowed:ATTEMPTS_ALLOWED,
   totalInGameDays:totalDays(),priorInGameDays:priorDays,
   inGameDays:inGameDays,inGameTicks:date.ticksElapsed-startTicks,
   monthsElapsed:date.monthsElapsed,day:date.day,month:date.month,year:date.year,
   wallClockSeconds:Math.round(elapsed),
   guests:guestsInPark(),peakGuests:peakGuests,rating:park.rating,
   ownedTiles:tiles.owned,cash:park.cash,targetGuests:TARGET_GUESTS};
  store.set("outcome",outcome);
  recordAttempt(outcome.result);
  emit({kind:outcome.result==="completed"?"objective_complete":"objective_failed",
        outcome:outcome,attempts:ledger(),state:snapshot("outcome_state")});
  note(outcome.result==="completed"
   ?"OBJECTIVE COMPLETE: "+outcome.guests+" guests in the park at a rating of "
     +outcome.rating+", on year "+outcome.year+" month "+(outcome.month+1)+" day "+outcome.day
     +" ("+outcome.totalInGameDays+" in-game days over "+attempt+" attempt"
     +(attempt===1?"":"s")+"). The run is over."
   :"OBJECTIVE FAILED: the park rating stayed under 700 for "+RATING_GRACE_DAYS
     +" days and the park has been closed down. "
     +(attemptsLeft()>0
       ?"You have "+attemptsLeft()+" attempt"+(attemptsLeft()===1?"":"s")+" left: open the"
        +" floppy-disk icon at the top left of the toolbar, choose Load Game, and load"
        +" "+restartFile(attempt+1)+" to start"
        +" attempt "+(attempt+1)+" on a fresh park. The "+totalDays()+" in-game days spent so"
        +" far still count towards your time."
       :"That was attempt "+attempt+" of "+ATTEMPTS_ALLOWED+" and the run is over."
        +" Save your park for review."));
  // Trusted proof of how the run ended, taken at the moment it settled: the
  // finest autosave interval the engine offers is five minutes and would miss it.
  // One file per attempt, so a later attempt cannot overwrite the evidence of an
  // earlier one and the verifier can still take the newest.
  if(!finalSaved){
   finalSaved=true;
   try{context.saveGame({filename:"t39-final-attempt"+attempt});}
   catch(e){emit({kind:"final_save_failed",message:String(e)});}
  }
 }

 function updatePanel(){
  if(typeof ui==="undefined")return;
  var s=snapshot("panel_state");
  if(!panel){panel=ui.openWindow({classification:"onetile-progress",title:"One Tile objective",
    x:890,y:42,width:380,height:158,widgets:[
    {type:"label",name:"guests",x:10,y:23,width:360,height:16,text:""},
    {type:"label",name:"rating",x:10,y:42,width:360,height:16,text:""},
    {type:"label",name:"land",x:10,y:61,width:360,height:16,text:""},
    {type:"label",name:"clock",x:10,y:80,width:360,height:16,text:""},
    {type:"label",name:"attempt",x:10,y:99,width:360,height:16,text:""},
    {type:"label",name:"status",x:10,y:120,width:360,height:23,text:""}],onClose:function(){panel=null;}});}
  panel.findWidget("guests").text="Guests in park "+s.guests+" / "+TARGET_GUESTS+"  (peak "+s.peakGuests+")";
  panel.findWidget("rating").text="Rating "+s.rating+" (need 700)"
   +(s.ratingWarningDays>0?"; "+s.ratingWarningDays+" of "+RATING_GRACE_DAYS+" days under 700":"");
  panel.findWidget("land").text="Owned tiles "+s.ownedTiles+"; "+s.tilesForSale
   +" for sale at "+money(s.landPrice)+"; cash "+money(s.cash);
  panel.findWidget("clock").text="Year "+s.year+", month "+(s.month+1)+" of 8, day "+s.day
   +"; "+s.inGameDays+" in-game days this attempt";
  panel.findWidget("attempt").text="Attempt "+s.attempt+" of "+ATTEMPTS_ALLOWED
   +"; "+s.totalInGameDays+" in-game days in total (your score)"
   +(s.attempt>ATTEMPTS_ALLOWED?" - over the limit, nothing here is scored":"");
  panel.findWidget("status").text=s.scenarioStatus==="completed"?"OBJECTIVE COMPLETE - the run is over"
   :s.scenarioStatus==="failed"
    ?(attemptsLeft()>0?"OBJECTIVE FAILED - load "+restartFile(attempt+1)+" to start attempt "+(attempt+1)
                      :"OBJECTIVE FAILED - park closed down, no attempts left")
   :started?"Running. There is no deadline; your time is your score."
   :"Unpause to start. Faster is better.";
 }

 function initialize(){
  if(configuring)return;
  configuring=true;
  // Deliberately not paused yet. interval.tick only fires while the game is
  // running, so this is reached unpaused -- and it has to stay that way: the
  // land actions are queued and executed by the tick loop, so pausing here
  // would hang the configuration waiting on callbacks that never come. The
  // handful of ticks it costs happen before the clock starts and are not
  // counted. The pause is set once the last callback has landed.
  //
  // The configuration resizes the map and paints land rights, which are exactly
  // the actions blocked below: the guard tells the hook these are the
  // environment's own, and it is lowered before the agent has a park to touch.
  applying=true;
  applyOneTileConfig(function(start){
   if(start===null){
    applying=false;
    emit({kind:"controller_error",message:"Scenario configuration failed: no park entrance found"});
    return;
   }
   // The land actions are queued; give the engine a tick to settle them before
   // the baseline is measured and handed to the grader as the starting state.
   context.setTimeout(function(){
    applying=false;
    refreshTiles();
    peakGuests=guestsInPark();peakRating=park.rating;peakCash=park.cash;
    baseline=configSummary();
    baseline.startTile=start;
    // The objective type disables the park window's open/close control (see
    // onetile-config.js, CONFIG.parkOpen), so a park that is closed here can
    // never be opened by the agent and the run is unwinnable. That is an
    // environment failure, and the grader treats controller_error as one.
    if(!baseline.parkOpen){
     emit({kind:"controller_error",message:"Scenario configuration failed: the park is closed and this objective type gives the agent no way to open it",baseline:baseline});
     return;
    }
    // Without an allowance the attempt ledger has no meaning and neither does
    // the total the run is ranked on, so it is an install failure, not a zero.
    if(ATTEMPTS_ALLOWED<1){
     emit({kind:"controller_error",message:"Scenario configuration failed: ONETILE_ATTEMPTS_ALLOWED was not compiled into the plugin",baseline:baseline});
     return;
    }
    initialized=true;
    // A fresh park means a fresh attempt: this is either the hand-over or a
    // restart the agent chose, and the ledger is what tells the two apart.
    var l=ledger();
    attempt=l.length+1;priorDays=daysBefore(l,l.length);
    l.push({attempt:attempt,inGameDays:0,result:"running",target:TARGET_GUESTS});
    context.sharedStorage.set(LEDGER,l);
    baseline.attempt=attempt;baseline.attemptsAllowed=ATTEMPTS_ALLOWED;
    baseline.priorInGameDays=priorDays;
    store.set("initialized",true);store.set("origin",ORIGIN);
    store.set("baseline",baseline);
    lastDay=date.day;lastMonth=date.monthsElapsed;startTicks=date.ticksElapsed;
    if(attempt>ATTEMPTS_ALLOWED){
     // The park is left playable rather than taken away -- there is no API to
     // unload it -- but the run is over and the grader will not credit this.
     emit({kind:"attempt_limit_exceeded",attempt:attempt,attemptsAllowed:ATTEMPTS_ALLOWED,
           priorInGameDays:priorDays});
     note("OVER THE LIMIT: this is attempt "+attempt+" of "+ATTEMPTS_ALLOWED+" allowed. The run"
       +" ended with the last one; nothing you do on this park is scored.");
    }else if(attempt>1){
     note("ATTEMPT "+attempt+" of "+ATTEMPTS_ALLOWED+": a fresh park, and the "+priorDays
       +" in-game days the earlier attempt"+(attempt>2?"s":"")+" spent still count towards your"
       +" time. Unpause to start it.");
    }
    note("HANDOVER: One Tile. You own "+tiles.owned+" tile of a "+baseline.playable+"x"
      +baseline.playable+" map; the other "+tiles.forSale+" are for sale at "+money(park.landPrice)
      +" each. Get "+TARGET_GUESTS+" guests into the park at a rating of 700 or more.");
    note("OPERATIONS: cash "+money(park.cash)+", and no loan is available. The park is open"
      +" and admission is free: set a price on the park window's ticket tab, and switch off"
      +" research funding in Finances, which costs $200 a month. There is no deadline, but"
      +" how much in-game time you take is your score, so do it fast.");
    note("WARNING: an empty park rates 500. After the first month, every day under a rating of"
      +" 700 counts, and on day "+RATING_GRACE_DAYS+" the park is closed down and the attempt is"
      +" over. Any day at 700 or more resets the count.");
    note("ATTEMPTS: you have "+ATTEMPTS_ALLOWED+" in all. If a park is closed down, load"
      +" 2nd-try.park or 3rd-try.park via the floppy-disk icon at the top left (Load Game) to"
      +" start the next one. Every attempt's in-game days are added up, so a restart costs you"
      +" the time it cost. Loading any other save is not a restart and voids the run.");
    emit({kind:"onetile_initialized",target:TARGET_GUESTS,baseline:baseline,state:snapshot("baseline_state")});
    updatePanel();
    context.paused=true;
   },20);
  });
 }

 context.subscribe("interval.tick",function(){
  if(!initialized){
   if(store.get("initialized",false)){
    // A park that was already played: the configuration is baked into the save,
    // so it is never applied twice. A restart loads a pristine copy and goes the
    // other way, through initialize(), so this is the verifier's path, a
    // restarted engine -- or an agent rewinding to a played save, which is not a
    // restart and which the grader refuses. Recorded either way.
    initialized=true;elapsed=store.get("elapsed",0);baseline=store.get("baseline",null);
    outcome=store.get("outcome",null);inGameDays=store.get("inGameDays",0);
    var back=ledger();attempt=back.length||1;priorDays=daysBefore(back,attempt-1);
    started=Date.now();lastTime=started;startTicks=store.get("startTicks",date.ticksElapsed);
    lastDay=date.day;lastMonth=date.monthsElapsed;refreshTiles();
    emit({kind:"onetile_reloaded",state:snapshot("reload_state")});
   }else initialize();
   return;
  }
  if(!started){
   started=Date.now();lastTime=started;startTicks=date.ticksElapsed;
   store.set("startTicks",startTicks);
   emit({kind:"clock_started",state:snapshot("start_state")});
   note("Started. Pause and fast-forward are both yours: only in-game time is scored.");
  }
  var current=guestsInPark();
  if(current>peakGuests)peakGuests=current;
  if(park.rating>peakRating)peakRating=park.rating;
  if(park.cash>peakCash)peakCash=park.cash;
  if(date.day!==lastDay||date.monthsElapsed!==lastMonth){
   inGameDays++;store.set("inGameDays",inGameDays);
   // The ledger is the score's memory: written every in-game day so that a
   // crash, a quit or a restart cannot make a spent attempt look free.
   recordAttempt("running");
   refreshTiles();
   var record={kind:"onetile_day",inGameDays:inGameDays,monthsElapsed:date.monthsElapsed,
    attempt:attempt,totalInGameDays:totalDays(),
    day:date.day,month:date.month,year:date.year,
    guests:current,peakGuests:peakGuests,rating:park.rating,
    ratingWarningDays:scenario.parkRatingWarningDays,
    ownedTiles:tiles.owned,cash:park.cash,parkOpen:park.getFlag("open"),
    entranceFee:park.entranceFee};
   days.push(record);if(days.length>64)days.shift();
   store.set("days",days);emit(record);
   lastDay=date.day;lastMonth=date.monthsElapsed;
  }
  recordOutcome();
 });

 context.setInterval(function(){
  if(!initialized)return;
  if(started){var now=Date.now();elapsed+=(now-lastTime)/1000;lastTime=now;store.set("elapsed",elapsed);}
  refreshTiles();recordOutcome();updatePanel();
  var state=snapshot("onetile_state");state.outcome=outcome;state.days=days.length;emit(state);
 },5000);

 context.subscribe("map.save",function(){recordOutcome();var s=snapshot("onetile_save");s.outcome=outcome;emit(s);});
 context.subscribe("action.query",function(e){
  // The environment's own configuration runs through these same actions, before
  // the agent has anything to click on; only what comes after it is blocked.
  if(applying)return;
  // landsetrights is the editor's own land-rights brush: it grants ownership
  // outright instead of buying it, which is the whole task. The configuration
  // above sets ownership by assigning cheats.sandboxMode directly rather than
  // through an action, so it is not affected by this hook.
  // Two things are deliberately NOT here. Pausing: the score is in-game time,
  // so stopping the clock to think costs the agent the only thing measured, and
  // blocking it only bought wall-clock panic. Loading a park: that is how a
  // restart is taken, and the attempt ledger charges it the time it cost, so it
  // is counted rather than forbidden -- a rewind to a played save shows up as
  // onetile_reloaded and the grader refuses the run.
  var forbidden=["cheatset","parksetdate","ridefreezerating","scenariosetsetting",
                 "tilemodify","landsetrights","mapchangesize"];
  if(forbidden.indexOf(e.action)>=0){
   e.result.error=1;e.result.errorTitle="Task rules";
   e.result.errorMessage="Cheats, land grants and re-dating are disabled. Pause, fast-forward and the three attempts are yours.";
   blocked++;emit({kind:"blocked_action",action:e.action});
  }
 });
 context.subscribe("action.execute",function(e){emit({kind:"action",action:e.action,args:e.args,result:e.result});});
}});