right and forward

main
serr 2025-06-25 14:41:20 +03:00
parent 299e45134e
commit 8b47d9904e
3 changed files with 49 additions and 12 deletions

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 2.5 KiB

View File

@ -2,8 +2,18 @@ mod turtle;
use turtle::Turtle; use turtle::Turtle;
fn square(turtle: &mut turtle::Turtle) {
turtle.left(90.0);
turtle.forward(5);
for _ in 0..3 {
turtle.right(90.0);
turtle.forward(5);
}
}
fn main() { fn main() {
let mut turtle = Turtle::new(); let mut turtle = Turtle::new();
turtle.draw_line((50, 50), (200, 200));
square(&mut turtle);
turtle.save("output.png").unwrap(); turtle.save("output.png").unwrap();
} }

View File

@ -8,16 +8,18 @@ type ImgBufU8 = ImageBuffer<Rgb<u8>, Vec<u8>>;
type Colour = Rgb<u8>; type Colour = Rgb<u8>;
type Coord = (i32, i32); type Coord = (i32, i32);
const DEFAULT_WIDTH: u32 = 800; const DEFAULT_WIDTH: u32 = 300;
const DEFAULT_HEIGHT: u32 = 800; const DEFAULT_HEIGHT: u32 = 300;
const DEFAULT_BACKGROUND_COLOUR: Colour = Rgb([255u8, 255u8, 255u8]); const DEFAULT_BACKGROUND_COLOUR: Colour = Rgb([255u8, 255u8, 255u8]);
const DEFAULT_COLOUR: Colour = Rgb([0u8, 0u8, 0u8]); const DEFAULT_COLOUR: Colour = Rgb([0u8, 0u8, 0u8]);
const DEFAULT_POS: Coord = ((DEFAULT_WIDTH as f64/2.0) as i32, (DEFAULT_HEIGHT as f64/2.0) as i32);
pub struct Turtle { pub struct Turtle {
buf: ImgBufU8, buf: ImgBufU8,
colour: Colour, colour: Colour,
pos: Coord, pos: Coord,
angle: f64, step_length: u32,
angle: f64, // угол в радианах
} }
impl Turtle { impl Turtle {
@ -30,7 +32,8 @@ impl Turtle {
Turtle { Turtle {
buf, buf,
colour: DEFAULT_COLOUR, colour: DEFAULT_COLOUR,
pos: (0, 0), pos: DEFAULT_POS,
step_length: 10,
angle: 0.0, angle: 0.0,
} }
} }
@ -39,13 +42,28 @@ impl Turtle {
self.pos self.pos
} }
pub fn draw_line(&mut self, start: Coord, end: Coord) { pub fn angle(&self) -> f64 {
drawing::draw_line_segment_mut( self.angle.to_degrees()
&mut self.buf, }
(start.0 as f32, start.1 as f32),
(end.0 as f32, end.1 as f32), pub fn forward(&mut self, steps_count: u32) {
self.colour let start_pos = self.pos;
);
let dy = self.angle.sin() * steps_count as f64 * self.step_length as f64;
let dx = self.angle.cos() * steps_count as f64 * self.step_length as f64;
self.pos.0 += dx.round() as i32;
self.pos.1 += dy.round() as i32;
self.draw_line(start_pos, self.pos);
}
pub fn right(&mut self, degrees: f64) {
self.angle += degrees.to_radians();
}
pub fn left(&mut self, degrees: f64) {
self.angle -= degrees.to_radians();
} }
pub fn save<P>(&self, output_path: P) -> ImageResult<()> pub fn save<P>(&self, output_path: P) -> ImageResult<()>
@ -54,4 +72,13 @@ impl Turtle {
{ {
self.buf.save(output_path) self.buf.save(output_path)
} }
fn draw_line(&mut self, start: Coord, end: Coord) {
drawing::draw_line_segment_mut(
&mut self.buf,
(start.0 as f32, start.1 as f32),
(end.0 as f32, end.1 as f32),
self.colour
);
}
} }