main.rs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. #[macro_use]
  2. extern crate specs_derive;
  3. #[macro_use]
  4. extern crate specs_system_macro;
  5. use ggez::{event::EventHandler, Context, GameError};
  6. use specs::prelude::*;
  7. #[derive(Component)]
  8. pub struct Pos {
  9. x: usize,
  10. y: usize,
  11. }
  12. #[derive(Component)]
  13. pub struct Renderable {
  14. glyph: carpet::CP437,
  15. color: carpet::Color,
  16. }
  17. system_impl! {
  18. Draw(
  19. resource mut board: carpet::Board<carpet::CP437>,
  20. renderable: Renderable,
  21. pos: Pos,
  22. ) {
  23. board.clear();
  24. for (p, r) in (&pos, &renderable).join() {
  25. board.set_with_color([p.x, p.y], r.glyph, r.color);
  26. }
  27. }
  28. }
  29. #[derive(Component)]
  30. pub struct MoveLeft;
  31. system! {
  32. Leftward (
  33. _left: MoveLeft,
  34. mut pos: Pos,
  35. ) {
  36. if pos.x == 0 {
  37. pos.x = 79;
  38. } else {
  39. pos.x -= 1;
  40. }
  41. }
  42. }
  43. struct State {
  44. world: World,
  45. }
  46. impl EventHandler for State {
  47. fn draw(&mut self, ctx: &mut Context) -> Result<(), GameError> {
  48. ggez::graphics::clear(ctx, ggez::graphics::BLACK);
  49. self.world.fetch::<carpet::Board<carpet::CP437>>().draw(ctx)?;
  50. ggez::graphics::present(ctx)
  51. }
  52. fn update(&mut self, _ctx: &mut Context) -> Result<(), GameError> {
  53. Ok(())
  54. }
  55. }
  56. fn main() -> Result<(), GameError> {
  57. let mut game = carpet::GameBuilder::new()
  58. .name("game")
  59. .author("me")
  60. .resource_path({
  61. let base = std::env::var("CARGO_MANIFEST_DIR").unwrap();
  62. let mut path = std::path::PathBuf::from(base);
  63. path.push("resources");
  64. path
  65. })
  66. .tileset("/terminal8x8.jpg", [8, 8])
  67. .map_size(80, 50)
  68. .build()?;
  69. game.register::<Pos>();
  70. game.register::<Renderable>();
  71. game.register::<MoveLeft>();
  72. game.world.print([1, 1], "Hello, world!");
  73. game.world.world
  74. .create_entity()
  75. .with(Pos { x: 40, y: 25 })
  76. .with(Renderable {
  77. glyph: carpet::CP437::from_char('A'),
  78. color: carpet::Color::Blue,
  79. })
  80. .build();
  81. for i in 0..10 {
  82. game.world.world
  83. .create_entity()
  84. .with(Pos { x: i * 7, y: 20 })
  85. .with(Renderable {
  86. glyph: carpet::CP437::from_char('X'),
  87. color: carpet::Color::Red,
  88. })
  89. .with(MoveLeft)
  90. .build();
  91. }
  92. game.run_with_systems(|world| {
  93. Draw.run_now(&world);
  94. Leftward.run_now(&world);
  95. })
  96. }
  97. // Local Variables:
  98. // cargo-process--command-build: "build --release"
  99. // cargo-process--command-run: "run --release --bin ch2"
  100. // End: