]> git.lizzy.rs Git - rs2048.git/blob - src/main.rs
Add score display
[rs2048.git] / src / main.rs
1 pub mod display;
2 pub mod game;
3
4 use crossterm::{cursor, event, execute, queue, style, terminal};
5 use game::{Board, Dir::*, Pos};
6 use std::io::Write;
7
8 fn main() {
9     let mut rng = rand::thread_rng();
10
11     let mut stdout = std::io::stdout();
12     queue!(stdout, terminal::EnterAlternateScreen, cursor::Hide).unwrap();
13
14     terminal::enable_raw_mode().unwrap();
15
16     let board = Board::new(Pos::new(4, 4));
17     board.spawn(&mut rng);
18     board.spawn(&mut rng);
19
20     let mut score = 0;
21
22     loop {
23         queue!(
24             stdout,
25             terminal::Clear(terminal::ClearType::All),
26             cursor::MoveTo(0, 0),
27             style::SetAttribute(style::Attribute::Bold),
28             style::Print("Score: ".to_string()),
29             style::SetAttribute(style::Attribute::Reset),
30             style::Print(score.to_string()),
31             cursor::MoveToNextLine(1),
32         )
33         .unwrap();
34         display::display_board(&mut stdout, &board).unwrap();
35         stdout.flush().unwrap();
36
37         if let Ok(evt) = event::read() {
38             match evt {
39                 event::Event::Key(event::KeyEvent { code, .. }) => match code {
40                     event::KeyCode::Char(ch) => {
41                         if let Some(sc) = board.step(match ch.to_ascii_lowercase() {
42                             'w' => Up,
43                             'a' => Left,
44                             's' => Down,
45                             'd' => Right,
46                             'q' => break,
47                             _ => continue,
48                         }) {
49                             score += sc;
50                             board.spawn(&mut rng);
51                         }
52                     }
53                     _ => {}
54                 },
55                 _ => {}
56             }
57         } else {
58             break;
59         }
60     }
61
62     terminal::disable_raw_mode().unwrap();
63     execute!(stdout, cursor::Show, terminal::LeaveAlternateScreen).unwrap();
64 }