summaryrefslogtreecommitdiff
path: root/src/main.rs
blob: d698ed4a1a60d43a8f0ae59f08b2df3ce211a29e (plain)
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();
}