git @ Cat's Eye Technologies Etcha / master src / Etcha.java
master

Tree @master (Download .tar.gz)

Etcha.java @masterraw · history · blame

  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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
package tc.catseye.etcha;

// SPDX-FileCopyrightText: In 2012, Chris Pressey, the original author of this work, placed it into the public domain.
// For more information, please refer to <https://unlicense.org/>
// SPDX-License-Identifier: Unlicense

// Etcha.java
// Ridiculous over-implementation of the Etcha programming language.
// I hereby place this work into the public domain.
// Chris Pressey, Cat's Eye Technologies.
// $Id: Etcha.java 257 2009-10-04 03:21:43Z cpressey $

import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

interface Grid
{
    void togglePixel(int x, int y);
    boolean isPixelBlack(int x, int y);
}

class DefaultGrid implements Grid
{
    private HashMap<Integer, HashMap<Integer, Boolean>> grid;
    private int minX, minY, maxX, maxY;

    DefaultGrid()
    {
        grid = new HashMap<Integer, HashMap<Integer, Boolean>>();
        minX = minY = maxX = maxY = 0;
    }

    private static boolean getBoolean(Boolean b)
    {
        return b == null ? false : b;
    }

    public void togglePixel(int x, int y)
    {
        HashMap<Integer, Boolean> column = grid.get(x);
        if (column == null) {
            column = new HashMap<Integer, Boolean>();
            column.put(y, true);
            grid.put(x, column);
        } else {
            column.put(y, !getBoolean(column.get(y)));
        }
        if (x < minX) minX = x;
        if (y < minY) minY = y;
        if (x > maxX) maxX = x;
        if (y > maxY) maxY = y;
    }

    public boolean isPixelBlack(int x, int y)
    {
        HashMap<Integer, Boolean> column = grid.get(x);
        if (column == null) {
            return false;
        } else {
            return getBoolean(column.get(y));
        }
    }

    public void dump()
    {
        int width = maxY - minY;
        for (int i = 0; i <= width; i++)
            System.out.print("-");
        System.out.println();
        for (int y = minY; y <= maxY; y++) {
            for (int x = minX; x <= maxX; x++) {
                System.out.print(isPixelBlack(x, y) ? "#" : " ");
            }
            System.out.println();
        }
        for (int i = 0; i <= width; i++)
            System.out.print("-");
        System.out.println();
    }
}

interface Turtle
{
    void forward(int distance);
    void rotate(int degrees);
    void setPenDown(boolean penDown);
    public boolean isPenDown();
    boolean detectPixel();
}

class DefaultTurtle implements Turtle
{
    private Grid grid;
    private int x, y;
    private int dx, dy;
    private boolean penDown;
    private int heading;

    DefaultTurtle()
    {
        grid = new DefaultGrid();
        x = 0;
        y = 0;
        penDown = true;
        heading = 0;
    }

    DefaultTurtle(Grid g)
    {
        grid = g;
        x = 0;
        y = 0;
        penDown = true;
        heading = 0;
    }

    public void forward(int distance)
    {
        for (int i = 0; i < distance; i++) {
            if (penDown)
                grid.togglePixel(x, y);
            x += dx();
            y += dy();
        }
    }

    private int dx()
    {
        if (heading == 90)
            return 1;
        if (heading == 270)
            return -1;
        return 0;
    }

    private int dy()
    {
        if (heading == 0)
            return -1;
        if (heading == 180)
            return 1;
        return 0;
    }

    public void rotate(int degrees)
    {
        heading += degrees;
        heading %= 360;
    }

    public void setPenDown(boolean penDown)
    {
        this.penDown = penDown;
    }

    public boolean isPenDown()
    {
        return penDown;
    }

    public boolean detectPixel()
    {
        return grid.isPixelBlack(x, y);
    }
}

interface Counter
{
    public boolean count();
}

class DefaultCounter implements Counter
{
    private int modulus;
    private int counter;

    DefaultCounter()
    {
        modulus = 4;
        counter = 0;
    }

    DefaultCounter(int m)
    {
        modulus = m;
        counter = 0;
    }

    DefaultCounter(int m, int c)
    {
        modulus = m;
        counter = c;
    }

