previndexinfonext

code guessing, round #42 (completed)

started at ; stage 2 at ; ended at

specification

they just wanna, they just wanna, oh, girls! girls just wanna have fun! so implement 2048 for them. submissions may be written in any language.

2048 is a puzzle game (which you have probably played before) based on sliding blocks on a grid. who could have guessed? it is based on a lineage of very similar games released at the same time, most notably the mobile game Threes, a clone of Threes called 1024, and a distinct clone of 1024 which is also called 2048. confusing, I know.

I'm sure you're quite familiar with how the game works already, but let's go over the rules again. the following specification will match the behaviour of the original JS game exactly.

the game takes place on a 4x4 grid. some spaces are empty, and some may contain tiles, which are labelled with powers of 2. when the game begins, the grid has 2 tiles on it. whenever a tile is placed on the board, it is put in a random empty space and has a 90% chance of being a 2 or a 10% chance of being a 4.

the player's only available move on each turn is to enter one of the 4 orthogonal directions to shift all the tiles in the grid in that direction. the tiles are moved in order of how close they are to the wall being pointed toward, the nearest ones first. they move as far as they can in the given direction, only stopping if they hit the edge of the grid or another tile with a different label.

if a tile hits another tile of the same label, the two merge: the tile moving is removed and the label of the tile it hit is doubled. a tile can only be merged with once in a single move.

after every move, if at least one tile moved, a tile is placed randomly, as described above. if there are no moves remaining that would move tiles, the player has lost; if a 2048 tile has been created, they have won.

here is an example of a move. the grid begins in this state:

4 - 2 2
8 8 8 -
2 2 2 2
2 - - 4

the player then decides to press right, so the tiles move like so:

- - 4 4
- - 8 16
- - 4 4
- - 2 4

after a random tile is placed, the grid may look like this:

- - 4 4
2 - 8 16
- - 4 4
- - 2 4

this process is repeated ad infinitum until the game is over.

your challenge is to implement an interactive playable version of 2048 through any medium you desire. after the player has won, you may allow them to keep playing, but this is not a requirement. this problem allows any language, and describes an interactive application, so there is no fixed API.

results

  1. πŸ‘‘ JJRubes +3 -0 = 3
    1. moshikoi (was taswelll)
    2. Lizzy Fleckenstein
    3. razetime (was kimapr)
    4. olive (was razetime)
    5. kimapr (was olus2000)
    6. Olivia (was moshikoi)
    7. LyricLy (was Olivia)
    8. taswelll (was olive)
    9. ultlang
    10. luatic
    11. olus2000 (was LyricLy)
  2. luatic +5 -3 = 2
    1. olus2000 (was taswelll)
    2. Lizzy Fleckenstein
    3. kimapr
    4. moshikoi (was razetime)
    5. JJRubes (was olus2000)
    6. ultlang (was moshikoi)
    7. Olivia
    8. olive
    9. taswelll (was ultlang)
    10. razetime (was JJRubes)
    11. LyricLy
  3. LyricLy +5 -3 = 2
    1. taswelll
    2. Lizzy Fleckenstein
    3. kimapr
    4. ultlang (was razetime)
    5. JJRubes (was olus2000)
    6. luatic (was moshikoi)
    7. Olivia
    8. olive
    9. olus2000 (was ultlang)
    10. moshikoi (was JJRubes)
    11. razetime (was luatic)
  4. taswelll +4 -2 = 2
    1. olus2000 (was Lizzy Fleckenstein)
    2. kimapr
    3. JJRubes (was razetime)
    4. luatic (was olus2000)
    5. moshikoi
    6. Olivia
    7. Lizzy Fleckenstein (was olive)
    8. ultlang
    9. LyricLy (was JJRubes)
    10. razetime (was luatic)
    11. olive (was LyricLy)
  5. moshikoi +3 -1 = 2
    1. razetime (was taswelll)
    2. Lizzy Fleckenstein
    3. olive (was kimapr)
    4. LyricLy (was razetime)
    5. luatic (was olus2000)
    6. Olivia
    7. JJRubes (was olive)
    8. ultlang
    9. olus2000 (was JJRubes)
    10. taswelll (was luatic)
    11. kimapr (was LyricLy)
  6. razetime +2 -0 = 2
    1. olive (was taswelll)
    2. Lizzy Fleckenstein
    3. moshikoi (was kimapr)
    4. kimapr (was olus2000)
    5. luatic (was moshikoi)
    6. Olivia
    7. olus2000 (was olive)
    8. JJRubes (was ultlang)
    9. LyricLy (was JJRubes)
    10. taswelll (was luatic)
    11. ultlang (was LyricLy)
  7. olus2000 +1 -0 = 1
    1. olive (was taswelll)
    2. luatic (was Lizzy Fleckenstein)
    3. LyricLy (was kimapr)
    4. Lizzy Fleckenstein (was razetime)
    5. Olivia (was moshikoi)
    6. kimapr (was Olivia)
    7. taswelll (was olive)
    8. ultlang
    9. moshikoi (was JJRubes)
    10. JJRubes (was luatic)
    11. razetime (was LyricLy)
  8. olive +4 -4 = 0
    1. razetime (was taswelll)
    2. Lizzy Fleckenstein
    3. kimapr
    4. moshikoi (was razetime)
    5. JJRubes (was olus2000)
    6. luatic (was moshikoi)
    7. Olivia
    8. olus2000 (was ultlang)
    9. taswelll (was JJRubes)
    10. ultlang (was luatic)
    11. LyricLy
  9. Lizzy Fleckenstein +4 -7 = -3
    1. moshikoi (was taswelll)
    2. kimapr
    3. JJRubes (was razetime)
    4. taswelll (was olus2000)
    5. LyricLy (was moshikoi)
    6. Olivia
    7. olive
    8. olus2000 (was ultlang)
    9. razetime (was JJRubes)
    10. luatic
    11. ultlang (was LyricLy)
  10. kimapr +3 -6 = -3
    1. Olivia (was taswelll)
    2. Lizzy Fleckenstein
    3. JJRubes (was razetime)
    4. moshikoi (was olus2000)
    5. ultlang (was moshikoi)
    6. LyricLy (was Olivia)
    7. olive
    8. olus2000 (was ultlang)
    9. razetime (was JJRubes)
    10. luatic
    11. taswelll (was LyricLy)
  11. ultlang +1 -4 = -3
    1. Lizzy Fleckenstein (was taswelll)
    2. JJRubes (was Lizzy Fleckenstein)
    3. LyricLy (was kimapr)
    4. olus2000 (was razetime)
    5. luatic (was olus2000)
    6. kimapr (was moshikoi)
    7. Olivia
    8. moshikoi (was olive)
    9. razetime (was JJRubes)
    10. taswelll (was luatic)
    11. olive (was LyricLy)
  12. Olivia +3 -8 = -5
    1. taswelll
    2. JJRubes (was Lizzy Fleckenstein)
    3. kimapr
    4. moshikoi (was razetime)
    5. luatic (was olus2000)
    6. ultlang (was moshikoi)
    7. Lizzy Fleckenstein (was olive)
    8. olus2000 (was ultlang)
    9. razetime (was JJRubes)
    10. olive (was luatic)
    11. LyricLy

entries

you can download all the entries

entry #1

written by taswelll
submitted at
1 like

guesses
comments 0

post a comment


2048.apls Unicode text, UTF-8 text
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
#!/usr/local/bin/dyalogscript
βŽ•IO←0 β‹„ g←4 4↑~∘0⍀1
c←>/∘⌽¨(,\0βˆ˜β‰ Γ—2=/0,⊒)
r←{⍡+2 4[0=?10]Γ—4 4⍴0=⍋⍒(1+?⍨16)Γ—0=,⍡}
s←{β‰βˆ˜βŒ½β£β΅ gΓ—βˆ˜(1∘⌽+~)∘c⍨g βŒ½βˆ˜β‰β£β΅ ⊒⍺}
lβ†βˆ§/∘,{~⍡[1;1]βˆŠβ΅Γ—3 3⍴0 1}⌺3 3⍀⊣
βŽ•β†'LW'[2048β‰€βŒˆ/,βŽ•β†{
 βŽ• βŽ•β†β΅ 'enter key (wasd): '
 r⍣(A≒⍡)⊒A←⍡s'asdw'β³βŽ•CβŠƒβž
}⍣l r 4 4⍴0]

entry #2

written by Lizzy Fleckenstein
submitted at
2 likes

guesses
comments 0

post a comment


dir rs2048
dir src
display.rs Unicode text, UTF-8 text
  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
use super::game::{Board, Pos};
use crossterm::{cursor, queue, style::*};

enum Mode {
    Roof_,
    Data_,
    Floor,
    Empty,
    Base_,
}

const FIELD_HEIGHT: usize = 3;
const FIELD_WIDTH: usize = 8;

fn write_line(stdout: &mut std::io::Stdout, vec: &[u32], mode: Mode) -> crossterm::Result<()> {
    let mut vec = vec;
    let len = vec.len();

    queue!(
        stdout,
        Print(match mode {
            Mode::Roof_ => "┏",
            Mode::Data_ => "┃",
            Mode::Floor => "β” ",
            Mode::Empty => "┃",
            Mode::Base_ => "β”—",
        })
    )?;

    for i in 0..len {
        let &n = vec.last().unwrap();
        vec = &vec[0..vec.len() - 1];

        match mode {
            Mode::Data_ | Mode::Empty => queue!(stdout, Print(" "))?,
            _ => {}
        }

        match mode {
            Mode::Data_ | Mode::Empty if n != 0 => {
                let (r, g, b) = hsl::HSL {
                    h: (n * 360 / 12) as f64,
                    s: 1.0,
                    l: 0.5,
                }
                .to_rgb();

                queue!(
                    stdout,
                    SetColors(Colors::new(Color::Black, Color::Rgb { r, g, b }))
                )?;
            }
            _ => {}
        };

        queue!(
            stdout,
            Print(match mode {
                Mode::Roof_ | Mode::Base_ => "━".repeat(FIELD_WIDTH),
                Mode::Floor => "─".repeat(FIELD_WIDTH),
                Mode::Data_ if n != 0 => format!("{:^w$}", 1 << n, w = FIELD_WIDTH - 2),
                Mode::Empty | Mode::Data_ => " ".repeat(FIELD_WIDTH - 2),
            })
        )?;

        match mode {
            Mode::Data_ | Mode::Empty => {
                queue!(stdout, SetAttribute(Attribute::Reset), Print(" "))?
            }
            _ => {}
        }

        if i != len - 1 {
            queue!(
                stdout,
                Print(match mode {
                    Mode::Roof_ => "β”―",
                    Mode::Data_ => "β”‚",
                    Mode::Floor => "β”Ό",
                    Mode::Empty => "β”‚",
                    Mode::Base_ => "β”·",
                })
            )?;
        }
    }

    queue!(
        stdout,
        Print(match mode {
            Mode::Roof_ => "β”“",
            Mode::Data_ => "┃",
            Mode::Floor => "┨",
            Mode::Empty => "┃",
            Mode::Base_ => "β”›",
        }),
        cursor::MoveToNextLine(1),
    )?;

    Ok(())
}

pub fn display_board(stdout: &mut std::io::Stdout, board: &Board) -> crossterm::Result<()> {
    let dummy = vec![0; board.size.x as usize];

    write_line(stdout, &dummy, Mode::Roof_)?;

    for y in 0..board.size.y {
        let vec = (0..board.size.x)
            .rev()
            .map(|x| board.get(Pos::new(x, y)).value())
            .collect::<Vec<u32>>();

        for i in 0..FIELD_HEIGHT {
            write_line(
                stdout,
                &vec,
                if i == FIELD_HEIGHT / 2 {
                    Mode::Data_
                } else {
                    Mode::Empty
                },
            )?;
        }

        if y != board.size.y - 1 {
            write_line(stdout, &dummy, Mode::Floor)?;
        }
    }

    write_line(stdout, &dummy, Mode::Base_)?;

    Ok(())
}
game.rs ASCII text
  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
pub use glam::i32::IVec2 as Pos;
use rand::seq::IteratorRandom;
use std::cell::RefCell;

trait Swap {
    fn swap(self) -> Self;
}

impl Swap for Pos {
    fn swap(self) -> Self {
        Self::new(self.y, self.x)
    }
}

pub struct Field(RefCell<u32>);

enum MergeResult {
    Merged(u32),
    Replaced,
    Blocked,
    Empty,
}

impl Field {
    fn new() -> Self {
        Self(RefCell::new(0))
    }

    pub fn value(&self) -> u32 {
        *self.0.borrow()
    }

    fn merge(&self, other: &Self) -> MergeResult {
        let mut s = self.0.borrow_mut();
        let mut o = other.0.borrow_mut();

        if *o == 0 {
            return MergeResult::Empty;
        }

        if *s == 0 {
            *s = *o;
            *o = 0;

            return MergeResult::Replaced;
        }

        if *s == *o {
            *s += 1;
            *o = 0;

            return MergeResult::Merged(1 << *s);
        }

        MergeResult::Blocked
    }
}

pub struct Board {
    pub size: Pos,
    fields: Vec<Vec<Field>>,
}

pub enum Dir {
    Up,
    Down,
    Left,
    Right,
}

impl Board {
    pub fn new(size: Pos) -> Self {
        Self {
            size,
            fields: (0..size.x)
                .map(|_| (0..size.y).map(|_| Field::new()).collect())
                .collect(),
        }
    }

    pub fn step(&self, dir: Dir) -> Option<u32> {
        let dir = match dir {
            Dir::Up => -Pos::Y,
            Dir::Down => Pos::Y,
            Dir::Left => -Pos::X,
            Dir::Right => Pos::X,
        };

        let step_row = dir.abs().swap();
        let step_col = -dir;

        let len_row = (step_row.abs() * self.size).max_element();
        let len_col = (step_col.abs() * self.size).max_element();

        let start = (dir + Pos::ONE) / 2 * (self.size - Pos::ONE);

        let mut score = None;

        for row in 0..len_row {
            let start_row = start + row * step_row;

            for col1 in 0..len_col - 1 {
                let field1 = self.get(start_row + col1 * step_col);

                for col2 in col1 + 1..len_col {
                    let field2 = self.get(start_row + col2 * step_col);

                    match field1.merge(field2) {
                        MergeResult::Merged(sc) => {
                            score = Some(score.unwrap_or(0) + sc);
                            break;
                        }
                        MergeResult::Replaced => score = Some(score.unwrap_or(0)),
                        MergeResult::Blocked => break,
                        MergeResult::Empty => continue,
                    }
                }
            }
        }

        score
    }

    pub fn get(&self, pos: Pos) -> &Field {
        self.fields
            .get(pos.x as usize)
            .unwrap()
            .get(pos.y as usize)
            .unwrap()
    }

    pub fn spawn<R>(&self, rng: &mut R)
    where
        R: rand::Rng + ?core::marker::Sized,
    {
        if let Some(field) = self
            .fields
            .iter()
            .flat_map(|v| v.iter())
            .filter(|f| f.value() == 0)
            .choose(rng)
        {
            *field.0.borrow_mut() = 1;
        }
    }
}
main.rs ASCII text
 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
pub mod display;
pub mod game;

use crossterm::{cursor, event, execute, queue, style, terminal};
use game::{Board, Dir::*, Pos};
use std::io::Write;

