circle/
circle.rs

1extern crate rustty;
2
3use std::time::Duration;
4
5use rustty::{Terminal, Event, HasSize, CellAccessor};
6
7use rustty::ui::{Painter, Dialog, Widget, Alignable, HorizontalAlign, VerticalAlign};
8
9const BLOCK: char = '\u{25AA}';
10
11fn create_optiondlg() -> Dialog {
12    let mut optiondlg = Dialog::new(50, 6);
13    let inc_label = "+ -> Increase Radius";
14    let dec_label = "- -> Decrease Radius";
15    let q_label = "q -> Quit";
16    let inc_pos = optiondlg.window().halign_line(inc_label, HorizontalAlign::Left, 1);
17    let dec_pos = optiondlg.window().halign_line(dec_label, HorizontalAlign::Left, 1);
18    let q_pos = optiondlg.window().halign_line(q_label, HorizontalAlign::Left, 1);
19    optiondlg.window_mut().printline(inc_pos, 1, inc_label);
20    optiondlg.window_mut().printline(dec_pos, 2, dec_label);
21    optiondlg.window_mut().printline(q_pos, 3, q_label);
22    optiondlg.window_mut().draw_box();
23    optiondlg
24}
25
26fn main() {
27    // Create our terminal, dialog window and main canvas
28    let mut term = Terminal::new().unwrap();
29    let mut optiondlg = create_optiondlg();
30    let mut canvas = Widget::new(term.size().0, term.size().1 - 4);
31
32    // Align canvas to top left, and dialog to bottom right
33    optiondlg.window_mut().align(&term, HorizontalAlign::Right, VerticalAlign::Bottom, 0);
34    canvas.align(&term, HorizontalAlign::Left, VerticalAlign::Top, 0);
35
36    let mut radius = 10u32;
37    'main: loop {
38        while let Some(Event::Key(ch)) = term.get_event(Duration::new(0, 0)).unwrap() {
39            match ch {
40                'q' => break 'main,
41                '+' => radius = radius.saturating_add(1),
42                '-' => radius = radius.saturating_sub(1),
43                _ => {}
44            }
45        }
46        // Grab the size of the canvas
47        let (cols, rows) = canvas.size();
48        let (cols, rows) = (cols as isize, rows as isize);
49
50        let (a, b) = (cols / 2, rows / 2);
51
52        // Main render loop, draws the circle to canvas
53        for i in 0..cols * rows {
54            let y = i as isize / cols;
55            let x = i as isize % cols;
56
57            let mut cell = canvas.get_mut(x as usize, y as usize).unwrap();
58
59            if ((x - a).pow(2) / 4 + (y - b).pow(2)) <= radius.pow(2) as isize {
60                cell.set_ch(BLOCK);
61            } else {
62                cell.set_ch(' ');
63            }
64        }
65
66        // draw the canvas, dialog window and swap buffers
67        canvas.draw_into(&mut term);
68        optiondlg.window().draw_into(&mut term);
69        term.swap_buffers().unwrap();
70    }
71}