JSFiddle - React, Tailwind, and code Playground

by Eugene Vilder

JavaScript

class Airplane {
  constructor(planeNumber) {
    this.planeNumber = planeNumber;
    this.fuel = Math.floor(Math.random() * 900) + 100;  // liters
    this.fuelRate = 1;  // liters / frame tick
    this.crashed = false;
    this.isLanded = false;
    
    this.isLanding = false;
    this.startLandingFrame = 0;
    this.framesReqToLand = 80;
  }

  frameTick(frameNumber) {
    if (!this.crashed && !this.isLanded) {
      this.fuel -= this.fuelRate;

      if (this.fuel <= 0) {
        this.crashed = true;
        console.log(`Plane ${this.planeNumber} crashed on frame ${frameNumber}`);
      } else {
      
        if (this.isLanding && !this.isLanded) {
          if (this.startLandingFrame + this.framesReqToLand < frameNumber) {
            console.log(`Plane ${this.planeNumber} landed on frame ${frameNumber}`);
            this.isLanded = true;
            this.isLanding = false;
          }

        }
      }
    }
  }
}

class Simulation {
  constructor() {
    this.airplanes = [];
    this.frameNumber = 0;
    this.framerate = 60;  // frames per second
    this.landing = [];
    this.isSomePlaneLanding = false;
  }

  async mainLoop() {
    while (true) {
      this.frameNumber += 1;
      if (Math.floor(Math.random() * 100) == 0) {
        const nextPlaneNumber = this.airplanes.length + 1;
        const newAirplane = new Airplane(nextPlaneNumber);
        console.log(
          `Plane ${newAirplane.planeNumber} entered airspace with `
          + `${newAirplane.fuel} liters of fuel on frame ${this.frameNumber}`
        );
        this.airplanes.push(newAirplane);
      }

			const q = this.airplanes.sort((a, b)=>{
      	return a.fuel - b.fuel;
      }).filter(plane=>!plane.isLanded && !plane.isLanding && !this.crashed);
      
      if (!this.isSomePlaneLanding && q.length) {
      	const newAirplane = q[0];
        q[0].isLanding = true;
        q[0].startLandingFrame = this.frameNumber;
					console.log(
          `Plane ${newAirplane.planeNumber}...