fn main() {
    let mut rng = rand::thread_rng();

    let mut stdout = std::io::stdout();
    queue!(stdout, terminal::EnterAlternateScreen, cursor::Hide).unwrap();

    terminal::enable_raw_mode().unwrap();

    let board = Board::new(Pos::new(4, 4));
    board.spawn(&mut rng);
    board.spawn(&mut rng);

    let mut score = 0;

    loop {
        queue!(
            stdout,
            terminal::Clear(terminal::ClearType::All),
            cursor::MoveTo(0, 0),
            style::SetAttribute(style::Attribute::Bold),
            style::Print("Score: ".to_string()),
            style::SetAttribute(style::Attribute::Reset),
            style::Print(score.to_string()),
            cursor::MoveToNextLine(1),
        )
        .unwrap();
        display::display_board(&mut stdout, &board).unwrap();
        stdout.flush().unwrap();

        if let Ok(evt) = event::read() {
            match evt {
                event::Event::Key(event::KeyEvent { code, .. }) => match code {
                    event::KeyCode::Char(ch) => {
                        if let Some(sc) = board.step(match ch.to_ascii_lowercase() {
                            'w' => Up,
                            'a' => Left,
                            's' => Down,
                            'd' => Right,
                            'q' => break,
                            _ => continue,
                        }) {
                            score += sc;
                            board.spawn(&mut rng);
                        }
                    }
                    _ => {}
                },
                _ => {}
            }
        } else {
            break;
        }
    }

    terminal::disable_raw_mode().unwrap();
    execute!(stdout, cursor::Show, terminal::LeaveAlternateScreen).unwrap();
}
.gitignore ASCII text
1
/target
Cargo.lock ASCII text
  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
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3

[[package]]
name = "autocfg"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"

[[package]]
name = "bitflags"
version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"

[[package]]
name = "cfg-if"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"

[[package]]
name = "crossterm"
version = "0.25.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e64e6c0fbe2c17357405f7c758c1ef960fce08bdfb2c03d88d2a18d7e09c4b67"
dependencies = [
 "bitflags",
 "crossterm_winapi",
 "libc",
 "mio",
 "parking_lot",
 "signal-hook",
 "signal-hook-mio",
 "winapi",
]

[[package]]
name = "crossterm_winapi"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2ae1b35a484aa10e07fe0638d02301c5ad24de82d310ccbd2f3693da5f09bf1c"
dependencies = [
 "winapi",
]

[[package]]
name = "getrandom"
version = "0.2.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4eb1a864a501629691edf6c15a593b7a51eebaa1e8468e9ddc623de7c9b58ec6"
dependencies = [
 "cfg-if",
 "libc",
 "wasi",
]

[[package]]
name = "glam"
version = "0.21.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "518faa5064866338b013ff9b2350dc318e14cc4fcd6cb8206d7e7c9886c98815"

[[package]]
name = "hsl"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "575fb7f1167f3b88ed825e90eb14918ac460461fdeaa3965c6a50951dee1c970"

[[package]]
name = "libc"
version = "0.2.132"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8371e4e5341c3a96db127eb2465ac681ced4c433e01dd0e938adbef26ba93ba5"

[[package]]
name = "lock_api"
version = "0.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f80bf5aacaf25cbfc8210d1cfb718f2bf3b11c4c54e5afe36c236853a8ec390"
dependencies = [
 "autocfg",
 "scopeguard",
]

[[package]]
name = "log"
version = "0.4.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e"
dependencies = [
 "cfg-if",
]

[[package]]
name = "mio"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57ee1c23c7c63b0c9250c339ffdc69255f110b298b901b9f6c82547b7b87caaf"
dependencies = [
 "libc",
 "log",
 "wasi",
 "windows-sys",
]

[[package]]
name = "parking_lot"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3742b2c103b9f06bc9fff0a37ff4912935851bee6d36f3c02bcc755bcfec228f"
dependencies = [
 "lock_api",
 "parking_lot_core",
]

[[package]]
name = "parking_lot_core"
version = "0.9.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09a279cbf25cb0757810394fbc1e359949b59e348145c643a939a525692e6929"
dependencies = [
 "cfg-if",
 "libc",
 "redox_syscall",
 "smallvec",
 "windows-sys",
]

[[package]]
name = "ppv-lite86"
version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eb9f9e6e233e5c4a35559a617bf40a4ec447db2e84c20b55a6f83167b7e57872"

[[package]]
name = "rand"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"
dependencies = [
 "libc",
 "rand_chacha",
 "rand_core",
]

[[package]]
name = "rand_chacha"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
dependencies = [
 "ppv-lite86",
 "rand_core",
]

[[package]]
name = "rand_core"
version = "0.6.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d34f1408f55294453790c48b2f1ebbb1c5b4b7563eb1f418bcfcfdbb06ebb4e7"
dependencies = [
 "getrandom",
]

[[package]]
name = "redox_syscall"
version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a"
dependencies = [
 "bitflags",
]

[[package]]
name = "rs2048"
version = "0.1.0"
dependencies = [
 "crossterm",
 "glam",
 "hsl",
 "rand",
]

[[package]]
name = "scopeguard"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd"

[[package]]
name = "signal-hook"
version = "0.3.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a253b5e89e2698464fc26b545c9edceb338e18a89effeeecfea192c3025be29d"
dependencies = [
 "libc",
 "signal-hook-registry",
]

[[package]]
name = "signal-hook-mio"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29ad2e15f37ec9a6cc544097b78a1ec90001e9f71b81338ca39f430adaca99af"
dependencies = [
 "libc",
 "mio",
 "signal-hook",
]

[[package]]
name = "signal-hook-registry"
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e51e73328dc4ac0c7ccbda3a494dfa03df1de2f46018127f60c693f2648455b0"
dependencies = [
 "libc",
]

[[package]]
name = "smallvec"
version = "1.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2fd0db749597d91ff862fd1d55ea87f7855a744a8425a64695b6fca237d1dad1"

[[package]]
name = "wasi"
version = "0.11.0+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"

[[package]]
name = "winapi"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
dependencies = [
 "winapi-i686-pc-windows-gnu",
 "winapi-x86_64-pc-windows-gnu",
]

[[package]]
name = "winapi-i686-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"

[[package]]
name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"

[[package]]
name = "windows-sys"
version = "0.36.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ea04155a16a59f9eab786fe12a4a450e75cdb175f9e0d80da1e17db09f55b8d2"
dependencies = [
 "windows_aarch64_msvc",
 "windows_i686_gnu",
 "windows_i686_msvc",
 "windows_x86_64_gnu",
 "windows_x86_64_msvc",
]

[[package]]
name = "windows_aarch64_msvc"
version = "0.36.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9bb8c3fd39ade2d67e9874ac4f3db21f0d710bee00fe7cab16949ec184eeaa47"

[[package]]
name = "windows_i686_gnu"
version = "0.36.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "180e6ccf01daf4c426b846dfc66db1fc518f074baa793aa7d9b9aaeffad6a3b6"

[[package]]
name = "windows_i686_msvc"
version = "0.36.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2e7917148b2812d1eeafaeb22a97e4813dfa60a3f8f78ebe204bcc88f12f024"

[[package]]
name = "windows_x86_64_gnu"
version = "0.36.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4dcd171b8776c41b97521e5da127a2d86ad280114807d0b2ab1e462bc764d9e1"

[[package]]
name = "windows_x86_64_msvc"
version = "0.36.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c811ca4a8c853ef420abd8592ba53ddbbac90410fab6903b3e79972a631f7680"
Cargo.toml ASCII text
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
[package]
name = "rs2048"
version = "0.1.0"
edition = "2021"

[dependencies]
crossterm = "0.25.0"
glam = "0.21.3"
hsl = "0.1.1"
rand = "0.8.5"
LICENSE ASCII text
  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
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU General Public License is a free, copyleft license for
software and other kinds of works.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.  We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors.  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received.  You must make sure that they, too, receive
or can get the source code.  And you must show them these terms so they
know their rights.

  Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

  For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software.  For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

  Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so.  This is fundamentally incompatible with the aim of
protecting users' freedom to change the software.  The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable.  Therefore, we
have designed this version of the GPL to prohibit the practice for those
products.  If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.

  Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary.  To prevent this, the GPL assures that
patents cannot be used to render the program non-free.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Use with the GNU Affero General Public License.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:

    <program>  Copyright (C) <year>  <name of author>
    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.

  The GNU General Public License does not permit incorporating your program
into proprietary programs.  If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.  But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

entry #3

written by kimapr
submitted at
3 likes

guesses
comments 1
kimapr ΒΆ

updated versions available at gitlab and my website


post a comment


.gitignore ASCII text
1
2
/http.conf
/tmp
README.md ASCII text
 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
# 2048.php

An implementation of 2048 in PHP. Supports arbitrary board sizes.

## Web UI

**NOTE**: Unfinished.

Uses streamed HTML and CSS to create dynamic content without any client-side
JavaScript.

CGI. Communication between the main game process and control scripts (invoked
by form buttons targeting an invisible iframe) is done via UNIX domain datagram
sockets. Will not work on Windows, get a real operating system.

For convenience, a CLI script is provided that runs a pre-configured lighttpd
instance:

    ./server.php [address <port>]

## CLI

Simple CLI. Displays numbers on the board as base 2 logarithms in hexadecimal
(1=>2, 2=>4, b=>2048, etc.).

    ./cli.php [width [height [initial blocks]]]
cli.php ASCII text
  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
#!/usr/bin/php
<?php
include 'game.php';

class x1p11TextUI {
	private $game;
	private $board;
	private $ents;
	private $w, $h;
	private $lost;
	private $won;
	private $score;
	private const STATES = [
		" ",
		"new" => "!",
		"slide" => ":",
		"merge" => "+",
	];
	private function set($x, $y, $v = null, $new = 0) {
		$v = $v == null ? '.' : dechex(log($v, 2));
		$v = (object) ['v' => $v, 'new' => $new];
		$this->board[$y][$x] = $v;
	}
	private function expire() {
		for ($y = 0; $y < $this->h; $y++) {
			for ($x = 0; $x < $this->w; $x++) {
				$this->board[$y][$x]->new = false;
			}
		}
	}
	private function board_dump() {
		for ($y = 0; $y < $this->h; $y++) {
			echo ' ';
			for ($x = 0; $x < $this->w; $x++) {
				$v = $this->board[$y][$x];
				$v = $v->v . (self::STATES[$v->new]);
				echo $v;
			}
			echo "\n";
		}
	}
	public function __construct(x1p11 $game) {
		$this->game = $game;
		$this->board = [];
		$this->ents = [];
		$this->score = 0;
		[$this->w, $this->h] = $game->dimensions();
		for ($y = 0; $y < $this->h; $y++) {
			for ($x = 0; $x < $this->w; $x++) {
				$this->set($x, $y);
			}
		}
		/*
			// Debug
			$this->game->attach_handler(function ($type, $event) {
				/* //noise
					echo "Event: ";
					print_r($type->name);
					echo "\n";
					foreach ((array)$event as $k=>$v) {
						echo "	$k: ";
						print_r($v);
						echo "\n";
					}
					echo "\n";
				//* /
			});
			$deleting = [];
			$this->game->detach_handler($this->game->attach_handler(function ($type, $event) use (&$deleting) {
				if($type!=BoardEventType::Spawn){
					return;
				}
				$deleting[] = $event->pos;
			}));
			foreach ($deleting as [$x, $y]) {
				$this->game->set($x, $y);
			}
			foreach ([
				[4, 5, 6, 4],
				[1, 4, 2, 2],
				[2, 3, 0, 2],
				[0, 0, 0, 0],
			] as $y => $row) {
				foreach ($row as $x => $v) {
					$this->game->set($x, $y, $v>0?(2 ** $v):null);
				}
			}
		//*/
		$this->game->attach_handler($handler = function ($type, $event) use (&$handler) {
			switch ($type) {
			case BoardEventType::Slide:
				$ent = $this->ents[$event->id];
				[$x, $y] = $ent->pos;
				$this->set($x, $y);
				$ent->pos = $event->pos;
				[$x, $y] = $ent->pos;
				$this->set($x, $y, $ent->value, "slide");
				break;
			case BoardEventType::Merge:
				$src = $this->ents[$event->src];
				$dest = $this->ents[$event->dest];
				$handler(BoardEventType::Despawn, (object) [
					'id' => $event->src,
				]);
				$dest->value += $src->value;
				[$x, $y] = $dest->pos;
				$this->set($x, $y, $dest->value, "merge");
				break;
			case BoardEventType::Score:
				$this->score += $event->value;
				break;
			case BoardEventType::Spawn:
				$ent = (object) [
					'pos' => $event->pos,
					'value' => $event->value,
				];
				$this->ents[$event->id] = $ent;
				[$x, $y] = $ent->pos;
				$this->set($x, $y, $ent->value, "new");
				break;
			case BoardEventType::Despawn:
				$ent = $this->ents[$event->id];
				unset($this->ents[$event->id]);
				[$x, $y] = $ent->pos;
				$this->set($x, $y);
				break;
			case BoardEventType::Lose:
				$this->lost = true;
				if ($this->won) {
					echo "Game over.\n";
				} else {
					echo "You lost the game.\n";
				}
				break;
			case BoardEventType::Win:
				$this->won = true;
				echo "You won!\n";
				break;
			}
		});
		$cmds = [
			'w' => Direction::Up,
			's' => Direction::Down,
			'a' => Direction::Left,
			'd' => Direction::Right,
			'q' => false,
		];
		$this->expire();
		while (1) {
			$this->board_dump();
			echo "Score: {$this->score}\n";
			if ($this->lost) {
				break;
			}
			//var_dump($this->game);
			$cmd = "";
			while (!isset($cmds[$cmd])) {
				$cmd = readline('> ');
				if ($cmd === false) {
					break 2;
				}
				$cmd = strtolower($cmd);
			}
			$cmd = $cmds[$cmd];
			if (!$cmd) {
				break;
			}
			$this->expire();
			$this->game->move($cmd);
		}
	}
}

$w = 4;
$h = 4;
$c = 2;
if (isset($argv[1])) {$w = $argv[1];}
if (isset($argv[2])) {$h = $argv[2];}
if (isset($argv[3])) {$c = $argv[3];}
if (!(is_numeric($w) && is_numeric($h) && is_numeric($c))) {
	echo <<<Eof
	2048.php CLI. WASD to move.
	Numbers are displayed as base 2 logarithms in hex.
	Usage: 2048.php [width [height [initial blocks]]]

	Eof;
	return;
}

new x1p11TextUI(new x1p11($w, $h, $c));
game.php Unicode text, UTF-8 text
  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
<?php

enum Direction: int {
case Down = 0;
case Left = 1;
case Up = 2;
case Right = 3;
}

enum BoardEventType {
case Spawn;
case Slide;
case Merge;
case Despawn;

case Score;
case Win;
case Lose;
}

