Created
December 23, 2014 18:05
-
-
Save michaelcontento/cdae0a47ec336306ac63 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
use std::fmt; | |
use std::num; | |
struct Point3 { | |
x: f64, | |
y: f64, | |
z: f64, | |
} | |
impl Point3 { | |
fn new(x: f64, y: f64, z: f64) -> Point3 { | |
Point3 { x: x, y: y, z: z} | |
} | |
fn zero() -> Point3 { | |
Point3 { x: 0.0, y: 0.0, z: 0.0 } | |
} | |
fn distance(&self, other: &Point3) -> f64 { | |
let sum = num::pow(other.x - self.x, 2) | |
+ num::pow(other.y - self.y, 2) | |
+ num::pow(other.z - self.z, 2); | |
(sum as f64).sqrt() | |
} | |
} | |
impl std::fmt::Show for Point3 { | |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
write!(f, "({}, {}, {})", self.x, self.y, self.z) | |
} | |
} | |
struct Planet { | |
name: String, | |
position: Point3, | |
} | |
impl Planet { | |
fn new(name: &str, position: Point3) -> Planet { | |
Planet { name: name.to_string(), position: position } | |
} | |
} | |
impl std::fmt::Show for Planet { | |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
write!(f, "{} at {}", self.name, self.position) | |
} | |
} | |
struct Ship { | |
name: String, | |
position: Point3, | |
speed: f64, | |
} | |
impl Ship { | |
fn new(name: &str, position: Point3, speed: f64) -> Ship { | |
Ship { name: name.to_string(), position: position, speed: speed } | |
} | |
fn move_to(&mut self, target: &Point3, timestep: int) { | |
for _ in range(0, timestep) { | |
self.position.x += (target.x - self.position.x) * self.speed; | |
self.position.y += (target.y - self.position.y) * self.speed; | |
self.position.z += (target.z - self.position.z) * self.speed; | |
} | |
} | |
} | |
impl std::fmt::Show for Ship { | |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
write!(f, "{} at {} with speed {}", self.name, self.position, self.speed) | |
} | |
} | |
fn main() { | |
println!("Space! The final frontier!"); | |
let earth = Planet::new("earth", Point3::new(-2.0, 15.0, 27.0)); | |
let sun = Planet::new("sun", Point3::zero()); | |
let mut icarus = Ship::new("icarus", earth.position, 0.2); | |
let mut step_counter: int = 0; | |
while icarus.position.distance(&sun.position) > 1.0 { | |
step_counter += 1; | |
println!("Step {}, distance: {} ({}) ", step_counter, icarus.position.distance(&sun.position), icarus); | |
icarus.move_to(&sun.position, 1); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment