Artifact Content
Not logged in

Artifact 95ed42a2d89e1fef9a37a76c14dc1db755211492


     1  import util;
     2  import game;
     3  import driver;
     4  import core.stdc.signal;
     5  
     6  class NilOutput : GameObserver
     7  {
     8  	this(in Game g) {}
     9  	override void on_game_changed(char c, in Game g, bool finished) {}
    10  }
    11  
    12  class StdOutput : GameObserver
    13  {
    14  	this(in Game g) {}
    15  	override void on_game_changed(char c, in Game g, bool finished)
    16  	{
    17  		stdout.write(c);
    18  		stdout.flush();
    19  	}
    20  }
    21  
    22  class GuardedOutput : GameObserver
    23  {
    24  	this(in Game g)
    25  	{
    26  		setup_sigint_handling();
    27  		score_log ~= g.score;
    28  		flushed = false;
    29  	}
    30  
    31  	override void on_game_changed(char c, in Game g, bool finished)
    32  	{
    33  		if(flushed)
    34  			return;
    35  
    36  		log ~= c;
    37  		score_log ~= g.score;
    38  		if(finished || log.length+1==g.map.W*g.map.H)
    39  			flush();
    40  		if(log.length+1==g.map.W*g.map.H)
    41  			application_exit();
    42  	}
    43  
    44  private:
    45  	string log;
    46  	long[] score_log;
    47  	bool   flushed;
    48  
    49  	void flush()
    50  	{
    51  		if(flushed)
    52  			return;
    53  
    54  		Tuple!(long, int) cand;
    55  		cand[0] = long.min;
    56  
    57  		for(int i=0; i<score_log.length; ++i)
    58  			if(cand[0] < score_log[i])	
    59  				cand = tuple(score_log[i],i);
    60  
    61  		std.c.stdio.printf("%.*sA\n", cand[1], log.ptr);
    62  		std.c.stdio.fflush(std.c.stdio.stdout);
    63  		flushed = true;
    64  	}
    65  
    66  private:
    67  	static __gshared GuardedOutput g_output;
    68  
    69  	void setup_sigint_handling()
    70  	{
    71  		assert(g_output is null);
    72  		g_output = this;
    73  		extern(C) static void catch_sigint(int) { g_output.flush(); application_exit(); }
    74  		core.stdc.signal.signal(SIGINT, &catch_sigint);
    75  	}
    76  }