lib.rs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. use ggez::graphics::spritebatch::{SpriteBatch, SpriteIdx};
  2. use ggez::graphics::{DrawParam, Drawable, Image};
  3. use ggez::{Context, GameError};
  4. use specs::WorldExt;
  5. use std::path::Path;
  6. #[derive(Eq, PartialEq, Debug, Copy, Clone)]
  7. pub enum Color {
  8. Red,
  9. Green,
  10. Blue,
  11. }
  12. impl From<Color> for ggez::graphics::Color {
  13. fn from(color: Color) -> ggez::graphics::Color {
  14. match color {
  15. Color::Red => [1.0, 0.0, 0.0, 1.0].into(),
  16. Color::Green => [0.0, 1.0, 0.0, 1.0].into(),
  17. Color::Blue => [0.0, 0.0, 1.0, 1.0].into(),
  18. }
  19. }
  20. }
  21. /// The `Tile` trait is used to identify which tile we care about on a
  22. /// tilesheet, and also to provide a sensible 'blank' tile. The tile
  23. /// identifiers we care about should at least be `Clone`, but often
  24. /// they'll be (wrappers over) small identifiers (like a `u8` or a
  25. /// `u16`) and could probably be `Copy`.
  26. pub trait Tile: Clone + Send + Sync {
  27. fn to_location(self) -> [f32;4];
  28. fn blank() -> Self;
  29. }
  30. /// This represents a character from DOS codepage 437
  31. #[derive(Debug, Copy, Clone)]
  32. pub struct CP437(u8);
  33. impl CP437 {
  34. pub fn from_u8(ch: u8) -> CP437 {
  35. CP437(ch)
  36. }
  37. pub fn from_char(ch: char) -> CP437 {
  38. CP437(match ch as u32 {
  39. // happy faces
  40. 0x263A => 1,
  41. 0x263B => 2,
  42. // card suits
  43. 0x2665 => 3,
  44. 0x2666 => 4,
  45. 0x2663 => 5,
  46. 0x2660 => 6,
  47. 0x2022 => 7,
  48. // fill this in some time later
  49. // standard ASCII mappings
  50. 0x20 ..= 0x7e => ch as u8,
  51. 0x2302 => 0x7f,
  52. _ => panic!("Character {} does not have a CP437 equivalent", ch),
  53. })
  54. }
  55. }
  56. impl Tile for CP437 {
  57. fn to_location(self) -> [f32;4] {
  58. const TILE_SIZE: f32 = 1.0 / 16.0;
  59. let u = f32::from(self.0 % 16) * TILE_SIZE;
  60. let v = f32::from(self.0 / 16) * TILE_SIZE;
  61. [u, v, TILE_SIZE, TILE_SIZE]
  62. }
  63. fn blank() -> Self {
  64. CP437(0)
  65. }
  66. }
  67. pub struct Board<Idx: Tile> {
  68. size: Size,
  69. contents: Vec<(Idx, SpriteIdx)>,
  70. tileset: Tileset<Idx>,
  71. }
  72. pub struct Tileset<Idx: Tile> {
  73. tile_size: Size,
  74. batch: SpriteBatch,
  75. idx: std::marker::PhantomData<Idx>,
  76. }
  77. impl<Idx: Tile> Tileset<Idx> {
  78. pub fn from_file(
  79. ctx: &mut Context,
  80. tile_size: impl Into<Size>,
  81. file: impl AsRef<Path>,
  82. ) -> Result<Tileset<Idx>, GameError> {
  83. let tile_size = tile_size.into();
  84. let image = Image::new(ctx, file)?;
  85. let mut batch = SpriteBatch::new(image);
  86. batch.set_filter(ggez::graphics::FilterMode::Nearest);
  87. Ok(Tileset {
  88. tile_size,
  89. batch,
  90. idx: std::marker::PhantomData,
  91. })
  92. }
  93. fn to_screen(&self, coord: impl Into<Coord>) -> [f32; 2] {
  94. let Coord { x, y } = coord.into();
  95. [
  96. (x * self.tile_size.width) as f32,
  97. (y * self.tile_size.height) as f32,
  98. ]
  99. }
  100. }
  101. #[derive(Debug, PartialEq, Eq, Hash)]
  102. pub struct Size {
  103. width: usize,
  104. height: usize,
  105. }
  106. impl From<[usize; 2]> for Size {
  107. fn from([width, height]: [usize; 2]) -> Size {
  108. Size { width, height }
  109. }
  110. }
  111. #[derive(Debug, PartialEq, Eq, Hash)]
  112. pub struct Coord {
  113. x: usize,
  114. y: usize,
  115. }
  116. impl From<[usize; 2]> for Coord {
  117. fn from([x, y]: [usize; 2]) -> Coord {
  118. Coord { x, y }
  119. }
  120. }
  121. impl<Idx: Tile> Board<Idx> {
  122. pub fn new(size: impl Into<Size>, mut tileset: Tileset<Idx>) -> Board<Idx> {
  123. let size = size.into();
  124. let mut contents = Vec::new();
  125. for y in 0..size.height {
  126. for x in 0..size.width {
  127. let param = DrawParam::new()
  128. .src(Idx::blank().to_location().into())
  129. .dest(tileset.to_screen([x, y]));
  130. let idx = tileset.batch.add(param);
  131. contents.push((Idx::blank(), idx));
  132. }
  133. }
  134. Board {
  135. size,
  136. contents,
  137. tileset,
  138. }
  139. }
  140. // fn sprite_location(ch: u8) -> [f32; 4] {
  141. // let u = f32::from(ch % 16) * TILE_SIZE;
  142. // let v = f32::from(ch / 16) * TILE_SIZE;
  143. // [u, v, TILE_SIZE, TILE_SIZE]
  144. // }
  145. pub fn draw(&self, ctx: &mut Context) -> Result<(), ggez::GameError> {
  146. self.tileset.batch.draw(ctx, DrawParam::new())
  147. }
  148. pub fn set(&mut self, at: impl Into<Coord>, ch: Idx) {
  149. let at = at.into();
  150. let idx = at.x + at.y * self.size.width;
  151. let param = DrawParam::new()
  152. .src(ch.to_location().into())
  153. .dest(self.tileset.to_screen(at));
  154. self.tileset.batch.set(self.contents[idx].1, param).unwrap();
  155. }
  156. pub fn set_with_color(
  157. &mut self,
  158. at: impl Into<Coord>,
  159. ch: Idx,
  160. color: impl Into<ggez::graphics::Color>,
  161. ) {
  162. let at = at.into();
  163. let idx = at.x + at.y * self.size.width;
  164. let param = DrawParam::new()
  165. .src(ch.to_location().into())
  166. .dest(self.tileset.to_screen(at))
  167. .color(color.into());
  168. self.tileset.batch.set(self.contents[idx].1, param).unwrap();
  169. }
  170. pub fn get(&self, at: impl Into<Coord>) -> Idx {
  171. let at = at.into();
  172. let idx = at.x + at.y * self.size.width;
  173. self.contents[idx].0.clone()
  174. }
  175. pub fn clear(&mut self) {
  176. for (n, contents) in self.contents.iter_mut().enumerate() {
  177. let x = n % self.size.width;
  178. let y = n / self.size.width;
  179. let param = DrawParam::new()
  180. .src(Idx::blank().to_location().into())
  181. .dest(self.tileset.to_screen([x, y]));
  182. contents.0 = Idx::blank();
  183. self.tileset.batch.set(contents.1, param).unwrap();
  184. }
  185. }
  186. }
  187. impl Board<CP437> {
  188. pub fn print(&mut self, at: impl Into<Coord>, msg: &str) {
  189. let Coord { x, y } = at.into();
  190. for (idx, ch) in msg.chars().enumerate() {
  191. self.set([idx + x, y], CP437::from_char(ch));
  192. }
  193. }
  194. }
  195. pub struct Game<Idx> {
  196. pub world: specs::World,
  197. idx: std::marker::PhantomData<Idx>,
  198. }
  199. impl<Idx: Tile + 'static> Game<Idx> {
  200. pub fn create(_name: &str, _author: &str, board: Board<Idx>) -> Result<Game<Idx>, ggez::GameError> {
  201. let mut world = specs::World::new();
  202. world.insert(board);
  203. Ok(Game {
  204. world,
  205. idx: std::marker::PhantomData,
  206. })
  207. }
  208. pub fn set(&mut self, at: impl Into<Coord>, ch: Idx) {
  209. self.world.fetch_mut::<Board<Idx>>().set(at, ch)
  210. }
  211. pub fn set_with_color(
  212. &mut self,
  213. at: impl Into<Coord>,
  214. ch: Idx,
  215. color: impl Into<ggez::graphics::Color>,
  216. ) {
  217. self.world
  218. .fetch_mut::<Board<Idx>>()
  219. .set_with_color(at, ch, color)
  220. }
  221. pub fn get(&self, at: impl Into<Coord>) -> Idx {
  222. self.world.fetch::<Board<Idx>>().get(at)
  223. }
  224. }
  225. impl Game<CP437> {
  226. pub fn print(&mut self, at: impl Into<Coord>, msg: &str) {
  227. self.world.fetch_mut::<Board<CP437>>().print(at, msg)
  228. }
  229. }
  230. impl<Idx: 'static + Tile> ggez::event::EventHandler for Game<Idx> {
  231. fn draw(&mut self, ctx: &mut Context) -> Result<(), ggez::GameError> {
  232. ggez::graphics::clear(ctx, ggez::graphics::BLACK);
  233. self.world.fetch::<Board<Idx>>().draw(ctx)?;
  234. ggez::graphics::present(ctx)
  235. }
  236. fn update(&mut self, _ctx: &mut Context) -> Result<(), ggez::GameError> {
  237. Ok(())
  238. }
  239. }