main.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. #[macro_use] extern crate specs_derive;
  2. #[macro_use] extern crate specs_system_macro;
  3. use ggez::graphics::Drawable;
  4. use specs::prelude::*;
  5. use specs::world::WorldExt;
  6. // * constants
  7. const WIDTH: f32 = 640.0;
  8. const HEIGHT: f32 = 480.0;
  9. const MAX_HP: u32 = 100;
  10. // * utility functions
  11. fn clamp(x: f32, min: f32, max: f32) -> f32 {
  12. if x < min {
  13. min
  14. } else if x > max {
  15. max
  16. } else {
  17. x
  18. }
  19. }
  20. // * components
  21. /// This is a component for things which can appear on the screen
  22. #[derive(Component)]
  23. pub struct Drawn {
  24. sprite: Sprite,
  25. }
  26. /// We only have three things which appear: the player, the hostile
  27. /// red dots, and the green 'collision' that appears when they hit
  28. /// each other
  29. pub enum Sprite {
  30. Player,
  31. Hostile,
  32. Kaboom,
  33. }
  34. impl Sprite {
  35. /// Convert one of the pre-known sprites to is intended visual appearance
  36. fn to_mesh(&self, ctx: &mut ggez::Context) -> ggez::GameResult<ggez::graphics::Mesh> {
  37. match self {
  38. Sprite::Player => {
  39. ggez::graphics::Mesh::new_circle(
  40. ctx,
  41. ggez::graphics::DrawMode::fill(),
  42. [0.0, 0.0],
  43. 10.0,
  44. 0.1,
  45. ggez::graphics::WHITE,
  46. )
  47. },
  48. Sprite::Hostile => {
  49. ggez::graphics::Mesh::new_circle(
  50. ctx,
  51. ggez::graphics::DrawMode::fill(),
  52. [0.0, 0.0],
  53. 10.0,
  54. 0.1,
  55. (1.0, 0.0, 0.0).into(),
  56. )
  57. },
  58. Sprite::Kaboom => {
  59. ggez::graphics::Mesh::new_circle(
  60. ctx,
  61. ggez::graphics::DrawMode::stroke(1.0),
  62. [0.0, 0.0],
  63. 20.0,
  64. 0.1,
  65. (0.0, 1.0, 0.0).into(),
  66. )
  67. },
  68. }
  69. }
  70. }
  71. /// A component for things which can be positioned somewhere on the
  72. /// screen
  73. #[derive(Component, Copy, Clone)]
  74. pub struct Position {
  75. x: f32,
  76. y: f32,
  77. }
  78. impl Position {
  79. /// Lazy collision detection: returns true if the two points are
  80. /// within 20 units of each other
  81. fn close_to(&self, other: &Position) -> bool{
  82. let dx = self.x - other.x;
  83. let dy = self.y - other.y;
  84. (dx * dx + dy * dy).sqrt() < 20.0
  85. }
  86. }
  87. /// A component for things which move around the screen at a specific
  88. /// velocity
  89. #[derive(Component)]
  90. pub struct Velocity {
  91. dx: f32,
  92. dy: f32,
  93. }
  94. /// A component for things which are player-controlled: that is, the
  95. /// player.
  96. #[derive(Component)]
  97. pub struct Controlled;
  98. /// A component for apply damage events
  99. #[derive(Component)]
  100. pub struct AppliesDamage {
  101. target: specs::Entity,
  102. }
  103. /// A component for things which are ephemeral: when lifetime hits 0,
  104. /// the thing is removed
  105. #[derive(Component)]
  106. pub struct Lifetime {
  107. lifetime: usize,
  108. }
  109. #[derive(Component)]
  110. pub struct HP {
  111. hp: u32,
  112. }
  113. // * KeyState impl
  114. /// A KeyState contains four bools that indicate whether particular
  115. /// keys are held (the only four keys we care about, the famous
  116. /// Gamer's Square: W, A, S, and who can forget D?)
  117. pub struct KeyState {
  118. w_pressed: bool,
  119. a_pressed: bool,
  120. s_pressed: bool,
  121. d_pressed: bool,
  122. }
  123. impl KeyState {
  124. /// By default, none of them are held down
  125. fn new() -> KeyState {
  126. KeyState {
  127. w_pressed: false,
  128. a_pressed: false,
  129. s_pressed: false,
  130. d_pressed: false,
  131. }
  132. }
  133. /// On a key-down event, we might flip some to true
  134. fn handle_down(&mut self, kc: winit::VirtualKeyCode) {
  135. if kc == winit::VirtualKeyCode::W {
  136. self.w_pressed = true;
  137. }
  138. if kc == winit::VirtualKeyCode::A {
  139. self.a_pressed = true;
  140. }
  141. if kc == winit::VirtualKeyCode::S {
  142. self.s_pressed = true;
  143. }
  144. if kc == winit::VirtualKeyCode::D {
  145. self.d_pressed = true;
  146. }
  147. }
  148. /// On a key-up event, we might flip some to false
  149. fn handle_up(&mut self, kc: winit::VirtualKeyCode) {
  150. if kc == winit::VirtualKeyCode::W {
  151. self.w_pressed = false;
  152. }
  153. if kc == winit::VirtualKeyCode::A {
  154. self.a_pressed = false;
  155. }
  156. if kc == winit::VirtualKeyCode::S {
  157. self.s_pressed = false;
  158. }
  159. if kc == winit::VirtualKeyCode::D {
  160. self.d_pressed = false;
  161. }
  162. }
  163. }
  164. // * systems
  165. /// The Draw system, which needs access to the ggez context in order
  166. /// to, uh, draw stuff
  167. struct Draw<'t> {
  168. pub ctx: &'t mut ggez::Context,
  169. }
  170. impl<'a, 't> specs::System<'a> for Draw<'t> {
  171. type SystemData = (
  172. // Position and Drawn are for the usual screen entities
  173. specs::ReadStorage<'a, Position>,
  174. specs::ReadStorage<'a, Drawn>,
  175. // HP and Controlled is so we can display the player HP
  176. specs::ReadStorage<'a, HP>,
  177. specs::ReadStorage<'a, Controlled>,
  178. );
  179. fn run(&mut self, (pos, draw, hp, controlled): Self::SystemData) {
  180. // clear to black
  181. ggez::graphics::clear(self.ctx, ggez::graphics::BLACK);
  182. // draw all the drawable things
  183. for (pos, draw) in (&pos, &draw).join() {
  184. let param = ggez::graphics::DrawParam {
  185. dest: [pos.x, pos.y].into(),
  186. ..ggez::graphics::DrawParam::default()
  187. };
  188. draw.sprite.to_mesh(self.ctx).unwrap().draw(self.ctx, param).unwrap();
  189. }
  190. // find the HP of the player and print it on the screen
  191. for (hp, _) in (&hp, &controlled).join() {
  192. let player_hp = format!("HP: {}/{}", hp.hp, MAX_HP);
  193. let display = ggez::graphics::Text::new(player_hp);
  194. display.draw(self.ctx, ([50.0, 50.0],).into()).unwrap();
  195. }
  196. // show it, yo
  197. ggez::graphics::present(self.ctx).unwrap();
  198. }
  199. }
  200. // The Control system is for adjusting the current velocity of things
  201. // based on the current state of the keys. The longer you hold keys,
  202. // the more it'll accelerate, up to some fixed speed (20 units per
  203. // tick)
  204. system!{
  205. Control(resource kc: KeyState, _c: Controlled, mut v: Velocity) {
  206. const SPEEDUP: f32 = 0.2;
  207. if kc.w_pressed {
  208. v.dy -= SPEEDUP;
  209. }
  210. if kc.a_pressed {
  211. v.dx -= SPEEDUP;
  212. }
  213. if kc.s_pressed {
  214. v.dy += SPEEDUP;
  215. }
  216. if kc.d_pressed {
  217. v.dx += SPEEDUP;
  218. }
  219. v.dx = clamp(v.dx, -20.0, 20.0);
  220. v.dy = clamp(v.dy, -20.0, 20.0);
  221. }
  222. }
  223. // This applies friction to components, currently by a global amount
  224. system!{
  225. Slowdown(mut v: Velocity, _c: Controlled) {
  226. const ROUNDING: f32 = 0.01;
  227. const FRICTION: f32 = 0.95;
  228. if v.dx.abs() < ROUNDING {
  229. v.dx = 0.0;
  230. } else {
  231. v.dx *= FRICTION;
  232. }
  233. if v.dy.abs() < ROUNDING {
  234. v.dy = 0.0
  235. } else {
  236. v.dy *= FRICTION;
  237. }
  238. }
  239. }
  240. // This moves components around and handles wrapping them
  241. system!{
  242. Move(mut pos: Position, v: Velocity) {
  243. pos.x += v.dx;
  244. pos.y += v.dy;
  245. if pos.x < 0.0 {
  246. pos.x += WIDTH;
  247. } else if pos.x > WIDTH {
  248. pos.x -= WIDTH;
  249. }
  250. if pos.y < 0.0 {
  251. pos.y += HEIGHT;
  252. } else if pos.y > HEIGHT {
  253. pos.y -= HEIGHT;
  254. }
  255. }
  256. }
  257. // This naively handles collision detection in a shitty way that
  258. // would never scale for anything real
  259. system_impl!{
  260. Collision(
  261. en: Entity,
  262. mut pos: Position,
  263. hp: HP,
  264. mut lifetime: Lifetime,
  265. mut drawn: Drawn,
  266. mut damage: AppliesDamage,
  267. ) {
  268. let mut seen = std::collections::HashMap::new();
  269. // just compare every entity to every other one
  270. for (e1, p1, _) in (&en, &pos, &hp).join() {
  271. for (e2, p2, _) in (&en, &pos, &hp).join() {
  272. // don't collide with ourselves, that's stupid
  273. if e1 == e2 {
  274. continue;
  275. }
  276. // if they're close and we haven't already looked at
  277. // this one (which we might have!) then add it to the
  278. // set of collisions
  279. if p1.close_to(p2) && !seen.contains_key(&(e1, e2)) {
  280. seen.insert((e1, e2), p1.clone());
  281. }
  282. }
  283. }
  284. // now, for each collision
  285. for ((e1, e2), p) in seen {
  286. // create the kaboom graphic! it'll only last 10 ticks,
  287. // such is the nature of kabooms. (this should probably be
  288. // split apart into another system, but whatevs)
  289. let ping = en.create();
  290. lifetime.insert(ping, Lifetime { lifetime: 10 }).unwrap();
  291. drawn.insert(ping, Drawn { sprite: Sprite::Kaboom }).unwrap();
  292. pos.insert(ping, p).unwrap();
  293. // and create the damage events
  294. let ev1 = en.create();
  295. damage.insert(ev1, AppliesDamage { target: e1 }).unwrap();
  296. let ev2 = en.create();
  297. damage.insert(ev2, AppliesDamage { target: e2 }).unwrap();
  298. }
  299. }
  300. }
  301. // This handles lifetimes ticking back down, and removing entities if
  302. // their lifetimes get too low
  303. system_impl! {
  304. TheInexorablePassageOfTime(en: Entity, mut l: Lifetime) {
  305. for (e, mut l) in (&en, &mut l).join() {
  306. l.lifetime -= 1;
  307. if l.lifetime == 0 {
  308. en.delete(e).unwrap();
  309. }
  310. }
  311. }
  312. }
  313. // This handles applying damage to entities, and removing them if
  314. // their HP gets too low.
  315. system_impl! {
  316. TheSlingsAndArrowsOfOutrageousFortune(
  317. en: Entity,
  318. mut dmg: AppliesDamage,
  319. mut hp: HP,
  320. ) {
  321. for dmg in (&dmg).join() {
  322. if let Some(target) = hp.get_mut(dmg.target) {
  323. target.hp -= 1;
  324. if target.hp == 0 {
  325. en.delete(dmg.target).unwrap();
  326. }
  327. }
  328. }
  329. dmg.clear();
  330. }
  331. }
  332. // * game definition
  333. /// A game just needs a specs world! All our state is in there
  334. struct MyGame {
  335. pub world: specs::World,
  336. }
  337. impl MyGame {
  338. fn setup() -> MyGame {
  339. // this is the first step in making apple pie from scratch
  340. let mut world = specs::World::new();
  341. // register some component types
  342. world.register::<Position>();
  343. world.register::<Drawn>();
  344. world.register::<Controlled>();
  345. world.register::<Velocity>();
  346. world.register::<HP>();
  347. world.register::<Lifetime>();
  348. world.register::<AppliesDamage>();
  349. // create our blank key state
  350. world.insert(KeyState::new());
  351. // create a player
  352. world.create_entity()
  353. .with(Drawn { sprite: Sprite::Player })
  354. .with(Position { x: 200.0, y: 200.0 })
  355. .with(Controlled)
  356. .with(Velocity { dx: 0.0, dy: 0.0 })
  357. .with(HP { hp: MAX_HP })
  358. .build();
  359. // create ten ENEMY ORBS!!!!!!!11111one
  360. for _ in 0..10 {
  361. let x = rand::random::<f32>() * WIDTH;
  362. let y = rand::random::<f32>() * HEIGHT;
  363. let dx = (rand::random::<f32>() * 20.0) - 10.0;
  364. let dy = (rand::random::<f32>() * 20.0) - 10.0;
  365. world.create_entity()
  366. .with(Drawn { sprite: Sprite::Hostile })
  367. .with(Position { x, y })
  368. .with(Velocity { dx, dy })
  369. .with(HP { hp: 50 })
  370. .build();
  371. }
  372. // this is the world I have created. observe it and despair
  373. MyGame { world }
  374. }
  375. }
  376. impl ggez::event::EventHandler for MyGame {
  377. // To draw things, we just run the Draw system
  378. fn draw(&mut self, ctx: &mut ggez::Context) -> ggez::GameResult<()> {
  379. Draw { ctx }.run_now(&self.world);
  380. Ok(())
  381. }
  382. // To update things, we just run a bunch of these systems, and
  383. // make sure we call maintain
  384. fn update(&mut self, _ctx: &mut ggez::Context) -> ggez::GameResult<()> {
  385. TheSlingsAndArrowsOfOutrageousFortune.run_now(&self.world);
  386. Slowdown.run_now(&self.world);
  387. Control.run_now(&self.world);
  388. Move.run_now(&self.world);
  389. Collision.run_now(&self.world);
  390. TheInexorablePassageOfTime.run_now(&self.world);
  391. self.world.maintain();
  392. Ok(())
  393. }
  394. // to handle events, we modify the stored KeyState resource
  395. fn key_down_event(
  396. &mut self,
  397. ctx: &mut ggez::Context,
  398. keycode: winit::VirtualKeyCode,
  399. _keymod: ggez::event::KeyMods,
  400. _repeat: bool,
  401. ) {
  402. if keycode == winit::VirtualKeyCode::Escape {
  403. ggez::event::quit(ctx);
  404. }
  405. KeyState::handle_down(&mut self.world.write_resource(),
  406. keycode);
  407. }
  408. fn key_up_event(
  409. &mut self,
  410. _ctx: &mut ggez::Context,
  411. keycode: winit::VirtualKeyCode,
  412. _keymod: ggez::event::KeyMods,
  413. ) {
  414. KeyState::handle_up(&mut self.world.write_resource(),
  415. keycode);
  416. }
  417. }
  418. // * main
  419. fn main() -> ggez::GameResult<()> {
  420. // And here, we make a context and an event loop
  421. let (mut ctx, mut evloop) = ggez::ContextBuilder::new("game", "me")
  422. // make our window a, uh, size
  423. .window_mode(ggez::conf::WindowMode {
  424. width: WIDTH,
  425. height: HEIGHT,
  426. ..ggez::conf::WindowMode::default()
  427. })
  428. // and build it
  429. .build()?;
  430. // then run the shit yo
  431. let mut my_game = MyGame::setup();
  432. ggez::event::run(&mut ctx, &mut evloop, &mut my_game)
  433. }