Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Slightly more idiomatic code for Conway #2

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions conway/src/ansi.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,16 @@ pub enum Ansi {

impl Ansi {
pub fn csi(&self) {
let seq = match *self {
Ansi::Clear => "2J".to_string(),
Ansi::CursorUp(n) => format!("{}A", n),
Ansi::CursorDown(n) => format!("{}B", n),
Ansi::CursorForward(n) => format!("{}C", n),
Ansi::CursorBack(n) => format!("{}D", n),
Ansi::CursorPos(row, col) => format!("{};{}H", row, col),
Ansi::EraseToEOL => "K".to_string(),
print!("\x1b[");
match *self {
Ansi::Clear => print!("2J"),
Ansi::CursorUp(n) => print!("{}A", n),
Ansi::CursorDown(n) => print!("{}B", n),
Ansi::CursorForward(n) => print!("{}C", n),
Ansi::CursorBack(n) => print!("{}D", n),
Ansi::CursorPos(row, col) => print!("{};{}H", row, col),
Ansi::EraseToEOL => print!("K"),
};
print!("\x1b[{}", seq);
}
}

30 changes: 22 additions & 8 deletions conway/src/conway.rs
Original file line number Diff line number Diff line change
@@ -1,24 +1,38 @@
use std::cmp;
use std::fmt;
use std::mem;

pub const MAP_WIDTH: usize = 40;
pub const MAP_HEIGHT: usize = 30;

type Cell = bool;

#[derive(Copy)]
#[derive(Copy, Clone)]
pub struct Conway {
map: [[Cell; MAP_WIDTH]; MAP_HEIGHT],
}

impl Eq for Conway { }
// We can't derive this, because [T; n] doesn't have an implentation
impl PartialEq for Conway {
fn eq(&self, other: &Conway) -> bool {
for (left_row, right_row) in self.map.iter().zip(other.map.iter()) {
if &left_row[] != &right_row[] {
return false;
}
}
true
}
}

impl Conway {
pub fn new() -> Conway {
Conway {
map: [[false; MAP_WIDTH]; MAP_HEIGHT],
}
}

pub fn init(&mut self, pattern: &Vec<&str>) {
pub fn init(&mut self, pattern: &[&str]) {
let h = pattern.len();
let h0 = (MAP_HEIGHT - h) / 2;
for i in 0..(h) {
Expand All @@ -33,7 +47,8 @@ impl Conway {

/// Iterate to next state. Return false if the state remains unchanged.
pub fn next(&mut self) -> bool {
let mut newmap = [[false; MAP_WIDTH]; MAP_HEIGHT];
// because all items in the new map will be overwritten, it's safe to use uninitialized mem
let mut newmap = Conway { map: unsafe { mem::uninitialized() } };
for i in 0..(MAP_HEIGHT) {
for j in 0..(MAP_WIDTH) {
let mut nlive = 0;
Expand All @@ -44,17 +59,16 @@ impl Conway {
}
}
}
newmap[i][j] = match (self.map[i][j], nlive) {
newmap.map[i][j] = match (self.map[i][j], nlive) {
(true, 2) | (true, 3) => true,
(true, _) => false,
(false, 3) => true,
(false, _) => false,
};
}
}
// let changed = self.map != newmap;
let changed = true;
self.map = newmap;
let changed = *self != newmap;
*self = newmap;
changed
}
}
Expand All @@ -67,7 +81,7 @@ impl fmt::String for Conway {
}
try!(write!(f, "\n"));
}
write!(f, "")
Ok(())
}
}

31 changes: 18 additions & 13 deletions conway/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,24 +1,22 @@
// Uncomment the following line to disable unstable warnings:
// #![allow(unstable)]

extern crate libc;

use std::io;
use std::io::{self, Timer};
use std::thread::Thread;
use std::time::Duration;
use std::sync::mpsc::channel;

use ansi::Ansi;
use conway::Conway;

pub mod ansi;
pub mod conway;

fn start(n: u32, initial: &Vec<&str>) {
fn start(n: u32, initial: &[&str]) {
let (tx, quit_thread) = channel();
Thread::spawn(move || {
let _ = io::stdin().read_line();
unsafe {
libc::exit(0 as libc::c_int);
}
let _ = tx.send(());
});

let mut game = Conway::new();
Expand All @@ -27,13 +25,20 @@ fn start(n: u32, initial: &Vec<&str>) {
Ansi::Clear.csi();
println!("");

for i in 1..(n+1) {
let mut timer = Timer::new().unwrap();
let timer = timer.periodic(Duration::milliseconds(20));

for i in 0..(n) {
Ansi::CursorPos(1, 1).csi();
print!("{}", game);
println!("n = {:<5} Press ENTER to exit", i);
io::timer::sleep(Duration::milliseconds(20));
if !game.next() {
break;
println!("n = {:<5} Press ENTER to exit", i + 1);
select!{
_ = timer.recv() => {
if !game.next() { break; }
},
_ = quit_thread.recv() => {
break;
}
}
}
}
Expand All @@ -51,6 +56,6 @@ fn main() {
" 1 1 ",
" 11 ",
};
start(n, &initial);
start(n, &initial[]);
}