Skip to content

Instantly share code, notes, and snippets.

@pcwalton
Created December 14, 2012 20:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pcwalton/4288478 to your computer and use it in GitHub Desktop.
Save pcwalton/4288478 to your computer and use it in GitHub Desktop.
// Original version: http://play.golang.org/p/ebO20f-eax
// Requires Rust 0.5.
extern mod std;
use io::WriterUtil;
const WIDTH: uint = 76;
const HEIGHT: uint = 10;
const NUM_BALLS: uint = 10;
struct Screen([[char * 76] * 10]);
impl Screen {
fn print(&self) {
io::print("\x1b[2J\x1b[;H"); // magic ANSI incantation to clear the screen
for self.each |row| {
for row.each |&ch| {
io::stdout().write_char(ch);
}
io::println("");
}
}
fn paint(&mut self, x: int, y: int, b: char) {
self[y][x] = b
}
}
struct Ball {
x: int, y: int,
xd: int, yd: int
}
impl Ball {
static fn new() -> Ball {
Ball {
x: rand::random() % WIDTH as int,
y: rand::random() % HEIGHT as int,
xd: (rand::random() % 2 * 2) as int - 1,
yd: (rand::random() % 2 * 2) as int - 1,
}
}
fn move_around(&mut self) {
move_bounce(&mut self.x, &mut self.xd, WIDTH as int);
move_bounce(&mut self.y, &mut self.yd, HEIGHT as int);
}
}
fn move_bounce(v: &mut int, d: &mut int, max: int) {
*v += *d;
if *v < 0 {
*v = -*v;
*d = -*d;
} else if *v >= max {
*v = max - 2 - (*v - max);
*d = -*d;
}
}
fn main() {
let mut balls = vec::from_fn(NUM_BALLS, |_| Ball::new());
loop {
let mut screen = Screen([ [ ' ', ..76 ], ..10 ]);
for vec::each_mut(balls) |ball| {
ball.move_around();
screen.paint(ball.x, ball.y, '*');
}
screen.print();
std::timer::sleep(std::uv_global_loop::get(), 1000 / 20);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment