Yarek T bio photo

Yarek T

Twitter

Computer loop

The main loop of Programming block programms isn’t ideal for writing large programs, as you can’t abstract implementation details into separate blocks because everything has to be called through the main method on update.

Since I discovered that method dispatch is sort of possible by using delegates:

void Main(string arg) {
	Action messageTarget = delegate() {
		Echo("Work within delegate");
	};
	messageTarget();
}

This code here is very experimental, and doesn’t really give any advantage to just putting code straight into the main method at the moment. The goal of this is to both separate init stage from runtime and to offer a mechanism for timer speed management. Another neccessity is to provide a state machine responding to stimuli from outside. None of this is possible really without wrappers for the loop and the storage mechanisms.

public class Computer {
    private bool runOnce = false;

    // Returns false once
    public bool init() {
        bool val = this.runOnce;
        this.runOnce = true;
        return val;
    }

    private IMyTimerBlock timerBlock;

    public void setTimer(IMyTimerBlock timerBlock) {
        this.timerBlock = timerBlock;
    }

    public void triggerNow() {
        this.timerBlock.GetActionWithName("TriggerNow").Apply(this.timerBlock);
    }

    public void loop() {

    }
}

And to use create it before the main method:

Computer computer = new Computer();
SpeedCalculator sc;
LCD lcd;
void Main(string arg)  
{
    if (! computer.init()) {
        IMyTimerBlock timerBlock = GridTerminalSystem.GetBlockWithName("Timer Block") as IMyTimerBlock;
        computer.setTimer(timerBlock);

        sc = new SpeedCalculator((IMyTerminalBlock)Me);
        lcd = new LCD(GridTerminalSystem, "LCD");
    }

    //computer.loop();

    SpeedCalculator.Store store = SpeedCalculator.Store.fromString(Storage); 
    sc.calculate(ref store); 
    Storage = store.ToString(); 
 
    lcd.clear();
    lcd.writeLine("Speed: "+Math.Round(sc.getSpeed(), 3)); 
    lcd.writeLine("Seconds Delta: "+Math.Round(sc.getDeltaSeconds(), 3)); 
}