Created
December 14, 2012 02:04
-
-
Save anonymous/4281920 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); | |
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, |_i| 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