challenge 出力の一時停止と再開

起動すると、標準出力に1秒毎に'a'の1文字を出力し続けるプログラムで、 以下の条件を満たすものを「どう書く?」

  • 'q'キーが押されるとプログラムは終了する
  • 出力中に'p'キーが押されると一時停止する
  • 一時停止中に'p'キーが押されると出力を再開する

Posted feedbacks - Other

標準出力といえるかかなり微妙ですが、Processing で。ウィンドウ中央に適当な色で a を書き続けます。
 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
boolean pause = false;

void setup(){
  size(200,200);
  frameRate(1);
  // "Processing -> Tools -> Create Font ..." and save "Courier-48.vlw" 
  PFont font = loadFont("Courier-48.vlw");
  textFont(font, 48);
  textAlign(CENTER);
}

void draw() {
  if (! pause) {
    fill(random(255),random(255),random(255));
    text("a", width/2, height/2);
  }
}

void keyPressed() {
  switch (key) {
    case 'p':
      pause = !pause;
      break;
    case 'q':
      fill(0, 30);
      text("quit", width/2, height/2);
      exit();
      break;
  }
}

ざっくりと。

 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
module Doukaku179 = begin
    type PeriodicAutoWriter = class
        val mutable timer : System.Threading.Timer
        new() = { timer = null }
        member t.Start()  = t.timer <- new System.Threading.Timer(
                              (fun _ -> printf "%s" "a"), null, 0, 1000)
        member t.Stop()   = if t.timer <> null then (t.timer.Dispose();
                                                     t.timer <- null)
                                               else ()
        member t.Toggle() = if t.timer = null then t.Start() else t.Stop()
    end
    
    let read_char () = System.Console.ReadKey().KeyChar
    let keep_read () = seq { while true do yield read_char () done }
    let run () = let writer = new PeriodicAutoWriter() in
                 writer.Start ();
                 seq { for c in keep_read () do
                         yield (match c with
                                  'q' -> writer.Stop();   false
                                | 'p' -> writer.Toggle(); true
                                | _   -> true)
                       done }
                 |> Seq.find ((=) false)
                 |> (fun _ -> printfn "%s" "");;
end;;

#if COMPILED
let _ = Doukaku179.run ();;
#endif

Index

Feed

Other

Link

Pathtraq

loading...