aboutsummaryrefslogtreecommitdiff
path: root/src/tetris.rs
blob: cd882319da79ddc1e14b1f3fb9e146b605c2549d (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
pub mod piece;

#[derive(Debug)]
pub struct Tetris {
    grid: Vec<Vec<i8>>
}
impl Tetris {
    pub fn new() -> Tetris {
        Tetris{
            grid: vec!(vec!(0; 10); 20),
        }
    }

    // Return the grid
    pub fn return_grid(&self) -> &Vec<Vec<i8>> {
        &self.grid
    }

    // Set the grid at a Pos
    pub fn set_grid(&mut self, pos: piece::Pos, value: i8) {
        if self.get_grid_pos(pos) != value {
            self.grid[pos.0 as usize][pos.1 as usize] = value
        }
    }

    // Check each row of the grid
    // If one is full, remove it and drop
    // the rest of the grid down
    pub fn check_lines(&mut self) {
        // While there are full lines, continue to iterate
        let mut row = 19;
        while row > 0 {
            let mut c = 0;
            for x in self.grid.get(row as usize).expect("Out of bounds") {
                if *x == 1 {
                    c += 1;
                } else {
                    row -= 1;
                    continue
                }
            }

            // If the line is full remove it and
            // move everything down
            if c == 10 {
                self.grid.remove(row as usize);
                self.grid.insert(0, vec![0; 10]);
                continue;
            }

            row -= 1;
        }
    }

    pub fn get_grid_pos(&self, pos: piece::Pos) -> i8 {
        match self.grid.get(pos.0 as usize) {
            None => return 0,
            _ => return *self.grid.get(pos.0 as usize).unwrap()
            .get(pos.1 as usize).unwrap_or(&0)
        }
    }
}