Hello everyone,
First of all thank you for being a part of this forum. The rust community has been very welcoming to me and I'm grateful
I'm implementing the Tetris game in rust as an exercise. It goes pretty well, I'm having a lot of fun.
To represent the game's state I chose an array of 210 bytes:
pub struct Game<R, W: Write> {
stdout: W,
stdin: R,
// other content
board: [u8; 210],
}
The width of the game is 10, the indexes of the board's cells look like this:
200 201 202 203 204 205 206 207 208 209
190 191 192 193 194 195 196 197 198 199
// ------
20 21 22 23 24 25 26 27 28 29
10 11 12 13 14 15 16 17 18 19
0 1 2 3 4 5 6 7 8 9
I'm delighted about this data structure, it makes moving the pieces around a breeze.
Every byte of the array get assigned a value. 0 for an empty cell, 1 for a T block, etc. To display it I use Termion by doing:
impl<R: Read, W: Write> Game<R, W> {
fn display_the board(&mut self) {
write!(self.stdout, "{}{}", clear::All, cursor::Goto(1, 1)).unwrap();
// verbose way of iterating because I'm a learner
let mut line_iterator = self.board.chunks(10);
while let Some(line) = line_iterator.next() {
for &cell in line.iter() {
let symbol = match cell {
0 => b" ",
1 => b"T",
2 => b"I",
3 => b"S",
4 => b"Z",
5 => b"O",
6 => b"L",
7 => b"J",
_ => b"X",
};
self.stdout.write(symbol).unwrap();
}
}
self.stdout.flush().unwrap();
}
}
Wwhich works perfectly well but draws my board upside-down :
0 1 2 3 4 5 6 7 8 9
20 21 22 23 24 25 26 27 28 29
10 11 12 13 14 15 16 17 18 19
// ------
190 191 192 193 194 195 196 197 198 199
200 201 202 203 204 205 206 207 208 209
In order to iterate over the line_iterator
(made of array chunks) from end to start, I want to replace the next(&mut self)
iterator method with last(self)
.
Because of the different method signature, I remove the mut
keyword when creating line_iterator
. But rustc tells me:
let line_iterator = self.board.chunks(10);
// ------------- move occurs because `line_iterator` has type
// `std::slice::Chunks<'_, u8>`, which does not implement the `Copy` trait
while let Some(line) = line_iterator.last() {
// ^^^^^^^^^^^^^ value moved here, in previous iteration of loop
Which is too bad. I want to consume the iterator, it seems to be the right thing to do.
Do I have to implement the Copy
trait for this Chunk type, like rustc suggests ? And how do I do that ?
Or am I entirely wrong and there is a much easier way of dealing with this ?
Thanks a lot in advance.