boggle_maker/
boggle_board.rs

1use rand::distr::{Distribution, Uniform};
2
3///The board struct
4pub struct Board{
5    width : usize,
6    length : usize,
7    value : Vec<char>,
8    score : Option<isize>
9}
10
11impl Board{
12    
13    ///returns new board instance by given char vector and board width, length and score
14    pub fn new(value : Vec<char>, width : usize ,length : usize, score: Option<isize>) -> Self{
15        Self{
16            width : width,
17            length : length,
18            value : value,
19            score : score,
20        }
21    }
22
23    ///gets board's width
24    pub fn width(&self) -> usize{
25        self.width
26    }
27
28    ///gets board's length
29    pub fn length(&self) -> usize{
30        self.length
31    }
32
33    ///gets board's score
34    pub fn score(&self) -> Option<isize>{
35        self.score
36    }
37
38    /// gets board's value
39    pub fn value(&self) -> &Vec<char>{
40        &self.value
41    }
42
43    ///generate a random board by given width and length
44    pub fn new_random(width : usize, length : usize)->Self{
45        let mut brd = Self{
46            width : width,
47            length : length,
48            value : vec![' '; width * length],
49            score : None
50        };
51
52        let uniform = Uniform::try_from(0..26).unwrap();
53        let mut rng = rand::rng();
54
55        for i in 0..width*length {
56            let rnd = uniform.sample(&mut rng);
57            let random_char = (b'A' + rnd) as char;
58            brd.value[i]= random_char;
59        }
60        
61        
62        brd
63    }
64
65    pub fn copy(&self) -> Self{
66        Self{
67            width : self.width,
68            length : self.length,
69            value : self.value.to_vec(),
70            score : self.score,
71        }
72    }
73
74    pub fn to_string(&self)->String{
75        let mut s = String::new();
76        for (i,val) in self.value.iter().enumerate() {
77            if i>0 && i%self.width == 0{
78                s.push('\n');
79            }
80            s.push(*val);
81        }
82
83        s
84    }
85
86    pub fn hash(&self)->String{
87        let mut s = String::new();
88        for val in self.value.iter() {
89            s.push(*val);
90        }
91
92        s
93    }
94
95    ///gets the char located in (i,j)
96    pub fn get(&self, i:usize,j:usize)->Option<char>{
97        if i>=self.width || j>=self.length
98        {
99            return None;
100        }
101        Some(self.value[i* self.width + j])
102    }  
103    
104    ///sets char located in (i,j)
105    pub fn set(&mut self, i:usize,j:usize,ch:char){
106        if !(i>=self.width || j>=self.length)
107        {
108            self.value[i* self.width + j] = ch;
109        }
110    }
111}