From b7b4665a53290f9b277f4646e5e0a2ddda4ae6cf Mon Sep 17 00:00:00 2001 From: Jacob Signorovitch Date: Wed, 9 Apr 2025 19:18:01 -0400 Subject: [PATCH] Attempt at movement. --- .../src/twentyfortyeight/Main.java | 38 ++++++++++++++++--- 1 file changed, 33 insertions(+), 5 deletions(-) diff --git a/twentyfortyeight/src/twentyfortyeight/Main.java b/twentyfortyeight/src/twentyfortyeight/Main.java index 80f8fb7..0fcfe9a 100644 --- a/twentyfortyeight/src/twentyfortyeight/Main.java +++ b/twentyfortyeight/src/twentyfortyeight/Main.java @@ -81,7 +81,11 @@ class Game extends World { public void onKeyEvent(String key) { System.out.println("YES"); - if (key == "h") { this.grid.set(0, 0, 8); } + if (key.equals("left") || key.equals("h")) this.grid.move(0); + else if (key.equals("down") || key.equals("j")) this.grid.move(1); + else if (key.equals("up") || key.equals("k")) this.grid.move(2); + else if (key.equals("right") || key.equals("l")) this.grid.move(3); + else return; this.draw(); } @@ -119,21 +123,45 @@ class Grid { return free; } - // Set the tile at the coords. Just for testing. + // Get the indexes of all "unfree" cells -- those whose value in buf is not + // 0, and represent a used tile. + List unfreeCellIdxs() { + List unfree = new ArrayList<>(); + for (int i = 0; i < this.sz; i++) + if (this.buf.get(i) != 0 && unfree.add(i)) continue; + + return unfree; + } + + // Set the tile at the coords. Grid set(int x, int y, int v) { this.buf.set(this.w * y + x, v); return this; } - // Get the value at the coords. Just for testing. + // Get the value at the coords. int get(int x, int y) { return this.buf.get(this.w * y + x); } + // Get the x coord for an index. + int ix(int i) { return i % this.h; } + + // Get the y coord for an index. + int iy(int i) { return i % this.w; } + // Move all tiles in that direction until they can't move or combine any // more. void move(int d) { // TODO: Don't assume right. // Assume right. - for (int i = 0; i < this.h; i++) {} + List unfrees = this.unfreeCellIdxs(); + List frees = this.freeCellIdxs(); + for (int unfree : unfrees) { + /* + if (frees.contains(this.ix(unfree) + 1)) { + this.buf.set(unfree, 0)) + } + */ + } } // Render the grid. @@ -204,7 +232,7 @@ class Examples { } /* - void testMoveLeft(Tester t) { + void testMoveRight(Tester t) { init(); regular.set(1, 0, 16) .set(2, 0, 16)