    public boolean count()
    {
        counter++;
        counter %= modulus;
        return (counter == 0);
    }
}

// An execution context knows what command it is currently executing.
interface ExecutionContext
{
    Turtle getTurtle();
    Counter getCounter();
    ExecutionContext step();
}

class BaseExecutionContext implements ExecutionContext
{
    protected Turtle turtle;
    protected Counter counter;
    protected ExecutionContext parent;

    BaseExecutionContext(Turtle t, Counter c)
    {
        turtle = t;
        counter = c;
        parent = null;
    }

    BaseExecutionContext(ExecutionContext parent)
    {
        turtle = parent.getTurtle();
        counter = parent.getCounter();
        this.parent = parent;
    }

    public Turtle getTurtle()
    {
        return turtle;
    }

    public Counter getCounter()
    {
        return counter;
    }

    public ExecutionContext step()
    {
        return parent;
    }
}

class PrimitiveExecutionContext extends BaseExecutionContext
{
    protected Command cmd;

    PrimitiveExecutionContext(Command cmd, ExecutionContext parent)
    {
        super(parent);
        this.cmd = cmd;
    }

    public ExecutionContext step()
    {
        cmd.execute(turtle, counter);
        return parent;
    }
}

class BlockExecutionContext extends PrimitiveExecutionContext
{
    protected int pos;
    protected Block cmd;

    BlockExecutionContext(Block cmd, ExecutionContext parent)
    {
        super(cmd, parent);
        this.cmd = cmd;  // because our cmd is not our parent's!
        pos = 0;
    }

    public ExecutionContext step()
    {
        Command sub = cmd.get(pos);
        if (sub == null) {
            return parent;
        }
        pos++;
        ExecutionContext e = sub.createExecutionContext(this);
        // Could just return e here.  But then we'd have to do twice as many
        // steps, stepping into each contained command
        return e.step();
    }
}

class LoopExecutionContext extends BlockExecutionContext
{
    protected Loop cmd;

    LoopExecutionContext(Loop cmd, ExecutionContext parent)
    {
        super(cmd, parent);
        this.cmd = cmd;  // because our cmd is not our parent's!
    }

    public ExecutionContext step()
    {
        if (pos >= cmd.size()) {
            pos = 0;
        }
        if (pos == 0 && !turtle.detectPixel()) {
            return parent;
        }
        return super.step();
    }
}

interface Command
{
    void execute(Turtle t, Counter c);
    ExecutionContext createExecutionContext(ExecutionContext parent);
}

abstract class AbstractCommand implements Command
{
    abstract public void execute(Turtle t, Counter c);
    public ExecutionContext createExecutionContext(ExecutionContext parent)
    {
        return new PrimitiveExecutionContext(this, parent);
    }
}

class Right extends AbstractCommand
{
    public void execute(Turtle t, Counter c)
    {
        t.rotate(90);
        if (c.count())
            t.setPenDown(!t.isPenDown());
    }
}

class Forward extends AbstractCommand
{
    public void execute(Turtle t, Counter c)
    {
        t.forward(1);
    }
}

class Block extends AbstractCommand
{
    private List<Command> cmds;

    Block(List<Command> cmds)
    {
        this.cmds = cmds;
    }

    public Command get(int index)
    {
        try {
            return cmds.get(index);
        } catch (IndexOutOfBoundsException e) {
            return null;
        }
    }

    public int size()
    {
        return cmds.size();
    }

    public void execute(Turtle t, Counter c)
    {
        for (Command cmd : cmds) {
            cmd.execute(t, c);
        }
    }

    public ExecutionContext createExecutionContext(ExecutionContext parent)
    {
        return new BlockExecutionContext(this, parent);
    }
}

class Loop extends Block
{
    Loop(List<Command> cmds)
    {
        super(cmds);
    }

    public void execute(Turtle t, Counter c)
    {
        while (t.detectPixel()) {
            super.execute(t, c);
        }
    }

    public ExecutionContext createExecutionContext(ExecutionContext parent)
    {
        return new LoopExecutionContext(this, parent);
    }
}

class Executor
{
    Turtle turtle;
    Counter counter;