class x1p11 {
	private $dirs;
	private $board;
	private $w, $h;
	private $freeds;
	private $ents;
	private $won;
	private $lost;
	private $score;
	private $handlers;
	private function pos($x, $y) {
		return $this->w * $y + $x;
	}
	private function spawn(Callable $handler, ?int $c = 1) {
		$cands = [];
		for ($y = 0; $y < $this->h; $y++) {
			for ($x = 0; $x < $this->w; $x++) {
				if ($this->board[$this->pos($x, $y)] == -1) {
					$cands[] = [$x, $y];
				}
			}
		}
		$c = min(count($cands), $c);
		if ($c == 0) {
			return;
		}
		$ids = array_slice($this->freeds, count($this->freeds) - $c);
		$rands = array_rand($cands, $c);
		if ($c == 1) {
			$rands = [$rands];
		}
		foreach (array_map(function ($k) use (&$cands) {return $cands[$k];}, $rands) as $i => [$x, $y]) {
			$handler(BoardEventType::Spawn, (object) [
				'pos' => [$x, $y],
				'id' => $ids[$i],
				'value' => rand(1, 2) * 2,
			]);
		}
	}
	private function safeset($i, $v) {
		if ($this->board[$i] != -1) {
			$this->apply(BoardEventType::Despawn, (object) [
				'id' => $this->board[$i],
			]);
		}
		$this->board[$i] = $v;
	}
	private function apply(BoardEventType $type, object $event) {
		switch ($type) {
		case BoardEventType::Slide:
			$id = $event->id;
			$pos = $event->pos;

			$ent = $this->ents[$id];
			$this->safeset($this->pos(...$pos), $id);
			$this->board[$this->pos(...$ent->pos)] = -1;
			$ent->pos = $pos;
			break;

		case BoardEventType::Merge:
			$src = $event->src;
			$dest = $event->dest;

			$entsrc = $this->ents[$src];
			$entdest = $this->ents[$dest];
			$this->apply(BoardEventType::Despawn, (object) [
				'id' => $src,
			]);
			$entdest->value += $entsrc->value;
			break;

		case BoardEventType::Score:
			$score = $event->value;

			$this->score += $score;
			break;

		case BoardEventType::Despawn:
			$id = $event->id;

			$ent = $this->ents[$event->id];
			$this->freeds[$event->id] = $event->id;
			unset($this->ents[$event->id]);
			$this->board[$this->pos(...$ent->pos)] = -1;
			break;

		case BoardEventType::Spawn:
			$id = $event->id;
			$pos = $event->pos;
			$value = $event->value;

			unset($this->freeds[$id]);
			$this->safeset($this->pos(...$pos), $id);
			$this->ents[$id] = (object) [
				'pos' => $pos,
				'value' => $value,
			];
			break;

		case BoardEventType::Lose:
			$this->lost = true;
			break;

		case BoardEventType::Win:
			$this->won = true;
			break;
		}
	}
	private function _move(Callable $handler, Direction $dir, bool $check = true) {
		[$ox, $oy, $mc, $mb, $cdx, $cdy, $bdx, $bdy] = $this->dirs[$dir->value];
		$moved = false;
		for ($c = 0; $c < $mc; $c++) {
			[$xπŸ₯Ί, $yπŸ₯Ί] = [$ox, $oy];
			[$x😈, $y😈] = [$ox, $oy];
			for ([$bπŸ₯Ί, $b😈] = [0, 0]; $bπŸ₯Ί < $mb - 1 && $b😈 < $mb;) {
				$idπŸ₯Ί = $this->board[$this->pos($xπŸ₯Ί, $yπŸ₯Ί)];
				$valπŸ₯Ί = $idπŸ₯Ί != -1 ? $this->ents[$idπŸ₯Ί]->value : null;
				$merges = $idπŸ₯Ί == -1 ? 2 : 1;
				for (; $merges > 0;) {
					do {
						[$x😈, $y😈, $b😈] = [$x😈 + $bdx, $y😈 + $bdy, $b😈 + 1];
					} while ($b😈 <= $bπŸ₯Ί);
					if ($b😈 >= $mb) {
						break;
					}
					$id😈 = $this->board[$this->pos($x😈, $y😈)];
					$val😈 = $id😈 != -1 ? $this->ents[$id😈]->value : null;
					if ($id😈 != -1) {
						$merges--;
						if ($idπŸ₯Ί == -1) {
							$handler(BoardEventType::Slide, (object) [
								'id' => $id😈,
								'pos' => [$xπŸ₯Ί, $yπŸ₯Ί],
								'lane' => $c,
							]);
							$valπŸ₯Ί = $val😈;
							$val😈 = null;
							$idπŸ₯Ί = $id😈;
							$id😈 = -1;
							$moved = true;
						} elseif ($valπŸ₯Ί == $val😈) {
							$handler(BoardEventType::Merge, (object) [
								'src' => $id😈,
								'dest' => $idπŸ₯Ί,
								'lane' => $c,
							]);
							$valπŸ₯Ί = $valπŸ₯Ί + $val😈;
							$val😈 = null;
							$idπŸ₯Ί = $id😈;
							$id😈 = -1;
							$handler(BoardEventType::Score, (object) [
								'value' => $valπŸ₯Ί,
							]);
							if ($check && !$this->won && $valπŸ₯Ί >= 2048) {
								$handler(BoardEventType::Win, (object) []);
							}
							$moved = true;
						} else {
							[$x😈, $y😈, $b😈] = [$x😈 - $bdx, $y😈 - $bdy, $b😈 - 1];
							break;
						}
					}
				}
				[$xπŸ₯Ί, $yπŸ₯Ί, $bπŸ₯Ί] = [$xπŸ₯Ί + $bdx, $yπŸ₯Ί + $bdy, $bπŸ₯Ί + 1];
			}
			[$ox, $oy] = [$ox + $cdx, $oy + $cdy];
		}
		if (!$check) {
			return $moved;
		}
		if ($moved) {
			$this->spawn($handler);
		}
		$lost = true;
		foreach (Direction::cases() as $cdir) {
			if ($cdir != $dir && $this->_move(fn() => null, $cdir, false)) {
				$lost = false;
				break;
			}
		}
		if ($lost) {
			$handler(BoardEventType::Lose, (object) []);
		}
	}
	private function handler(...$a) {
		$this->apply(...$a);
		foreach ($this->handlers as $f) {
			$f(...$a);
		}
	}

	public function __construct(?int $w = 4, ?int $h = null, ?int $c = 2) {
		$h = $h == null ? $w : $h;
		$this->board = [];
		$this->freeds = [];
		$this->ents = [];
		$this->handlers = new SplObjectStorage();
		$this->won = false;
		$this->lost = false;
		$this->score = 0;
		$id = 0;
		for ($i = 0; $i < $w * $h; $i++) {
			$this->board[] = -1;
			$this->freeds[$id] = $id;
			$id++;
		}
		array_reverse($this->freeds, true);
		[$mx, $my] = [$w - 1, $h - 1];
		$this->dirs = [
			[0, $my, $w, $h, 1, 0, 0, -1],
			[0, 0, $h, $w, 0, 1, 1, 0],
			[$mx, 0, $w, $h, -1, 0, 0, 1],
			[$mx, $my, $h, $w, 0, -1, -1, 0],
		];
		[$this->w, $this->h] = [$w, $h];
		$this->spawn([$this, 'apply'], $c);
	}
	public function dimensions() {
		return [$this->w, $this->h];
	}
	public function attach_handler(Callable $handler) {
		if (!is_object($handler)) {
			$handler = static function (...$a) use ($handler) {
				return $handler(...$a);
			};
		}
		$this->handlers->attach($handler);
		foreach ($this->ents as $id => $ent) {
			$handler(BoardEventType::Spawn, (object) [
				'id' => $id,
				'pos' => $ent->pos,
				'value' => $ent->value,
			]);
			if ($this->won) {
				$handler(BoardEventType::Win, (object) []);
			}
			if ($this->lost) {
				$handler(BoardEventType::Lose, (object) []);
			}
			$handler(BoardEventType::Score, (object) [
				'value' => $this->score,
			]);
		}
		return $handler;
	}
	public function detach_handler(Callable $handler) {
		$this->handlers->detach($handler);
	}
	public function move(Direction $dir) {
		$this->_move([$this, 'handler'], $dir);
	}
	public function get(int $x, int $y) {
		$pos = $this->pos($x, $y);
		$id = $this->board[$pos];
		if ($this->board[$id] == -1) {
			return null;
		}
		return $this->ents[$id]->value;
	}
	public function set(int $x, int $y, ?int $value = null) {
		$pos = $this->pos($x, $y);
		$id = $this->board[$pos];
		if ($id != -1) {
			$this->handler(BoardEventType::Despawn, (object) [
				'id' => $id,
			]);
		}
		if ($value != null) {
			[$id] = array_slice($this->freeds, count($this->freeds) - 1);
			$this->handler(BoardEventType::Spawn, (object) [
				'id' => $id,
				'pos' => [$x, $y],
				'value' => $value,
			]);
		}
	}
}
index.php ASCII text
  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
<?php
include 'game.php';
include 'webutil.php';

ignore_user_abort(true);
define("DIR", getenv("C2K48_TMP_PREFIX") ?: "./tmp/c2k48_");

// the handler never runs in practice but not having one makes the script
// terminate on connection abort. i have no idea why.
$alive = true;
pcntl_signal(SIGTERM, function () {
	global $alive;
	$alive = false;
	error_log("bai!");
});

$chunking = false;

class BlockAnims {
	private $stylist;
	private $stack;
	private $buf;
	private $name;
	private $ents;
	private $t;
	//private $loaded;
	private $game;
	private static function valcolor($v) {
		return [255, floor(max(200 - ((log($v, 2) / 11) ** 1) * 200, 0)), floor(max(120 - ((log($v, 2) / 11) ** 1) * 120, 0))];
	}
	public function __construct(StyleMutator $stylist, string $name, x1p11 $game, Callable $write) {
		[$w, $h] = $game->dimensions();
		$entc = $w * $h;
		$this->stack = [];
		$this->name = $name;
		//$this->loaded=false;
		$this->game = $game;
		$this->stylist = $stylist;
		for ($i = 0; $i < $entc; $i++) {
			$ent = (object) [];
			$elid = $name . dechex($i);
			$elem = "<div class=b id=$elid><div>";
			$ent->name = '#' . $elid;
			$ent->num = new CursedNumber($stylist, $elid . "n", appendf($elem), 5);
			$ent->vis = false;
			$ent->real = ['color' => [0, 0, 0], 'pos' => [0, 0], 'z' => 0, 'value' => 0];
			$ent->fake = $ent->real;
			$elem .= "</div></div>\n";
			$write($elem);
			$this->ents[] = $ent;
		}
		$this->draw(0);
		/*$game->attach_handler(function($type,$event){
				if($this->loaded){
					//$realm="slide";
					switch($type){
					case BoardEventType::Slide:
						$id=$event->id;
						$ent=$this->ents[$id];
						break;
					case BoardEventType::Merge:
						break;
					case BoardEventType::Despawn:
						throw new Exception("unimplemented");
						break;
					case BoardEventType::Spawn:
						//$realm="spawn";
						break;
					}
				}else{
				}
			});
		*/
	}
	private function update(float $dt) {
		if ($dt <= 0) {return;}
		if (count($this->stack) == 0) {return;}
		$this->t += $dt;
	}
	public function draw(float $dt) {
		//$this->update($dt);
		foreach ($this->ents as $id => $ent) {
			$ent->vis = false;
		}
		$this->game->detach_handler($this->game->attach_handler(function ($type, $event) {
			if ($type != BoardEventType::Spawn) {
				return;
			}
			$value = $event->value;
			$pos = $event->pos;
			$ent = $this->ents[$event->id];
			$ent->vis = true;
			$ent->real = ['color' => self::valcolor($value), 'pos' => $pos, 'z' => 0, 'value' => $value];
			$ent->fake = $ent->real;
		}));
		[$w, $h] = $this->game->dimensions();
		$stylist = $this->stylist;
		foreach ($this->ents as $id => $ent) {
			$stylist->set($ent->name, "display", $ent->vis ? 'flex' : 'none');
			$stylist->set($ent->name, "z-index", $ent->fake['z']);
			$stylist->set($ent->name, "justify-content", "center");
			$stylist->set($ent->name, "align-items", "center");
			$stylist->set($ent->name, "position", "absolute");
			$stylist->set($ent->name, "background-color", sprintf("#%02X%02X%02X", ...$ent->fake['color']));
			[$x, $y] = $ent->fake['pos'];
			$stylist->set($ent->name, "left", sprintf("%f%%", ($x / $w) * 100));
			$stylist->set($ent->name, "top", sprintf("%f%%", ($y / $w) * 100));
			$stylist->set($ent->name, "width", sprintf("%f%%", (1 / $w) * 100));
			$stylist->set($ent->name, "height", sprintf("%f%%", (1 / $h) * 100));
			$stylist->set($ent->name, "font-size", "2em");
			$ent->num->draw($ent->fake['value']);
		}
	}
	public function mstart() {
		$this->buf = [];
	}
	public function mend() {
		array_push($this->stack, array_values($this->buf));
	}
}

const MOVES = [
	'u' => Direction::Up,
	'd' => Direction::Down,
	'l' => Direction::Left,
	'r' => Direction::Right,
];

