Hi.
I am wondering why this happens about my code.
I am building a battleship game on console. And my struggling was to paint the points on board.
This is the code doesnt work:
I understand the error: "table has a reference, cant be moved"
//find_free_spot has reference
if let Some(result) = table.find_free_spot(){
table.change_state(result);//signature is (&mut self)
}
But I dont understand this behaviour.
match table.can_be_road((free_spot.x, free_spot.y), spots, direction){
Ok(points) => {
table.change_state(points.iter().collect());
return Ok(points);
},
Err(why) => continue,
};
This signature also moves change_state(& mut self)
the reference, and table_can_be_road(&self)
also takes an inmutable the reference. Why this happens?
In the first example, doesnt work because was moved, and second seems the same, but it works.
My idea is: when you open a scope with {}
inside a match, it seems another scope or something like that.
This is not for help, because works, but I dont know why it works :=)
this is the code:
pub fn points_from_root_point(table: & mut Table, spots: i8) -> Result<Vec<Point>, String>{
let directions = Direction::get_directions();
let opportunities = 10;
for _time in 0..opportunities{
let free_spot = match User::find_free_point(table){
Some(point) => point,
None => panic!("There are any spots free")
};
for direction in directions.iter(){
match table.can_be_road((free_spot.x, free_spot.y), spots, direction){
Ok(points) => {
table.change_state(points.iter().collect());
return Ok(points);
},
Err(why) => continue,
};
}
}
return Err(format!("Any directions were sufficient to draw from root point"));
}
//--------------------------------------------
pub fn can_be_road(&self, from: (i8,i8), spots: i8, direction: &Direction) -> Result<Vec<Point>,String>{
let dir = direction.get_vector();
let points = (0..spots).map(|item| {
let mut position = Point::new(0, 0);
position.x = from.0 + dir.0*item;
position.y = from.1 + dir.1*item;
position
}).collect::<Vec<Point>>();
let feasible = points.iter().all(|item| self.can_put(&item));
match feasible{
true => Ok(points),
false=>Err(format!("Some points in the road are not feasible to draw"))
}
}
//------------------------------------------------
//and this is the change_state
pub fn change_state(&mut self,points: Vec<&Point>){
for point in points{
if let Ok(point) = self.get_mut_point(point.x,point.y){
point.is_active = true;
};
}
}
```