    Executor()
    {
        turtle = new DefaultTurtle();
        counter = new DefaultCounter();
    }

    Executor(Turtle t, Counter c)
    {
        turtle = t;
        counter = c;
    }

    Executor(Grid g)
    {
        turtle = new DefaultTurtle(g);
        counter = new DefaultCounter();
    }

    public void run(Command program)
    {
        program.execute(turtle, counter);
    }

    // same as run, but uses the step methods
    public void stepAll(Command program)
    {
        ExecutionContext base = new BaseExecutionContext(turtle, counter);
        ExecutionContext e = program.createExecutionContext(base);
        while (e != base) {
            e = e.step();
        }
    }
}

interface Warner
{
    void warn(String warning);
}

interface ParseFactory<X>
{
    char getRepresentation();
    X generate(Parser p);
}

abstract class AbstractParseFactory<X> implements ParseFactory<X>
{
    public abstract char getRepresentation();
    public abstract X generate(Parser p);
}

class ForwardParseFactory extends AbstractParseFactory<Command>
{
    public char getRepresentation()
    {
        return '+';
    }

    public Command generate(Parser p)
    {
        return new Forward();
    }
}

class RightParseFactory extends AbstractParseFactory<Command>
{
    public char getRepresentation()
    {
        return '>';
    }

    public Command generate(Parser p)
    {
        return new Right();
    }
}

class LoopParseFactory extends AbstractParseFactory<Command>
{
    public char getRepresentation()
    {
        return '[';
    }

    public Command generate(Parser p)
    {
        p.advance();
        Set<Character> until = new HashSet<Character>();
        until.add(new Character(']'));
        List<Command> cmds = p.parseMany(until);
        return new Loop(cmds);
    }
}

class Parser
{
    private String str;
    private int pos;
    private Warner warner;
    private Map<Character,ParseFactory<Command>> factoryMap;

    Parser(String s)
    {
        str = s;
        pos = 0;
        warner = null;
        factoryMap = new HashMap<Character,ParseFactory<Command>>();
        ArrayList<ParseFactory<Command>> factories = new ArrayList<ParseFactory<Command>>();
        factories.add(new ForwardParseFactory());
        factories.add(new RightParseFactory());
        factories.add(new LoopParseFactory());
        for (ParseFactory<Command> factory : factories) {
            factoryMap.put(factory.getRepresentation(), factory);
        }
    }

    public void setWarner(Warner w)
    {
        warner = w;
    }

    public void advance()
    {
        pos++;
    }

    public Command parseOne()
    {
        char c = str.charAt(pos);
        Command cmd = null;

        ParseFactory<Command> factory = factoryMap.get(c);
        if (factory != null) {
            cmd = factory.generate(this);
        } else if (warner != null) {
            warner.warn("unrecognized command '" + c +
                        "' at position " + pos);
        }
        advance();

        return cmd;
    }

    public List<Command> parseMany(Set<Character> until)
    {
        List<Command> cmds = new ArrayList<Command>();

        while (pos < str.length()) {
            char c = str.charAt(pos);
            if (until != null && until.contains(c))
                break;
            Command cmd = parseOne();
            if (cmd != null)
                cmds.add(cmd);
        }

        return cmds;
    }
}

// A command-line interface to our Etcha interpreter.
class Main
{
    static public void main(String argv[])
    {
        // parse command line arguments
        for (String arg : argv)
            loadAndInterpret(arg);
    }

    static void loadAndInterpret(String filename)
    {
        // open and read file
        StringBuffer fileContents = new StringBuffer();
        try {
            BufferedReader input = new BufferedReader(new FileReader(filename));
            String str;
            str = input.readLine();
            while (str != null) {
                fileContents.append(str);
                str = input.readLine();
            }
            input.close();
        } catch (IOException e) {
            System.err.println("Couldn't read '" + filename + "'");
            return;
        }
        Parser parser = new Parser(fileContents.toString());
        Set<Character> empty = new HashSet<Character>();
        Block program = new Block(parser.parseMany(empty));
        DefaultGrid grid = new DefaultGrid();
        Executor executor = new Executor(grid);
        executor.stepAll(program);
        grid.dump();
    }
}