function game(&$quitf) {
	global $alive;
	$uid = bin2hex(random_bytes(8));
	$dir = DIR . hash("sha256", $uid);
	$socket = socket_create(AF_UNIX, SOCK_DGRAM, 0);
	socket_bind($socket, $dir);
	socket_set_nonblock($socket);
	$quitf = function () use (&$socket, &$dir) {
		socket_close($socket);
		unlink($dir);
	};
	chunk_start();
	$styles = "";
	$cons = "";
	$elems = "";
	$statusl = "";
	$stwrite = appendf($styles);
	$stylist = new StyleMutator(callf($stwrite));
	foreach ([
		["l", "&lt;", 1, 2],
		["d", "v", 2, 3],
		["u", "^", 2, 1],
		["r", "&gt;", 3, 2],
	] as [$cmd, $label, $x, $y]) {
		$cons .=
			"<form method=post action=act/$uid/$cmd id=cb$cmd name=cb$cmd target=out></form>" .
			"<div class=conbc id=cbd$cmd><button class=conb form=cb$cmd>$label</button></div>";
		$stylist->set("#cbd$cmd", "grid-row-start", $y);
		$stylist->set("#cbd$cmd", "grid-column-start", $x);
	}
	$statusl .= "<div>";
	$tlab = new CursedNumber($stylist, "tcc", appendf($statusl));
	$statusl .= " fps</div><div id=win>You won!</div><div>score: ";
	$scor = new CursedNumber($stylist, "scc", appendf($statusl));
	$tlab->draw(0);
	$scor->draw(0);
	$game = new x1p11(4, 4);
	$gamer = new BlockAnims($stylist, "gg", $game, appendf($elems));
	[$w, $h] = $game->dimensions();
	$statusl .= "</div>";
	unset($cmd, $label);
	$bvalc = 16;
	unset($i, $elem, $elid, $bval, $bvald, $elnc, $elnid);
	$stylist->set("#win", "display", "none");
	$stylist->set("#die", "display", "none");
	$stylist->present();
	$headch = <<<Eof
	<!DOCTYPE html>
	<head><meta name="viewport" content="width=device-width" /><title>2048.php</title></head>
	<style>
	body,html{width:100%;height:100%;margin:0;padding:0;font-size:min(1em,3vmin)}
	#cont{display:flex;width:100%;height:100%;flex-direction:row;}
	#bcont{flex-grow:1;padding:2em;display:flex;align-items:center;justify-content:center}
	.filler{flex-grow:1}
	#sidec{font-size:1.5em;flex-basis:min(13rem,50vmin);padding:1rem;border-left:solid 1px black;display:flex;flex-direction:column;}
	@media(max-aspect-ratio:1/1){
		#cont{flex-direction:column}
		#sidec{flex-direction:row;border-left:initial;border-top:solid 1px black}
	}
	#bcont2{container-name:bbox;container-type:size;width:100%;height:100%;display:flex;justify-content:center;align-items:center}
	#board{aspect-ratio:$w/$h;border:solid 1px black;position:relative}
	@container bbox (max-aspect-ratio:$w/$h) {#board{width:100%}}
	@container bbox not (max-aspect-ratio:$w/$h) {#board{height:100%}}
	#if{display:none}
	#con{display:grid;aspect-ratio:1;}
	.conbc{width:100%;height:100%;}
	.conb{font-size:1em;width:100%;height:100%}
	form{display:none}
	</style>
	$styles<iframe id=if name=out></iframe>
	<div id=cont>
	<div id=bcont><div id=bcont2><div id=board>
	$elems</div></div></div>
	<div id=sidec>
	<div id=status>$statusl</div>
	<div class=filler></div>
	<span id=die>Game over.</span><div id=con>
	$cons
	</div>
	</div>
	</div>

	Eof;
	unset($styles, $elems, $cons, $statusl);
	$stwrite = 'chunk';
	chunk($headch);
	$timer = new DTimer();
	$score = 0;
	$lost = false;
	$won = false;
	$game->attach_handler(function ($type, $event) use (&$lost, &$won, &$score) {
		switch ($type) {
		case BoardEventType::Score:
			$score += $event->value;
			break;
		case BoardEventType::Win:
			$won = true;
			break;
		case BoardEventType::Lose:
			$lost = true;
			break;
		}
	});
	$t = 0;
	$tt = (int) (1000_000 / 30);
	$hidden = false;
	$hidt = 1;
	$tod = 10;
	$ii = 2;
	while (1) {
		$dt = $timer->tick();
		$t += $dt;
		$hidt -= $dt;
		$tod -= $dt;
		if ($hidt <= 0) {
			$hidden = !$hidden;
			$hidt = 0.5;
		}
		//$stylist->set("#board","display",$hidden?"none":"block");
		//$stylist->set("#board", "width", ((sin($t) + 1) / 2 * 25) . 'em');
		//chunk("<!--".str_repeat("-",4096*1024)."-->"); // stress test
		$buf = '';
		while (socket_recv($socket, $buf, 65536, 0) != false) {
			if (MOVES[$buf]) {
				$game->move(MOVES[$buf]);
				if ($lost) {
					$stylist->set("#con", "display", "none");
					$stylist->set("#die", "display", "initial");
				}
				if ($won) {
					$stylist->set("#win", "display", "initial");
				}
			}
		}
		$tlab->draw(1 / $dt);
		$gamer->draw($dt);
		$scor->draw($score);
		$stylist->present();
		if (connection_aborted() || !$alive) {
			error_log("bye!");
			return;
		}
		if ($lost) {
			break;
		}
		usleep(floor(max($tt - $dt, 0)));
		//if(--$ii==0){ break; }
	}
	/*chunk(<<<Eof
		<meta http-equiv="refresh" content="0">

	*/
	chunk_end();
};
$path = explode('/', $_SERVER["REQUEST_URI"]);
$path = array_values(array_filter($path, function ($e) {
	return $e != '';
}));
$spath = implode('/', $path);
if ($spath == '') {
	echo <<<EOF
	<!DOCTYPE html>
	<head><title>2048</title></head>
	<h1>2048.php</h1>
	<p>An implementation of the popular puzzle game <a href="https://en.wikipedia.org/wiki/2048_(video_game)">2048</a>.</p>
	<p>As it relies heavily on progressive HTML rendering and advanced CSS features (e.g. <code>display: none</code>) it might not work in older web browsers.</p>
	<p><a href="play">Start game</a></p>
	EOF;
} else if ($spath == "play") {
	$quitf = function () {};
	try {
		game($quitf);
	} catch (\Throwable $e) {
		error_log($e);
	} finally {
		$quitf();
	}
} else {
	if ($path[0] == "play") {
		array_shift($path);
	}
	if ($path[0] != "act") {
		echo "404\n";
		return;
	}
	array_shift($path);
	if (count($path) < 2) {
		echo "bad\n";
		return;
	}
	$dir = DIR . hash("sha256", $path[0]);
	$socket = socket_create(AF_UNIX, SOCK_DGRAM, 0);
	socket_sendto($socket, $path[1], strlen($path[1]), 0, $dir);
}
server.php ASCII text
 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
#!/usr/bin/php
<?php
chdir(dirname(realpath($argv[0])));
$cwd = getcwd();
$host = "127.0.0.1";
$port = "4444";
if (count($argv) == 3) {
	$host = $argv[1];
	$port = $argv[2];
} elseif (count($argv) != 1) {
	error_log("invalid argument");
	exit(1);
}
$f = fopen("http.conf", "w");
fwrite($f, <<<Eof
server.document-root = "$cwd"
server.bind = "$host"
server.port = $port
server.stream-response-body = 2
server.modules += ( "mod_cgi", "mod_rewrite" )
url.rewrite-once = ( "^/(.*)" => "/" )
cgi.assign = (".php" => "/usr/bin/php-cgi")
index-file.names = ( "index.php" )
Eof);
fclose($f);
mkdir("tmp");
$httpd = getenv("LIGHTTPD") ?: "/usr/sbin/lighttpd";
system("$httpd -D -f ./http.conf");
webutil.php Unicode text, UTF-8 text
  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
<?php

function chunk_start() {
	global $chunking;
	if ($chunking) {
		throw new Exception("already chunking");
	}

	$chunking = true;
	if (ob_get_level() == 0) {
		ob_start();
	}

	header("Content-type: text/html; charset=utf-8");
	header("X-Content-Type-Options: nosniff");
	header("Transfer-encoding: chunked");
}

function chunk($str) {
	global $chunking;
	if (!$chunking) {
		throw new Exception("not chunking");
	}

	printf("%s\r\n", dechex(strlen($str)));
	printf("%s\r\n", $str);
	ob_flush();
	flush();
	if ($str == '') {
		$chunking = false;
		ob_end_flush();
	}
}

function chunk_end() {
	chunk("");
}

class DTimer {
	private $last;
	public function __construct() {
		$this->last = 0;
		$this->tick();
	}
	public function tick() {
		$cur = hrtime(true);
		$dt = $cur - $this->last;
		$this->last = $cur;
		return $dt / 1000_000_000;
	}
}
function appendf(&$s) {return function ($a) use (&$s) {$s .= $a;};}
function callf(&$f) {return function (...$a) use (&$f) {return $f(...$a);};}

class StyleMutator {
	private $current;
	private $dirty;
	private $write;
	public function __construct(Callable $write, ?StyleMutator $from = null) {
		if (isset($from)) {
			$this->current =  &$from->current;
			$this->dirty =  &$from->dirty;
		} else {
			$this->current = [];
			$this->dirty = [];
		}
		$this->write = $write;
	}
	public function set($i, $k, $v) {
		$this->dirty[$k][$i] = $v;
		if (isset($this->current[$k][$i]) && $this->current[$k][$i] == $v) {
			unset($this->dirty[$k][$i]);
		}
	}
	public function present() {
		$str = "<style>%s</style>\n";
		$byval = [];
		foreach ($this->dirty as $k => $l) {
			foreach ($l as $i => $v) {
				$byval[$k . ":" . $v][] = $i;
			}
		}
		foreach ($byval as $v => $l) {
			$byval[$v] = sprintf("%s{%s}", implode(',', $l), $v);
		}
		($this->write)(sprintf($str, implode('', $byval)));
		foreach ($this->dirty as $k => $l) {
			foreach ($l as $i => $v) {
				$this->current[$k][$i] = $v;
			}
		}
		$this->dirty = [];
		return true;
	}
}

const SI_BIGGER = [
	['k', 1000 ** 1],
	['M', 1000 ** 2],
	['G', 1000 ** 3],
	['T', 1000 ** 4],
	['P', 1000 ** 5],
	['E', 1000 ** 6],
	['Z', 1000 ** 7],
	['Y', 1000 ** 8],
	['R', 1000 ** 9],
	['Q', 1000 ** 10],
];
const SI_SMALLER = [
	['m', 1000 ** -1],
	['ΞΌ', 1000 ** -2],
	['n', 1000 ** -3],
	['p', 1000 ** -4],
	['a', 1000 ** -5],
	['z', 1000 ** -6],
	['y', 1000 ** -7],
	['r', 1000 ** -8],
	['q', 1000 ** -9],
];

function fnumfitweak($n, $m) {
	$dd = max($m - strlen(sprintf("%.0f", $n)) - 1, 0);
	$s = rtrim(sprintf("%.{$dd}f", $n), ".0");
	return $s == '' ? '0' : $s;
}

function fnumfit($n, $m) {
	$p = '';
	$s = fnumfitweak($n, $m);
	foreach (SI_SMALLER as [$vp, $vm]) {
		if (!($n > 0 && $s == 0)) {
			break;
		}
		$p = $vp;
		$s = fnumfitweak($n / $vm, $m - 1);
	}
	if ($p != '') {
		return [$s, $p];
	}
	foreach (SI_BIGGER as [$vp, $vm]) {
		if (strlen($s . $p) <= $m) {
			break;
		}
		$p = $vp;
		$s = fnumfitweak($n / $vm, $m - 1);
	}
	return [$s, $p];
}

class CursedNumber {
	private $stylist;
	private $maxlen;
	private $name;
	private const DIGITS = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, '.' => 's'];
	public function __construct( ? StyleMutator &$stylist = null, ?string $name = null,  ? Callable $write = null, int $maxlen = 5) {
		$this->stylist =  &$stylist;
		$this->maxlen = $maxlen;
		if (isset($stylist)) {
			if (!(isset($name) && isset($write))) {
				throw new Exception("invalid argument");
			}
			$this->name = $name;
			$str = "<span id=$name>";
			$state = "none";
			for ($i = 0; $i < $maxlen; $i++) {
				foreach (self::DIGITS as $v => $d) {
					$en = $this->elname('d', $i, $d);
					$str .= "<span id=$en>$v</span>";
					$this->stylist->set('#' . $en, "display", $state);
				}
			}
			foreach ([...SI_BIGGER, ...SI_SMALLER] as [$d, $v]) {
				$en = $this->elname('p', $d);
				$str .= "<span id=$en>$d</span>";
				$this->stylist->set('#' . $en, "display", $state);
			}
			$str .= "</span>";
			$write($str);
		}
	}
	private function elname($type, ...$l) {
		$name = $this->name;
		switch ($type) {
		case "d" :
			return "{$name}n{$l[0]}{$l[1]}";
		case "p" :
			return "{$name}p{$l[0]}";
		}
	}
	public function draw($n) {
		$n = fnumfit($n, $this->maxlen);
		for ($i = 0; $i < $this->maxlen; $i++) {
			foreach (self::DIGITS as $v => $d) {
				$en = $this->elname('d', $i, $d);
				$state = "none";
				if (isset($n[0][$i]) && $n[0][$i] == $v) {
					$state = "initial";
				}
				$this->stylist->set('#' . $en, "display", $state);
			}
		}
		foreach ([...SI_BIGGER, ...SI_SMALLER] as [$d, $v]) {
			$en = $this->elname('p', $d);
			$state = "none";
			if ($n[1] == $d) {
				$state = "initial";
			}
			$this->stylist->set('#' . $en, "display", $state);
		}
	}
}

entry #4

written by razetime
submitted at
3 likes

guesses
comments 0

post a comment


slide.puzzlescript ASCII text
  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
title 2048
author Friedrich Nietzsche
homepage www.puzzlescript.net

========
OBJECTS
========

Background
#bbada0

Empty
#bbada0

Two
#eee4da #776e65 #bbada0
20000
20000
20000
20010
22222

Four
#eee1c9 #776e65 #bbada0
20000
20000
20000
20100
22222

Eight
#f3b27a #f9f6f2 #bbada0
20000
20000
20000
21000
22222

Sixteen
#f69664 #f9f6f2 #bbada0
20000
20000
20001
20000
22222

ThirtyTwo
#f77c5f #f9f6f2 #bbada0
20000
20000
20010
20000
22222

SixtyFour
#f75f3b #f9f6f2 #bbada0
20000
20000
20100
20000
22222

OneTwoEight
#edcf72 #f9f6f2 #bbada0
20000
20000
21000
20000
22222

TwoFiveSix
#edcc61 #f9f6f2 #bbada0
20000
20001
20000
20000
22222

FiveOneTwo
#edc850 #f9f6f2 #bbada0
20000
20010
20000
20000
22222

OneZeroTwoFour
#edc53f #f9f6f2 #bbada0
20000
20100
20000
20000
22222

TwoZeroFourEight
#edc22e #f9f6f2 #bbada0
20000
21000
20000
20000
22222

=======
LEGEND
=======

. = Background
E = Empty
2 = Two
Spawn = Two or Four
Player = Two and Four and Eight and Sixteen and ThirtyTwo and SixtyFour and OneTwoEight and TwoFiveSix and FiveOneTwo and OneZeroTwoFour and TwoZeroFourEight

=======
SOUNDS
=======

================
COLLISIONLAYERS
================

Background
Empty
Two
Four
Eight
Sixteen
ThirtyTwo
SixtyFour
OneTwoEight
TwoFiveSix
FiveOneTwo
OneZeroTwoFour
TwoZeroFourEight


======
RULES
======

[ > Two | Empty ] -> [ Empty | > Two ]
[ > Four | Empty ] -> [ Empty | > Four ]
[ > Eight | Empty ] -> [ Empty | > Eight ]
[ > Sixteen | Empty ] -> [ Empty | > Sixteen ]
[ > ThirtyTwo | Empty ] -> [ Empty | > ThirtyTwo ]
[ > SixtyFour | Empty ] -> [ Empty | > SixtyFour ]
[ > OneTwoEight | Empty ] -> [ Empty | > OneTwoEight ]
[ > TwoFiveSix | Empty ] -> [ Empty | > TwoFiveSix ]
[ > FiveOneTwo | Empty ] -> [ Empty | > FiveOneTwo ]
[ > OneZeroTwoFour | Empty ] -> [ Empty | > OneZeroTwoFour ]
[ > TwoZeroFourEight | Empty ] -> [ Empty | > TwoZeroFourEight ]

[ > Two | Four ] -> [ Two | Four ]
[ > Two | Eight ] -> [ Two | Eight ]
[ > Two | Sixteen ] -> [ Two | Sixteen ]
[ > Two | ThirtyTwo ] -> [ Two | ThirtyTwo ]
[ > Two | SixtyFour ] -> [ Two | SixtyFour ]
[ > Two | OneTwoEight ] -> [ Two | OneTwoEight ]
[ > Two | TwoFiveSix ] -> [ Two | TwoFiveSix ]
[ > Two | FiveOneTwo ] -> [ Two | FiveOneTwo ]
[ > Two | OneZeroTwoFour ] -> [ Two | OneZeroTwoFour ]
[ > Two | TwoZeroFourEight ] -> [ Two | TwoZeroFourEight ]
[ > Four | Two ] -> [ Four | Two ]

[ > Four | Eight ] -> [ Four | Eight ]
[ > Four | Sixteen ] -> [ Four | Sixteen ]
[ > Four | ThirtyTwo ] -> [ Four | ThirtyTwo ]
[ > Four | SixtyFour ] -> [ Four | SixtyFour ]
[ > Four | OneTwoEight ] -> [ Four | OneTwoEight ]
[ > Four | TwoFiveSix ] -> [ Four | TwoFiveSix ]
[ > Four | FiveOneTwo ] -> [ Four | FiveOneTwo ]
[ > Four | OneZeroTwoFour ] -> [ Four | OneZeroTwoFour ]
[ > Four | TwoZeroFourEight ] -> [ Four | TwoZeroFourEight ]
[ > Eight | Two ] -> [ Eight | Two ]
[ > Eight | Four ] -> [ Eight | Four ]

[ > Eight | Sixteen ] -> [ Eight | Sixteen ]
[ > Eight | ThirtyTwo ] -> [ Eight | ThirtyTwo ]
[ > Eight | SixtyFour ] -> [ Eight | SixtyFour ]
[ > Eight | OneTwoEight ] -> [ Eight | OneTwoEight ]
[ > Eight | TwoFiveSix ] -> [ Eight | TwoFiveSix ]
[ > Eight | FiveOneTwo ] -> [ Eight | FiveOneTwo ]
[ > Eight | OneZeroTwoFour ] -> [ Eight | OneZeroTwoFour ]
[ > Eight | TwoZeroFourEight ] -> [ Eight | TwoZeroFourEight ]
[ > Sixteen | Two ] -> [ Sixteen | Two ]
[ > Sixteen | Four ] -> [ Sixteen | Four ]
[ > Sixteen | Eight ] -> [ Sixteen | Eight ]

[ > Sixteen | ThirtyTwo ] -> [ Sixteen | ThirtyTwo ]
[ > Sixteen | SixtyFour ] -> [ Sixteen | SixtyFour ]
[ > Sixteen | OneTwoEight ] -> [ Sixteen | OneTwoEight ]
[ > Sixteen | TwoFiveSix ] -> [ Sixteen | TwoFiveSix ]
[ > Sixteen | FiveOneTwo ] -> [ Sixteen | FiveOneTwo ]
[ > Sixteen | OneZeroTwoFour ] -> [ Sixteen | OneZeroTwoFour ]
[ > Sixteen | TwoZeroFourEight ] -> [ Sixteen | TwoZeroFourEight ]
[ > ThirtyTwo | Two ] -> [ ThirtyTwo | Two ]
[ > ThirtyTwo | Four ] -> [ ThirtyTwo | Four ]
[ > ThirtyTwo | Eight ] -> [ ThirtyTwo | Eight ]
[ > ThirtyTwo | Sixteen ] -> [ ThirtyTwo | Sixteen ]

[ > ThirtyTwo | SixtyFour ] -> [ ThirtyTwo | SixtyFour ]
[ > ThirtyTwo | OneTwoEight ] -> [ ThirtyTwo | OneTwoEight ]
[ > ThirtyTwo | TwoFiveSix ] -> [ ThirtyTwo | TwoFiveSix ]
[ > ThirtyTwo | FiveOneTwo ] -> [ ThirtyTwo | FiveOneTwo ]
[ > ThirtyTwo | OneZeroTwoFour ] -> [ ThirtyTwo | OneZeroTwoFour ]
[ > ThirtyTwo | TwoZeroFourEight ] -> [ ThirtyTwo | TwoZeroFourEight ]
[ > SixtyFour | Two ] -> [ SixtyFour | Two ]
[ > SixtyFour | Four ] -> [ SixtyFour | Four ]
[ > SixtyFour | Eight ] -> [ SixtyFour | Eight ]
[ > SixtyFour | Sixteen ] -> [ SixtyFour | Sixteen ]
[ > SixtyFour | ThirtyTwo ] -> [ SixtyFour | ThirtyTwo ]

[ > SixtyFour | OneTwoEight ] -> [ SixtyFour | OneTwoEight ]
[ > SixtyFour | TwoFiveSix ] -> [ SixtyFour | TwoFiveSix ]
[ > SixtyFour | FiveOneTwo ] -> [ SixtyFour | FiveOneTwo ]
[ > SixtyFour | OneZeroTwoFour ] -> [ SixtyFour | OneZeroTwoFour ]
[ > SixtyFour | TwoZeroFourEight ] -> [ SixtyFour | TwoZeroFourEight ]
[ > OneTwoEight | Two ] -> [ OneTwoEight | Two ]
[ > OneTwoEight | Four ] -> [ OneTwoEight | Four ]
[ > OneTwoEight | Eight ] -> [ OneTwoEight | Eight ]
[ > OneTwoEight | Sixteen ] -> [ OneTwoEight | Sixteen ]
[ > OneTwoEight | ThirtyTwo ] -> [ OneTwoEight | ThirtyTwo ]
[ > OneTwoEight | SixtyFour ] -> [ OneTwoEight | SixtyFour ]

[ > OneTwoEight | TwoFiveSix ] -> [ OneTwoEight | TwoFiveSix ]
[ > OneTwoEight | FiveOneTwo ] -> [ OneTwoEight | FiveOneTwo ]
[ > OneTwoEight | OneZeroTwoFour ] -> [ OneTwoEight | OneZeroTwoFour ]
[ > OneTwoEight | TwoZeroFourEight ] -> [ OneTwoEight | TwoZeroFourEight ]
[ > TwoFiveSix | Two ] -> [ TwoFiveSix | Two ]
[ > TwoFiveSix | Four ] -> [ TwoFiveSix | Four ]
[ > TwoFiveSix | Eight ] -> [ TwoFiveSix | Eight ]
[ > TwoFiveSix | Sixteen ] -> [ TwoFiveSix | Sixteen ]
[ > TwoFiveSix | ThirtyTwo ] -> [ TwoFiveSix | ThirtyTwo ]
[ > TwoFiveSix | SixtyFour ] -> [ TwoFiveSix | SixtyFour ]
[ > TwoFiveSix | OneTwoEight ] -> [ TwoFiveSix | OneTwoEight ]

[ > TwoFiveSix | FiveOneTwo ] -> [ TwoFiveSix | FiveOneTwo ]
[ > TwoFiveSix | OneZeroTwoFour ] -> [ TwoFiveSix | OneZeroTwoFour ]
[ > TwoFiveSix | TwoZeroFourEight ] -> [ TwoFiveSix | TwoZeroFourEight ]
[ > FiveOneTwo | Two ] -> [ FiveOneTwo | Two ]
[ > FiveOneTwo | Four ] -> [ FiveOneTwo | Four ]
[ > FiveOneTwo | Eight ] -> [ FiveOneTwo | Eight ]
[ > FiveOneTwo | Sixteen ] -> [ FiveOneTwo | Sixteen ]
[ > FiveOneTwo | ThirtyTwo ] -> [ FiveOneTwo | ThirtyTwo ]
[ > FiveOneTwo | SixtyFour ] -> [ FiveOneTwo | SixtyFour ]
[ > FiveOneTwo | OneTwoEight ] -> [ FiveOneTwo | OneTwoEight ]
[ > FiveOneTwo | TwoFiveSix ] -> [ FiveOneTwo | TwoFiveSix ]

[ > FiveOneTwo | OneZeroTwoFour ] -> [ FiveOneTwo | OneZeroTwoFour ]
[ > FiveOneTwo | TwoZeroFourEight ] -> [ FiveOneTwo | TwoZeroFourEight ]
[ > OneZeroTwoFour | Two ] -> [ OneZeroTwoFour | Two ]
[ > OneZeroTwoFour | Four ] -> [ OneZeroTwoFour | Four ]
[ > OneZeroTwoFour | Eight ] -> [ OneZeroTwoFour | Eight ]
[ > OneZeroTwoFour | Sixteen ] -> [ OneZeroTwoFour | Sixteen ]
[ > OneZeroTwoFour | ThirtyTwo ] -> [ OneZeroTwoFour | ThirtyTwo ]
[ > OneZeroTwoFour | SixtyFour ] -> [ OneZeroTwoFour | SixtyFour ]
[ > OneZeroTwoFour | OneTwoEight ] -> [ OneZeroTwoFour | OneTwoEight ]
[ > OneZeroTwoFour | TwoFiveSix ] -> [ OneZeroTwoFour | TwoFiveSix ]
[ > OneZeroTwoFour | FiveOneTwo ] -> [ OneZeroTwoFour | FiveOneTwo ]

[ > OneZeroTwoFour | TwoZeroFourEight ] -> [ OneZeroTwoFour | TwoZeroFourEight ]
[ > TwoZeroFourEight | Two ] -> [ TwoZeroFourEight | Two ]
[ > TwoZeroFourEight | Four ] -> [ TwoZeroFourEight | Four ]
[ > TwoZeroFourEight | Eight ] -> [ TwoZeroFourEight | Eight ]
[ > TwoZeroFourEight | Sixteen ] -> [ TwoZeroFourEight | Sixteen ]
[ > TwoZeroFourEight | ThirtyTwo ] -> [ TwoZeroFourEight | ThirtyTwo ]
[ > TwoZeroFourEight | SixtyFour ] -> [ TwoZeroFourEight | SixtyFour ]
[ > TwoZeroFourEight | OneTwoEight ] -> [ TwoZeroFourEight | OneTwoEight ]
[ > TwoZeroFourEight | TwoFiveSix ] -> [ TwoZeroFourEight | TwoFiveSix ]
[ > TwoZeroFourEight | FiveOneTwo ] -> [ TwoZeroFourEight | FiveOneTwo ]
[ > TwoZeroFourEight | OneZeroTwoFour ] -> [ TwoZeroFourEight | OneZeroTwoFour ]

[ > Two | Two ] -> [ Empty | Four ]
[ > Four | Four ] -> [ Empty | Eight ]
[ > Eight | Eight ] -> [ Empty | Sixteen ]
[ > Sixteen | Sixteen ] -> [ Empty | ThirtyTwo ]
[ > ThirtyTwo | ThirtyTwo ] -> [ Empty | SixtyFour ]
[ > SixtyFour | SixtyFour ] -> [ Empty | OneTwoEight ]
[ > OneTwoEight | OneTwoEight ] -> [ Empty | TwoFiveSix ]
[ > TwoFiveSix | TwoFiveSix ] -> [ Empty | FiveOneTwo ]
[ > FiveOneTwo | FiveOneTwo ] -> [ Empty | OneZeroTwoFour ]
[ > OneZeroTwoFour | OneZeroTwoFour ] -> [ Empty | TwoZeroFourEight ]


random [ Empty ] -> [ random Spawn ]

==============
WINCONDITIONS
==============
Some TwoZeroFourEight

=======
LEVELS
=======

2EEE
EEEE
EEEE
EEEE

entry #5

written by olus2000
submitted at
0 likes

guesses
comments 0

post a comment


2048.lua ASCII text
 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
l=(function()end)w=(function(st)for i=1,(16)do(l)()if(st[i]==
2              *              2              *              2
* 2*256)then(l ) (5)return(12 ) end(l)(6)end l ()return(l)( 1
) end)l("B")o= ( function(s)l ( )for i=1,(16 ) do(l)()if(l) (
) or(not(s[i]) ) then;return( l (false));end ( l)({5,})if(i %
4 ~=0)and(s[i+ 1 -1]==s[i+2-1 ] )then(l)("D" ) return(l)("c "
) elseif(s[i+1 - 1]==s[i+2+2] ) then(l)(9+10 ) return(((l)( )
) )end(l)()end l ()return(556 ) end)function a (s)n=(94627* 0
) +math.random ( 16)if(s[n]or l ())then(a)(s ) else(s)[n]=( 0
*              2              +              0              +
math.random(4)//4*2+2)end(l)()return(s)end(l)()f=(function(s,
m              )              l              (              1
) if(m=="w"and 4 )then(l)()t= { }for x=0,(3. ) do(l)(21)for y
= 0,(3)do(t)[4 * x+y+1]=s[4*y + x+1]end(l)(0 ) end(l)("smig "
) return(t)end l ()if(m==("s" ) )then(l)("s" ) return(f((f( (
s ),"w")),"d") ) elseif((((m) ) =="d"))then( l )()t=({})for x
= 1,(16)do(t)[ x ]=s[17-x]end ; l("2")return ( t)end;return (
( table.move(s , 1,16,1,{}))) ; end)function b (c);l()local x
, s={}l(69)for i =1,(4)do;if( c [i])then;if( c [i]==s)then( l
)              (              -              4              )
table.insert(x,s*2)s=l()else;table.insert(x,s)s=(c[i])end;end
;              l              (              -              1
) end;l("upi") ; table.insert ( x,s)return(x ) end;function g
( s)l("d!")for i =1,16,(4)do; ; table.move(b ( table.move(s ,
i ,i+3,1,{})), 1 ,4,i,s)end(l ) ()return((s) ) end;function d
( _,s)if(o((s) ) )then(l)(426 ) io.write(j,e , "lost!\n")l( 4
) return;end;l ( )if(w(s)and{ } )then(l)()io . write(j,e,p) ;
; return;end;m = ""while(not( ( l()or(m:find ( ("[wasd]"))) )
) )do;l(5)m=io . read(15+-14) : lower()end;t = f(g(f(s,m)), m
)              l              (              9              )
for i=1,(16)do;if(t[i]~=s[i])then;return(a(t))end;end;return(
s              )              ,              6              ,
1 end;j="You"; p ="won!\n"e=" " q=function() ; l();A(r);l(- 2
) return(u(a(a ( {}))))end;l( ) v=(function( ) return(d),l( )
, (q())end);u= ( function(s); ; for x=1,16,( 4 )do;A(z);for y
= 0,(3)do;if(s [ x+y]and(s[x+ y ]//(100)>-0) ) then;l(32)A( B
: format(s[x+y ] //100))else; A ("|",e,e)end ; end;A("|\n") ;
; for y=0,3 do ; if(s[x+y+-0] ) then;l(g)A(B : format(s[x+y ]
% 100))else;;A ( "|",e,e)end; ; end;A("|\n") ; end;l("dummy "
)              A              (              z              )
return(s)end)r="Move by inputting WASD\n"z="+--+--+--+--+\n"e



=" "B="|%2d"A=(io.write)entry=function()for i in v() do;u(i);
end                                                       end

entry #6

written by moshikoi
submitted at
3 likes

guesses
comments 0

post a comment


main.go ASCII text, with CRLF line terminators
  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
package main

import (
	"cmp"
	"image/color"
	"log"
	"math"
	"math/rand"
	"slices"
	"strconv"

	"golang.org/x/image/font"
	"golang.org/x/image/font/opentype"

	"github.com/hajimehoshi/ebiten/v2"
	"github.com/hajimehoshi/ebiten/v2/examples/resources/fonts"
	"github.com/hajimehoshi/ebiten/v2/inpututil"
	"github.com/hajimehoshi/ebiten/v2/text"
)

var (
	tileImage *ebiten.Image
	tileFont  font.Face
)

const (
	fontSize              = 48
	innerTileSize         = 90
	tileSize              = 100
	tileSpeed     float64 = 1

	tilePadding = (tileSize - innerTileSize) / 2
)

type Direction int

const (
	DirectionNone Direction = iota
	DirectionLeft
	DirectionRight
	DirectionUp
	DirectionDown
)

type Tile struct {
	screenPos struct{ x, y float64 }
	value     int
	hasMerged bool
}

type Game struct {
	tiles  [4][4]Tile
	isLoss bool

	pressedKeys []ebiten.Key
}

func init() {
	ttf, err := opentype.Parse(fonts.MPlus1pRegular_ttf)

	if err != nil {
		log.Fatal(err)
	}

	tileFont, err = opentype.NewFace(ttf, &opentype.FaceOptions{
		DPI:     72,
		Size:    fontSize,
		Hinting: font.HintingVertical,
	})

	if err != nil {
		log.Fatal(err)
	}

	tileImage = ebiten.NewImage(innerTileSize, innerTileSize)
}

func (g *Game) updateLoss() {
	copy := *g
	g.isLoss = !(copy.stepTiles(DirectionLeft) ||
		copy.stepTiles(DirectionRight) ||
		copy.stepTiles(DirectionUp) ||
		copy.stepTiles(DirectionDown))
}

func (g *Game) IsFull() bool {
	for _, row := range g.tiles {
		for _, tile := range row {
			if tile.value == 0 {
				return false
			}
		}
	}
	return true
}

func (g *Game) SpawnTile() {
	if g.IsFull() {
		g.isLoss = true
		return
	}

	x := rand.Intn(len(g.tiles))
	y := rand.Intn(len(g.tiles[x]))

	for g.tiles[y][x].value != 0 {
		x = rand.Intn(len(g.tiles))
		y = rand.Intn(len(g.tiles[x]))
	}
	if rand.Intn(10) == 0 {
		g.tiles[y][x].value = 4
	} else {
		g.tiles[y][x].value = 2
	}
}

func (g *Game) stepTiles(direction Direction) (hasChanged bool) {
	switch direction {
	case DirectionLeft:
		for y := range g.tiles {
			for x := 1; x < len(g.tiles[y]); x++ {
				if g.tiles[y][x-1].value == 0 {
					g.tiles[y][x-1] = g.tiles[y][x]
					g.tiles[y][x] = Tile{}
					hasChanged = true
				} else if g.tiles[y][x-1].value == g.tiles[y][x].value && !g.tiles[y][x-1].hasMerged && !g.tiles[y][x].hasMerged {
					g.tiles[y][x-1].value *= 2
					g.tiles[y][x-1].hasMerged = true
					g.tiles[y][x] = Tile{}
					hasChanged = true
				}
			}
		}
	case DirectionRight:
		for y := range g.tiles {
			for x := len(g.tiles[y]) - 2; x >= 0; x-- {
				if g.tiles[y][x+1].value == 0 {
					g.tiles[y][x+1] = g.tiles[y][x]
					g.tiles[y][x] = Tile{}
					hasChanged = true
				} else if g.tiles[y][x+1].value == g.tiles[y][x].value && !g.tiles[y][x+1].hasMerged && !g.tiles[y][x].hasMerged {
					g.tiles[y][x+1].value *= 2
					g.tiles[y][x+1].hasMerged = true
					g.tiles[y][x] = Tile{}
					hasChanged = true
				}
			}
		}
	case DirectionUp:
		for y := 1; y < len(g.tiles); y++ {
			for x := range g.tiles[y] {
				if g.tiles[y-1][x].value == 0 {
					g.tiles[y-1][x] = g.tiles[y][x]
					g.tiles[y][x] = Tile{}
					hasChanged = true
				} else if g.tiles[y-1][x].value == g.tiles[y][x].value && !g.tiles[y-1][x].hasMerged && !g.tiles[y][x].hasMerged {
					g.tiles[y-1][x].value *= 2
					g.tiles[y-1][x].hasMerged = true
					g.tiles[y][x] = Tile{}
					hasChanged = true
				}
			}
		}
	case DirectionDown:
		for y := len(g.tiles) - 2; y >= 0; y-- {
			for x := range g.tiles[y] {
				if g.tiles[y+1][x].value == 0 {
					g.tiles[y+1][x] = g.tiles[y][x]
					g.tiles[y][x] = Tile{}
					hasChanged = true
				} else if g.tiles[y+1][x].value == g.tiles[y][x].value && !g.tiles[y+1][x].hasMerged && !g.tiles[y][x].hasMerged {
					g.tiles[y+1][x].value *= 2
					g.tiles[y+1][x].hasMerged = true
					g.tiles[y][x] = Tile{}
					hasChanged = true
				}
			}
		}
	}

	return
}

func (g *Game) MoveTiles(direction Direction) {
	for y := range g.tiles {
		for x := range g.tiles[y] {
			g.tiles[y][x].hasMerged = false
		}
	}

	for {
		old := g.tiles
		g.stepTiles(direction)
		if slices.Equal(g.tiles[:], old[:]) {
			break
		}
	}
}

func (g *Game) Animate() {
	for y, row := range g.tiles {
		for x := range row {
			var targetX = float64(x*tileSize + tilePadding)
			var targetY = float64(y*tileSize + tilePadding)
			g.tiles[y][x].screenPos.x += float64(cmp.Compare(targetX, g.tiles[y][x].screenPos.x)) * tileSpeed
			g.tiles[y][x].screenPos.y += float64(cmp.Compare(targetY, g.tiles[y][x].screenPos.y)) * tileSpeed
		}
	}
}

func (g *Game) Update() error {
	g.Animate()
	g.pressedKeys = inpututil.AppendJustPressedKeys(g.pressedKeys[:0])

	var direction Direction = DirectionNone

Loop:
	for _, key := range g.pressedKeys {
		switch key {
		case ebiten.KeyLeft:
			direction = DirectionLeft
			break Loop

		case ebiten.KeyRight:
			direction = DirectionRight
			break Loop

		case ebiten.KeyUp:
			direction = DirectionUp
			break Loop

		case ebiten.KeyDown:
			direction = DirectionDown
			break Loop
		}
	}

	if direction != DirectionNone {
		old := g.tiles
		g.MoveTiles(direction)
		if !slices.Equal(g.tiles[:], old[:]) {
			g.SpawnTile()
		}
		g.updateLoss()
	}

	return nil
}

func (g *Game) Draw(screen *ebiten.Image) {
	for _, row := range g.tiles {
		for _, tile := range row {
			drawOptions := ebiten.DrawImageOptions{}
			drawOptions.GeoM.Translate(tile.screenPos.x, tile.screenPos.y)

			tileImage.Fill(color.RGBA{R: uint8(50 * math.Log2(float64(tile.value))), G: 0, B: 0, A: 255})

			if tile.value != 0 {
				str := strconv.Itoa(tile.value)
				textBound := text.BoundString(tileFont, str)

				text.Draw(
					tileImage,
					str,
					tileFont,
					innerTileSize/2-textBound.Dx()/2,
					innerTileSize/2+textBound.Dy()/2,
					color.White,
				)
			}

			screen.DrawImage(tileImage, &drawOptions)
		}
	}

	if g.isLoss {
		str := "You lost"
		textBound := text.BoundString(tileFont, str)
		text.Draw(
			screen,
			str,
			tileFont,
			screen.Bounds().Dx()/2-textBound.Dx()/2,
			screen.Bounds().Dy()/2+textBound.Dy()/2,
			color.White,
		)
	}
}

func (g *Game) Layout(outsideWidth, outsideHeight int) (screenWidth, screenHeight int) {
	return 4 * tileSize, 4 * tileSize
}

func main() {
	ebiten.SetWindowSize(640, 640)
	ebiten.SetWindowTitle("Hello, World!")

	game := Game{}
	game.SpawnTile()

	if err := ebiten.RunGame(&game); err != nil {
		log.Fatal(err)
	}
}

entry #7

written by Olivia
submitted at
5 likes

guesses
comments 0

post a comment


512.rs ASCII text
  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
#!/usr/bin/env -S cargo +nightly -Zscript
//! ```cargo
//! [package]
//! edition = "2021"
//! authors = [ "RocketRace <oliviaspalmu@gmail.com>" ]
//! description = "The game of 2048 for the Esolangs Code Guessing round 42"
//! 
//! [dependencies]
//! rand = "0.8.5"
//! ti = { version = "1.2", git = "https://github.com/RocketRace/ti.git", features = ["images"] }
//! ```
use ::{std::ops::{Index, IndexMut}, rand::{seq::IteratorRandom, thread_rng}, ti::{color::Color, event::{Direction, Event}, screen::{Blit, Screen}, sprite::{Atlas, ColorMode, Sprite}}};

#[derive(Clone, Copy, PartialEq, Default)]
struct Cell {
    value: u8,
    offset: (i16, i16),
    intention: (i16, i16),
    speed: i16
}
impl Cell {
    fn new(value: u8) -> Self {
        Cell { value, ..Default::default() }
    }
}
#[derive(Default, PartialEq, Clone, Copy)]
struct Grid([[Option<Cell>; 4]; 4]);
type Slides = Vec<(u16, u16)>;

impl Index<u16> for Grid {
    type Output = Option<Cell>;
    fn index(&self, index: u16) -> &Self::Output {
        &self.0[index as usize / 4][index as usize % 4]
    }
}
impl IndexMut<u16> for Grid {
    fn index_mut(&mut self, index: u16) -> &mut Self::Output {
        &mut self.0[index as usize / 4][index as usize % 4]
    }
}
impl Grid {
    fn iter(&self) -> impl Iterator<Item = &Cell> {
        self.0.iter().flatten().flatten()
    }
    fn iter_mut(&mut self) -> impl Iterator<Item = &mut Cell> {
        self.0.iter_mut().flatten().flatten()
    }
    fn spawn_food(&mut self) -> Option<()> {
        (0..16)
            .filter(|&i| self[i].is_none())
            .choose(&mut thread_rng())
            .map(|i| self[i] = Some(Cell::new(if rand::random::<f64>() < 0.9 { 1 } else { 2 })))
    }
    fn gravity(&mut self, direction: Direction) -> Option<(Slides, Grid, u32)> {
        let vertical   = [[0, 4, 8, 12], [1, 5, 9, 13], [2, 6, 10, 14], [3,  7,  11, 15]];
        let horizontal = [[0, 1, 2, 3 ], [4, 5, 6, 7 ], [8, 9, 10, 11], [12, 13, 14, 15]];
        let slices = match direction {
            Direction::Right => horizontal.map(reversed),
            Direction::Left  => horizontal,
            Direction::Up    => vertical,
            Direction::Down  => vertical.map(reversed),
        };
    
        let mut buf = Grid::default();
        let mut sliders = vec![(0, 0); 16];
        let mut scored = 0;
        for slice in slices {
            let mut dst = 0;
            for src in 0..4 {
                match (self[slice[src]], buf[slice[dst]]) {
                    (None, _) => (),
                    (Some(n), None) => {
                        buf[slice[dst]] = Some(n);
                        sliders.push((slice[src], (src - dst) as u16));
                    }
                    (Some(n), Some(m)) => {
                        if n.value == m.value {
                            buf[slice[dst]] = Some(Cell::new(n.value + 1));
                            sliders.push((slice[src], (src - dst) as u16));
                            scored += 1 << (n.value + 1);
                        } else {
                            // this can never panic: dst <= src && this match arm is only
                            // possible after executing the previous arm once => dst < 3
                            buf[slice[dst + 1]] = Some(n);
                            sliders.push((slice[src], (src - dst - 1) as u16));
                        }
                        dst += 1;
                    }
                }
            }
        }
        if *self != buf { Some((sliders, buf, scored)) } else { None }
    }
}


fn draw_borders(screen: &mut Screen, offset_x: u16, offset_y: u16, color: Color) {
    screen.draw_sprite(&Sprite::rectangle(18, 18, Some(color), 0), offset_x, offset_y, Blit::Set);
    screen.draw_sprite(&Sprite::rectangle(16, 16, None, 0), offset_x + 1, offset_y + 1, Blit::Subtract);
}

fn draw_cells(screen: &mut Screen, grid: Grid, sprites: &[Sprite], offset_x: u16, offset_y: u16) {
    (0..16).for_each(|i| {
        let (x, y) = (i % 4, i / 4);
        let rgb = (0..=5).choose_multiple(&mut thread_rng(), 3);
        let fuzzy = Sprite::rectangle(4, 4, Some(Color::from_ansi_components(rgb[0], rgb[1], rgb[2])), 1);
        if let Some(Cell {value, offset, .. }) = grid[i] {
            let sprite = sprites.get(value as usize - 1).unwrap_or(&fuzzy);
            screen.draw_sprite(sprite, (x * 4 + offset_x).wrapping_add_signed(offset.0), (y * 4 + offset_y).wrapping_add_signed(offset.1), Blit::Set);
        }
    })
}

fn draw_score(screen: &mut Screen, score: u32, offset_x: u16, offset_y: u16, color: Color) {
    for i in 2..32 {
        screen.draw_pixel_colored(offset_x + i % 2, offset_y + i / 2, if score & (1 << i) != 0 { Blit::Add } else { Blit::Subtract}, Some(color));
    }
}

fn reversed<const N: usize, T>(array: [T; N]) -> [T; N] {
    let mut copy = array;
    copy.reverse();
    copy
}

struct Game {
    grid: Grid,
    next_grid: Grid,
    sliding: bool,
    over: bool,
    won: bool,
    score: u32,
    grid_pos: (u16, u16),
    score_pos: (u16, u16)
}

impl Game {
    fn new(grid_pos: (u16, u16), score_pos: (u16, u16)) -> Self {
        let mut this = Game {
            grid: Grid::default(),
            next_grid: Grid::default(),
            sliding: false,
            over: false,
            won: false,
            score: 0,
            grid_pos,
            score_pos
        };
        this.grid.spawn_food();
        this
    }
    fn tick(&mut self, screen: &mut Screen, event: Option<Event>, best: &mut u32, breath: u8, sprites: &[Sprite]) {
        if !self.sliding {
            if let Some(event) = event {
                if let Some(dir) = event.direction_wasd() {
                    if let Some((sliders, new_grid, scored)) = self.grid.gravity(dir) {
                        self.sliding = true;
                        self.score += scored;
                        *best = (*best).max(self.score);
                        self.next_grid = new_grid;
                        for (slider, cells) in sliders {
                            if let Some(c) = self.grid[slider].as_mut() {
                                let dist = cells as i16 * 4;
                                c.speed = cells as i16;
                                c.intention = match dir {
                                    Direction::Up    => (0, -dist),
                                    Direction::Down  => (0,  dist),
                                    Direction::Right => ( dist, 0),
                                    Direction::Left  => (-dist, 0),
                                };
                            };
                        }
                        if !self.won && self.grid.iter().any(|c| c.value >= 11) {
                            // 2^11 = 2048
                            self.won = true;
                        }
                    }
                    else if !self.over && [Direction::Up, Direction::Down, Direction::Right, Direction::Left].into_iter().all(|dir| self.grid.clone().gravity(dir).is_none()) {
                        self.over = true;
                    }
                } else if let Event::Char('r') = event {
                    self.grid = Grid::default();
                    self.grid.spawn_food();
                    self.grid.spawn_food();
                    self.over = false;
                    self.score = 0;
                }
            }
        }
        else if self.grid.iter_mut().fold(true, |equal, cell| {
            if cell.offset != cell.intention { 
                cell.offset.0 += cell.intention.0.signum() * cell.speed;
                cell.offset.1 += cell.intention.1.signum() * cell.speed;
            }
            equal && cell.offset == cell.intention
        }) {
            self.sliding = false;
            self.grid = self.next_grid;
            self.grid.iter_mut().for_each(|cell| *cell = Cell { value: cell.value, ..Default::default() });
            self.grid.spawn_food();
        }
        
        let playing_color = Color::from_ansi_greyscale(breath / 4 + 6);
        let c = breath * 3 + 112;
        let lost_color    = Color::from_rgb_approximate(c,  64, 64);
        let won_color     = Color::from_rgb_approximate(64, c,  64);
        let score_color   = Color::from_rgb_approximate(c,  64, c );
        let record_color  = Color::from_rgb_approximate(c,  c,  64);
        let border_color = if self.over { if self.won { won_color } else { lost_color }} else { playing_color };
        draw_borders(screen, self.grid_pos.0, self.grid_pos.1, border_color);
        draw_cells(screen, self.grid, sprites, self.grid_pos.0 + 1, self.grid_pos.1 + 1);
        draw_score(screen, self.score, self.score_pos.0, self.score_pos.1, if self.score == *best { record_color } else { score_color });
    }
}

fn main() {
    let mut screen = Screen::new_pixels(54, 24);
    let sprites = Atlas::open("atlas.png", ColorMode::Rgb, true).map(|atlas| (0..16).map(|i| atlas.sprite(i % 4 * 4, i / 4 * 4, 4, 4, 1, 1)).collect::<Vec<Sprite>>()).expect("sprite error");
    
    let mut game = Game::new((1, 3), (22, 4));
    let mut redo = false;
    let mut p2 = Game::new((35, 3), (30, 4));
    let mut best = 0;

    let mut inhaling = true;
    let mut breath = 0;

    screen
        .start_loop(60, |screen, event| {
            if let Some(Event::Char('y')) = event {
                redo = true;
            }
            if inhaling {
                breath += 1; if breath == 47 { inhaling = false; }
            } else {
                breath -= 1; if breath == 0  { inhaling = true;  }
            }
            game.tick(screen, event, &mut best, breath, &sprites);
            if redo {
                p2.tick(screen, event, &mut best, breath, &sprites);
            }
            let best_color = Color::from_rgb_approximate(64, breath * 3 + 112, 64);
            draw_score(screen, best, 26, 4, best_color);
            Ok(())
        })
        .unwrap()
}
atlas.png PNG image data, 16 x 16, 8-bit/color RGBA, non-interlaced
demo.mp4 ISO Media, MP4 Base Media v1 [ISO 14496-12:2003]
instructions ASCII text
1
2
3
4
5
6
7
slide: arrows/WASD
retry: R
exit: ^C
there is no undo feature, it's cheating
redo: Y

use a font with proper braille (example in the RocketRace/ti repository)

entry #8

written by olive
submitted at
1 like

guesses
comments 0

post a comment


main.lua ASCII text, with CRLF line terminators
  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
local floor, ceil = math.floor, math.ceil
local min, max = math.min, math.max

local lg = love.graphics
lg.setColour, lg.setColor = lg.setColor, nil

math.randomseed(os.time())
love.window.setMode(600, 600, { resizable = true })
lg.setFont(lg.newFont(12))

local width, height = 4, 4
local grid = {}

local colours = {
	[ 1] = { 11/11, 11/11, 11/11 },
	[ 2] = { 10/11, 10/11, 10/11 },
	[ 3] = {  9/11,  9/11,  9/11 },
	[ 4] = {  8/11,  8/11,  8/11 },
	[ 5] = {  7/11,  7/11,  7/11 },
	[ 6] = {  6/11,  6/11,  6/11 },
	[ 7] = {  5/11,  5/11,  5/11 },
	[ 8] = {  4/11,  4/11,  4/11 },
	[ 9] = {  3/11,  3/11,  3/11 },
	[10] = {  2/11,  2/11,  2/11 },
	[11] = {  1/11,  1/11,  1/11 },
}
assert(2^11 == 2048)

local function addrandomly()
	local value = math.random(1,2)
	local index repeat
		index = math.random(0,width*height-1)
	until not grid[index]
	grid[index] = value
end

local state = "begin"

local function getr()
	local t = love.timer.getTime()
	local w, h = lg.getDimensions()
	local r = min(w,h)
	local pad = min(60, r*0.1)*(0.98 + 0.2 * math.sin(t/8*math.pi*2))
	local xshif = max(0,floor((w-h)/2))
	local yshif = max(0,floor((h-w)/2))
	return r-pad*2, pad, xshif, yshif
end

local function perr(x,y)
	local r, pad, xshif, yshif = getr()
	x = (x - pad - xshif) / r
	y = (y - pad - yshif) / r
	return x, y
end

local drawers = {
	begin = function()
		lg.setColour(0.80, 0.90, 0.80)
		lg.rectangle("fill", 0,0, 1,1)
	end,
	playing = function()
		local tp = love.timer.getTime()*math.pi*2
		lg.setColour(0.85, 0.85, 0.85+0.05*math.sin(tp/5))
		lg.rectangle("fill", 0,0, 1,1)
		for x = 0, width-1 do
			for y = 0, height-1 do
				local v = grid[x+y*width]
				if v then
					lg.setColour(colours[v])
					lg.rectangle("fill", x*0.25+0.01, y*0.25+0.01, 0.23, 0.23)
					lg.setColour(0,0,0)
					for i = 1, v do
						lg.circle("fill", x*0.25+0.01+0.04*i, y*0.25+0.01+0.04, 0.02)
					end
				end
			end
		end
	end,
	over = function()
		lg.setColour(0.90, 0.80, 0.80)
		lg.rectangle("fill", 0,0, 1,1)
	end,
}

local clickers = {
	begin = function(x,y)
		state = "playing"
		addrandomly()
		addrandomly()
	end,
	playing = function(x,y)
	end,
	over = function(x,y)
		state = "begin"
	end,
}

local keybers = {
	begin = function()
	end,
	playing = function(key)
		
		-- I am ashamed
		
		if key == "left" then
			for y = 0, 3 do
				for x = 1, 3 do
					if grid[x+y*width] then
						for xx = x-1, 0, -1 do
							if not grid[xx+y*width] then
								grid[xx+y*width] = grid[(xx+1)+y*width]
								grid[(xx+1)+y*width] = nil
							elseif grid[xx+y*width] == grid[(xx+1)+y*width] then
								grid[xx+y*width] = grid[xx+y*width] + 1
								grid[(xx+1)+y*width] = nil
								break
							else
								break
							end
						end
					end
				end
			end
		elseif key == "right" then
			for y = 0, 3 do
				for x = 2, 0, -1 do
					if grid[x+y*width] then
						for xx = x+1, 3 do
							if not grid[xx+y*width] then
								grid[xx+y*width] = grid[(xx-1)+y*width]
								grid[(xx-1)+y*width] = nil
							elseif grid[xx+y*width] == grid[(xx-1)+y*width] then
								grid[xx+y*width] = grid[xx+y*width] + 1
								grid[(xx-1)+y*width] = nil
								break
							else
								break
							end
						end
					end
				end
			end
		elseif key == "up" then
			for x = 0, 3 do
				for y = 1, 3 do
					if grid[x+y*width] then
						for yy = y-1, 0, -1 do
							if not grid[x+yy*width] then
								grid[x+yy*width] = grid[x+(yy+1)*width]
								grid[x+(yy+1)*width] = nil
							elseif grid[x+yy*width] == grid[x+(yy+1)*width] then
								grid[x+yy*width] = grid[x+yy*width] + 1
								grid[x+(yy+1)*width] = nil
								break
							else
								break
							end
						end
					end
				end
			end
		elseif key == "down" then
			for x = 0, 3 do
				for y = 2, 0, -1 do
					if grid[x+y*width] then
						for yy = y+1, 3 do
							if not grid[x+yy*width] then
								grid[x+yy*width] = grid[x+(yy-1)*width]
								grid[x+(yy-1)*width] = nil
							elseif grid[x+yy*width] == grid[x+(yy-1)*width] then
								grid[x+yy*width] = grid[x+yy*width] + 1
								grid[x+(yy-1)*width] = nil
								break
							else
								break
							end
						end
					end
				end
			end
		end

		addrandomly()

		local filled = 0
		for i = 0, width*height-1 do
			if grid[i] == 11 then
				state = over
			elseif grid[i] then
				filled = filled + 1
			end
		end
		if filled == width*height then
			state = over
		end
	end,
	over = function()
	end,
}

function love.draw()
	lg.clear(1,1,1)
	do
		local r, pad, xshif, yshif = getr()
		lg.translate(pad, pad)
		lg.translate(xshif, yshif)
		lg.scale(r)
	end

	drawers[state]()
end

function love.mousepressed(x,y)
	clickers[state](perr(x,y))
end

function love.keypressed(key, scancode)
	keybers[state](key, scancode)
end

entry #9

written by ultlang
submitted at
5 likes

guesses
comments 0

post a comment


cg.sb3 Zip archive data, at least v1.0 to extract, compression method=deflate

entry #10

written by JJRubes
submitted at
3 likes

guesses
comments 0

post a comment


2048.c ASCII text, with very long lines (302)
  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
#define _ -1
int board[16] = {
//  +-------+-------+-------+-------+
//  |       |       |       |       |
         -1 ,    -1 ,    -1 ,    -1 ,
//  |       |       |       |       |
//  +-------+-------+-------+-------+
//  |       |       |       |       |
         -1 ,    -1 ,    -1 ,     2 ,
//  |       |       |       |       |
//  +-------+-------+-------+-------+
//  |       |       |       |       |
         -1 ,     2 ,    -1 ,    -1 ,
//  |       |       |       |       |
//  +-------+-------+-------+-------+
//  |       |       |       |       |
         -1 ,    -1 ,    -1 ,    -1 ,
//  |       |       |       |       |
//  +-------+-------+-------+-------+
};

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#ifdef NEW_GAME
#define val(i, j) board[i * 4 + (0 + j)]
#endif
#ifdef LEFT
#define val(i, j) board[i * 4 + (0 + j)]
#endif
#ifdef RIGHT
#define val(i, j) board[i * 4 + (3 - j)]
#endif
#ifdef DOWN
#define val(i, j) board[i + (3 - j) * 4]
#endif
#ifdef UP
#define val(i, j) board[i + (0 + j) * 4]
#endif
#define s(x) #x
#define S(x) #x " " s(x)

#define AA "#define "
#define AB "//  |       |       |       |       |\n"
#define AC "//  +-------+-------+-------+-------+\n"
#define AD int gameOver() {
#define AE for(int i = 0; i < 4; i++) {
#define AF int prevRow = -1; int prevCol = -1;
#define AG for(int j = 0; j < 4; j++) {
#define AL } } return 1; }

#define AM void addRandom() {
#define AN while(1) { int index = rand() % 16;
#define AO if(board[index] == -1) {
#define AP board[index] = rand() % 100 < 90 ? 2 : 4;
#define AQ return; } } }

#define AR int move() {
#define AS int changed = 0;
#define AT for(int i = 0; i < 4; i++) {
#define AU int k = 0;
#define AV for(int j = 1; j < 4; j++) {
#define BD } else { k++;
#define BG } } } } return changed; }

#define BH void newGame() {
#define BI for(int i = 0; i < 16; i++) {
#define BJ board[i] = -1;
#define BK } addRandom(); addRandom(); }

#define BL int main() {
#define BM "//  +------ *** Game Over *** ------+\n"
#define BN char* mid = (gameOver() ? "//  +------ *** Game Over *** ------+\n" : "//  +-------+-------+-------+-------+\n");
#define BO newGame();
#define BP srand(time(((void *)0)));
#define BQ if(move()) addRandom();
#define BR ,
#define BS "%1$s%2$s\nint board[16] = {\n%3$s%4$s%5$11d ,%6$6d ,%7$6d ,%8$6d ,\n"
#define BT "%4$s%3$s%4$s%9$11d ,%10$6d ,%11$6d ,%12$6d ,\n%4$s%3$s%4$s%13$11d ,%14$6d ,%15$6d ,%16$6d ,\n"
#define BU "%4$s%3$s%4$s%17$11d ,%18$6d ,%19$6d ,%20$6d ,\n%4$s%3$s};\n\n"
#define BV "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <time.h>\n"
#define BW "#ifdef NEW_GAME\n#define val(i, j) board[i * 4 + (0 + j)]\n#endif\n"
#define BX "#ifdef LEFT\n#define val(i, j) board[i * 4 + (0 + j)]\n#endif\n"
#define BY "#ifdef RIGHT\n#define val(i, j) board[i * 4 + (3 - j)]\n#endif\n"
#define BZ "#ifdef DOWN\n#define val(i, j) board[i + (3 - j) * 4]\n#endif\n"
#define CA "#ifdef UP\n#define val(i, j) board[i + (0 + j) * 4]\n#endif\n"
#define CB "#define s(x) #x\n#define S(x) #x \" \" s(x)\n\n"
#define CC "%1$s%21$s\n%1$s%22$s\n%1$s%23$s\n%1$s%24$s\n%1$s%25$s\n%1$s%26$s\n"
#define CD "%1$s%27$s\n%1$s%28$s\n\n%1$s%29$s\n%1$s%30$s\n%1$s%31$s\n%1$s%32$s\n"
#define CE "%1$s%33$s\n\n%1$s%34$s\n%1$s%35$s\n%1$s%36$s\n%1$s%37$s\n%1$s%38$s\n"
#define CF "%1$s%39$s\n%1$s%40$s\n\n%1$s%41$s\n%1$s%42$s\n%1$s%43$s\n%1$s%44$s\n\n"
#define CG "%1$s%45$s\n%1$s%46$s\n%1$s%47$s\n%1$s%48$s\n%1$s%49$s\n%1$s%50$s\n#define BR ,\n"
#define CH "%1$s%51$s\n%1$s%52$s\n%1$s%53$s\n%1$s%54$s\n%1$s%55$s\n%1$s%56$s\n"
#define CI "%1$s%57$s\n%1$s%58$s\n%1$s%59$s\n%1$s%60$s\n%1$s%61$s\n"
#define CJ "%1$s%62$s\n%1$s%63$s\n%1$s%64$s\n%1$s%65$s\n%1$s%66$s\n%1$s%67$s\n"
#define CK "%1$s%68$s\n%1$s%69$s\n%1$s%70$s\n%1$s%71$s\n%1$s%72$s\n%1$s%73$s\n"
#define CL "%1$s%74$s\n%1$s%75$s\n%1$s%76$s\n%1$s%77$s\n%1$s%78$s\n%1$s%79$s\n"
#define CM "%1$s%80$s\n%1$s%81$s\n%1$s%82$s\n%1$s%83$s\n%1$s%84$s\n%1$s%85$s\n"
#define CN "%1$s%86$s\n%1$s%87$s\n%1$s%88$s\n%1$s%89$s\n%1$s%90$s\n%1$s%91$s\n"
#define CO "%1$s%92$s\n%1$s%93$s\n%1$s%94$s\n%1$s%95$s\n%1$s%96$s\n%1$s%97$s\n"
#define CP "%1$s%98$s\n%1$s%99$s\n%1$s%100$s\n%1$s%101$s\n%1$s%102$s\n%1$s%103$s\n"
#define CQ "%1$s%104$s\n%1$s%105$s\n%1$s%106$s\n"
#define CR ""
#define CS "AD\nAE\nAF\nAG\nif(val(i, j) == _ || val(i, j) == prevRow) return 0;\nprevRow = val(i, j);\nif(val(j, i) == _ || val(j, i) == prevCol) return 0;\nprevCol = val(j, j);\nAL\nAM\nAN\nAO\nAP\nAQ\nAR\nAS\nAT\n"
#define CT "AU\nAV\nif (val(i, j) == _) continue;\nif (val(i, k) == _) {\nval(i, k) = val(i, j);\nval(i, j) = _; changed = 1;\n} else if (val(i, k) == val(i, j)) {\nval(i, k) += val(i, j);\nval(i, j) = _; k++; changed = 1;\nBD\nval(i, k) = val(i, j);\nif(k != j) { val(i, j) = _;\nBG\nBH\nBI\nBJ\nBK\n"
#define CU "BL\nBN\n#ifdef NEW_GAME\nBO\n#else\nBP\nBQ\n#endif\nprintf(\nBS\nBT\nBU\n"
#define CV "BV\nBW\nBX\nBY\nBZ\nCA\nCB\nCC\nCD\nCE\nCF\nCG\nCH\nCI\nCJ\nCK\nCL\n"
#define CW "CM\nCN\nCO\nCP\nCQ\nCR\nCS\nCT\nCU\nCV\nCW\nCX,\nCY\nCZ\nDA\nDB\nDC\n"
#define CX "DD\nDE\nDF\nDG\nDH\nDI\nDJ\nDK\nDL\nDM\nDN\nDO\nDP\nDQ\nDR\nDS\nDT\nDU);}"
#define CY AA, S(_), AC, AB, board[0], board[1], board[2], board[3], board[4], board[5], board[6],
#define CZ board[7], board[8], board[9], board[10], board[11], board[12], board[13], board[14], board[15], S(AA),
#define DA S(AB), S(AC), S(AD), S(AE), S(AF), S(AG),
#define DB S(AL), S(AM), S(AN), S(AO), S(AP), S(AQ), S(AR), S(AS), S(AT), S(AU),
#define DC S(AV), S(BD),
#define DD S(BG), S(BH), S(BI), S(BJ), S(BK),
#define DE S(BL), S(BM), S(BN), S(BO),
#define DF S(BP), S(BQ), S(BS), S(BT), S(BU), S(BV), S(BW), S(BX), S(BY),
#define DG S(BZ), S(CA), S(CB), S(CC), S(CD), S(CE), S(CF), S(CG), S(CH), S(CI),
#define DH S(CJ), S(CK), S(CL), S(CM), S(CN), S(CO), S(CP), S(CQ), S(CR), S(CS),
#define DI S(CT), S(CU), S(CV), S(CW), S(CX), DK, DL, DM, DN, DO, DP, DQ, DR, DS,
#define DJ DT, DU, DV, S(DK), S(DL), S(DM), S(DN), S(DO), S(DP), S(DQ), S(DR), S(DS), S(DT), S(DU), S(DV),
#define DK "CY AA, S(_), AC, AB, board[0], board[1], board[2], board[3], board[4], board[5], board[6],"
#define DL "CZ board[7], board[8], board[9], board[10], board[11], board[12], board[13], board[14], board[15], S(AA),"
#define DM "DA S(AB), S(AC), S(AD), S(AE), S(AF), S(AG),"
#define DN "DB S(AL), S(AM), S(AN), S(AO), S(AP), S(AQ), S(AR), S(AS), S(AT), S(AU),"
#define DO "DC S(AV), S(BD),"
#define DP "DD S(BG), S(BH), S(BI), S(BJ), S(BK),"
#define DQ "DE S(BL), S(BM), S(BN), S(BO),"
#define DR "DF S(BP), S(BQ), S(BS), S(BT), S(BU), S(BV), S(BW), S(BX), S(BY),"
#define DS "DG S(BZ), S(CA), S(CB), S(CC), S(CD), S(CE), S(CF), S(CG), S(CH), S(CI),"
#define DT "DH S(CJ), S(CK), S(CL), S(CM), S(CN), S(CO), S(CP), S(CQ), S(CR), S(CS),"
#define DU "DI S(CT), S(CU), S(CV), S(CW), S(CX), DK, DL, DM, DN, DO, DP, DQ, DR, DS,"
#define DV "DJ DT, DU, DV, S(DK), S(DL), S(DM), S(DN), S(DO), S(DP), S(DQ), S(DR), S(DS), S(DT), S(DU), S(DV),"
AD
AE
AF
AG
if(val(i, j) == _ || val(i, j) == prevRow) return 0;
prevRow = val(i, j);
if(val(j, i) == _ || val(j, i) == prevCol) return 0;
prevCol = val(j, j);
AL
AM
AN
AO
AP
AQ
AR
AS
AT
AU
AV
if (val(i, j) == _) continue;
if (val(i, k) == _) {
val(i, k) = val(i, j);
val(i, j) = _; changed = 1;
} else if (val(i, k) == val(i, j)) {
val(i, k) += val(i, j);
val(i, j) = _; k++; changed = 1;
BD
val(i, k) = val(i, j);
if(k != j) { val(i, j) = _;
BG
BH
BI
BJ
BK
BL
BN
#ifdef NEW_GAME
BO
#else
BP
BQ
#endif
printf(
BS
BT
BU
BV
BW
BX
BY
BZ
CA
CB
CC
CD
CE
CF
CG
CH
CI
CJ
CK
CL
CM
CN
CO
CP
CQ
CR
CS
CT
CU
CV
CW
CX,
CY
CZ
DA
DB
DC
DD
DE
DF
DG
DH
DI
DJ
DK
DL
DM
DN
DO
DP
DQ
DR
DS
DT
DU);}
Makefile ASCII text
 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
NO_MOVE:
	@echo "use make <direction> to move the board in that direction"
	@echo "or make NEW_GAME to start a new game"

left: LEFT
LEFT:
	@gcc 2048.c -o 2048 -D LEFT -w
	@./2048 > 2048.c
	@head -n 19 2048.c | tail -n 17

right: RIGHT
RIGHT:
	@gcc 2048.c -o 2048 -D RIGHT -w
	@./2048 > 2048.c
	@head -n 19 2048.c | tail -n 17

up: UP
UP:
	@gcc 2048.c -o 2048 -D UP -w
	@./2048 > 2048.c
	@head -n 19 2048.c | tail -n 17

down: DOWN
DOWN:
	@gcc 2048.c -o 2048 -D DOWN -w
	@./2048 > 2048.c
	@head -n 19 2048.c | tail -n 17

new_game: NEW_GAME
NEW_GAME:
	@gcc 2048.c -o 2048 -D NEW_GAME -w
	@./2048 > 2048.c
	@head -n 19 2048.c | tail -n 17

entry #11

written by luatic
submitted at
0 likes

guesses
comments 0

post a comment


dir 42
dir src
main.rs ASCII text
  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
// Simple 2048 game for the terminal

use crossterm::{
    self, cursor,
    event::{read, Event, KeyCode},
    execute, queue, terminal,
};
use rand::Rng;
use std::{
    fmt,
    io::{self, Stdout, Write},
};

#[derive(Copy, Clone, PartialEq)]
enum Move {
    Left,
    Right,
    Up,
    Down,
}

impl TryFrom<KeyCode> for Move {
    type Error = ();
    fn try_from(value: KeyCode) -> Result<Self, Self::Error> {
        match value {
            KeyCode::Left | KeyCode::Char('a') => Ok(Move::Left),
            KeyCode::Right | KeyCode::Char('d') => Ok(Move::Right),
            KeyCode::Up | KeyCode::Char('w') => Ok(Move::Up),
            KeyCode::Down | KeyCode::Char('s') => Ok(Move::Down),
            _ => Err(()),
        }
    }
}

#[derive(PartialEq, Clone)]
struct Board {
    tiles: [[u8; 4]; 4],
}

impl Board {
    fn random_tile() -> u8 {
        if rand::thread_rng().gen_range(1..=10) == 10 {
            2
        } else {
            1
        }
    }
    fn place_random_tile(&mut self) {
        loop {
            let y = rand::thread_rng().gen_range(0..4);
            let x = rand::thread_rng().gen_range(0..4);
            if self.tiles[y][x] == 0 {
                self.tiles[y][x] = Self::random_tile();
                break;
            }
        }
    }
    fn init() -> Self {
        let mut this = Self { tiles: [[0; 4]; 4] };
        this.place_random_tile();
        this.place_random_tile();
        this
    }
    fn transpose(&mut self) {
        let tiles = &mut self.tiles;
        for y in 0..tiles.len() {
            for x in 0..y {
                (tiles[y][x], tiles[x][y]) = (tiles[x][y], tiles[y][x]);
            }
        }
    }
    fn reverse_rows(&mut self) {
        for row in self.tiles.as_mut() {
            row.reverse()
        }
    }
    fn move_left(&mut self) {
        for row in self.tiles.as_mut() {
            for x in 1..4 {
                let mut nx = x;
                while nx > 0 && row[nx - 1] == 0 {
                    nx -= 1;
                }
                if nx > 0 && row[nx - 1] == row[x] {
                    row[nx - 1] += 1;
                    row[x] = 0;
                } else if nx < x {
                    row[nx] = row[x];
                    row[x] = 0;
                }
            }
        }
    }
    fn make_move(&mut self, mov: Move) {
        match mov {
            Move::Left => self.move_left(),
            Move::Right => {
                self.reverse_rows();
                self.move_left();
                self.reverse_rows();
            }
            Move::Up => {
                self.transpose();
                self.move_left();
                self.transpose();
            }
            Move::Down => {
                self.transpose();
                self.reverse_rows();
                self.move_left();
                self.reverse_rows();
                self.transpose();
            }
        }
    }
    fn valid_moves(&self) -> impl Iterator<Item = &Move> {
        [Move::Left, Move::Right, Move::Up, Move::Down]
            .iter()
            .filter(|&&mov| {
                let mut clone = self.clone();
                clone.make_move(mov);
                clone != *self
            })
    }
    fn won(&self) -> bool {
        const TILE_2048: u8 = 11;
        self.tiles.iter().flatten().any(|&t| t == TILE_2048)
    }
}

// TODO (...) the hardcoded carriage returns for raw terminal mode feel dirty.
impl fmt::Display for Board {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let sep: String = "+----".repeat(4) + "+\r\n";
        for row in self.tiles {
            f.write_str(&sep)?;
            f.write_str(
                &(String::from("|")
                    + &row
                        .map(|tile| {
                            if tile == 0 {
                                "    ".into()
                            } else {
                                format!("{:^4}", 1 << tile)
                            }
                        })
                        .join("|")
                    + "|\r\n"),
            )?;
        }
        f.write_str(&sep)?;
        Ok(())
    }
}

struct RawTerminal {
    stdout: Stdout,
}
impl RawTerminal {
    fn init() -> Result<Self, io::Error> {
        terminal::enable_raw_mode()?;
        let mut stdout = io::stdout();
        execute!(
            stdout,
            terminal::EnterAlternateScreen,
            crossterm::cursor::Hide
        )?;
        Ok(Self { stdout })
    }
    fn queue_reset(&mut self) -> Result<(), io::Error> {
        queue!(
            self.stdout,
            terminal::Clear(terminal::ClearType::FromCursorUp),
            cursor::MoveTo(0, 0)
        )
    }
    fn flush(&mut self) -> Result<(), io::Error> {
        self.stdout.flush()
    }
}
impl Drop for RawTerminal {
    fn drop(&mut self) {
        execute!(
            self.stdout,
            crossterm::cursor::Show,
            terminal::LeaveAlternateScreen
        )
        .unwrap();
        terminal::disable_raw_mode().unwrap();
    }
}

enum GameOutcome {
    Win,
    Loss,
    Quit,
}

fn play() -> Result<GameOutcome, io::Error> {
    let mut terminal = RawTerminal::init()?;
    let mut board = Board::init();
    'game: loop {
        terminal.queue_reset()?;
        print!("{board}");
        print!("arrow keys or WASD to play, q to quit");
        terminal.flush()?;
        if board.won() {
            return Ok(GameOutcome::Win);
        }
        let valid_moves: Vec<&Move> = board.valid_moves().collect();
        if valid_moves.is_empty() {
            return Ok(GameOutcome::Loss);
        }
        let mov = loop {
            match read()? {
                Event::Key(event) => {
                    if event.code == KeyCode::Char('q') {
                        return Ok(GameOutcome::Quit);
                    }
                    if let Ok(mov) = Move::try_from(event.code) {
                        if valid_moves.contains(&&mov) {
                            break mov;
                        }
                    }
                }
                Event::Resize(_, _) => {
                    continue 'game;
                }
                _ => (),
            }
        };
        board.make_move(mov);
        board.place_random_tile();
    }
}

fn main() {
    let outcome = play().unwrap();
    println!(
        "{}",
        match outcome {
            GameOutcome::Win => "You win!",
            GameOutcome::Loss => "You lose!",
            GameOutcome::Quit => "quit",
        }
    );
}
Cargo.lock ASCII text
  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
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3

[[package]]
name = "_2048"
version = "0.1.0"
dependencies = [
 "crossterm",
 "rand",
]

[[package]]
name = "autocfg"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"

[[package]]
name = "bitflags"
version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"

[[package]]
name = "bitflags"
version = "2.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4682ae6287fcf752ecaabbfcc7b6f9b72aa33933dc23a554d853aea8eea8635"

[[package]]
name = "cfg-if"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"

[[package]]
name = "crossterm"
version = "0.27.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f476fe445d41c9e991fd07515a6f463074b782242ccf4a5b7b1d1012e70824df"
dependencies = [
 "bitflags 2.4.0",
 "crossterm_winapi",
 "libc",
 "mio",
 "parking_lot",
 "signal-hook",
 "signal-hook-mio",
 "winapi",
]

[[package]]
name = "crossterm_winapi"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b"
dependencies = [
 "winapi",
]

[[package]]
name = "getrandom"
version = "0.2.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be4136b2a15dd319360be1c07d9933517ccf0be8f16bf62a3bee4f0d618df427"
dependencies = [
 "cfg-if",
 "libc",
 "wasi",
]

[[package]]
name = "libc"
version = "0.2.147"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4668fb0ea861c1df094127ac5f1da3409a82116a4ba74fca2e58ef927159bb3"

[[package]]
name = "lock_api"
version = "0.4.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c1cc9717a20b1bb222f333e6a92fd32f7d8a18ddc5a3191a11af45dcbf4dcd16"
dependencies = [
 "autocfg",
 "scopeguard",
]

[[package]]
name = "log"
version = "0.4.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5e6163cb8c49088c2c36f57875e58ccd8c87c7427f7fbd50ea6710b2f3f2e8f"

[[package]]
name = "mio"
version = "0.8.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "927a765cd3fc26206e66b296465fa9d3e5ab003e651c1b3c060e7956d96b19d2"
dependencies = [
 "libc",
 "log",
 "wasi",
 "windows-sys",
]

[[package]]
name = "parking_lot"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3742b2c103b9f06bc9fff0a37ff4912935851bee6d36f3c02bcc755bcfec228f"
dependencies = [
 "lock_api",
 "parking_lot_core",
]

[[package]]
name = "parking_lot_core"
version = "0.9.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "93f00c865fe7cabf650081affecd3871070f26767e7b2070a3ffae14c654b447"
dependencies = [
 "cfg-if",
 "libc",
 "redox_syscall",
 "smallvec",
 "windows-targets",
]

[[package]]
name = "ppv-lite86"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de"

[[package]]
name = "rand"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"
dependencies = [
 "libc",
 "rand_chacha",
 "rand_core",
]

[[package]]
name = "rand_chacha"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
dependencies = [
 "ppv-lite86",
 "rand_core",
]

[[package]]
name = "rand_core"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
dependencies = [
 "getrandom",
]

[[package]]
name = "redox_syscall"
version = "0.3.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "567664f262709473930a4bf9e51bf2ebf3348f2e748ccc50dea20646858f8f29"
dependencies = [
 "bitflags 1.3.2",
]

[[package]]
name = "scopeguard"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"

[[package]]
name = "signal-hook"
version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8621587d4798caf8eb44879d42e56b9a93ea5dcd315a6487c357130095b62801"
dependencies = [
 "libc",
 "signal-hook-registry",
]

[[package]]
name = "signal-hook-mio"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29ad2e15f37ec9a6cc544097b78a1ec90001e9f71b81338ca39f430adaca99af"
dependencies = [
 "libc",
 "mio",
 "signal-hook",
]

[[package]]
name = "signal-hook-registry"
version = "1.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d8229b473baa5980ac72ef434c4415e70c4b5e71b423043adb4ba059f89c99a1"
dependencies = [
 "libc",
]

[[package]]
name = "smallvec"
version = "1.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "62bb4feee49fdd9f707ef802e22365a35de4b7b299de4763d44bfea899442ff9"

[[package]]
name = "wasi"
version = "0.11.0+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"

[[package]]
name = "winapi"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
dependencies = [
 "winapi-i686-pc-windows-gnu",
 "winapi-x86_64-pc-windows-gnu",
]

[[package]]
name = "winapi-i686-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"

[[package]]
name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"

[[package]]
name = "windows-sys"
version = "0.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9"
dependencies = [
 "windows-targets",
]

[[package]]
name = "windows-targets"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c"
dependencies = [
 "windows_aarch64_gnullvm",
 "windows_aarch64_msvc",
 "windows_i686_gnu",
 "windows_i686_msvc",
 "windows_x86_64_gnu",
 "windows_x86_64_gnullvm",
 "windows_x86_64_msvc",
]

[[package]]
name = "windows_aarch64_gnullvm"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8"

[[package]]
name = "windows_aarch64_msvc"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc"

[[package]]
name = "windows_i686_gnu"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e"

[[package]]
name = "windows_i686_msvc"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406"

[[package]]
name = "windows_x86_64_gnu"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e"

[[package]]
name = "windows_x86_64_gnullvm"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc"

[[package]]
name = "windows_x86_64_msvc"
version = "0.48.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538"
Cargo.toml ASCII text
1
2
3
4
5
6
7
8
[package]
name = "_2048"
version = "0.1.0"
edition = "2021"

[dependencies]
rand = "0.8.5"
crossterm = "0.27.0"

entry #12

written by LyricLy
submitted at
6 likes

guesses
comments 0

post a comment


2048.html ASCII text
ClearSans-Bold-webfont.woff Web Open Font Format, TrueType, length 27120, version 1.0
ClearSans-Regular-webfont.woff Web Open Font Format, TrueType, length 26764, version 1.0