环境
- Time 2022-11-29
- WSL-Ubuntu 22.04
- RLTK 0.8.7
前言
说明
参考:https://bfnightly.bracketproductions.com/rustbook/
目标
渲染一个主窗口,并且在窗口上渲染一些静态的字符。
Cargo.toml
[package]
edition = "2021"
name = "game"
version = "0.1.0"
[dependencies]
rltk = "0.8.7"
specs = "0.18.0"
specs-derive = "0.4.1"
ECS
ECS 是一种游戏开发模式,将其分为了三种 E(Entity),C(Component)和 S(System)。
可以通过其它资料了解这种模式,specs 就是使用 ECS 的一个框架。
Component
#[derive(Component)]
struct Position {
x: i32,
y: i32,
}
#[derive(Component)]
struct Renderable {
glyph: rltk::FontCharType,
fg: RGB,
bg: RGB,
}
main
fn main() -> rltk::BError {
let context = rltk::RltkBuilder::simple80x50()
.with_title("冒险游戏")
.build()?;
let mut state = State {
world: World::new(),
};
state.world.register::<Position>();
state.world.register::<Renderable>();
state
.world
.create_entity()
.with(Position { x: 40, y: 25 })
.with(Renderable {
glyph: rltk::to_cp437('@'),
fg: RGB::named(rltk::YELLOW),
bg: RGB::named(rltk::BLACK),
})
.build();
for i in 0..10 {
state
.world
.create_entity()
//
.with(Position { x: i * 7, y: 20 })
.with(Renderable {
glyph: rltk::to_cp437('☺'),
fg: RGB::named(rltk::RED),
bg: RGB::named(rltk::BLACK),
})
.build();
}
rltk::main_loop(context, state)
}
GameState
struct State {
world: World,
}
impl GameState for State {
fn tick(&mut self, ctx: &mut Rltk) {
ctx.cls();
let positions = self.world.read_storage::<Position>();
let renderables = self.world.read_storage::<Renderable>();
for (pos, render) in (&positions, &renderables).join() {
ctx.set(pos.x, pos.y, render.fg, render.bg, render.glyph);
}
}
}
效果
总结
创建了游戏的主窗口,并且在窗口内渲染了几个字符。
附录
源码
use rltk::prelude::*;
use specs::prelude::*;
use specs_derive::Component;
struct State {
world: World,
}
impl GameState for State {
fn tick(&mut self, ctx: &mut Rltk) {
ctx.cls();
let positions = self.world.read_storage::<Position>();
let renderables = self.world.read_storage::<Renderable>();
for (pos, render) in (&positions, &renderables).join() {
ctx.set(pos.x, pos.y, render.fg, render.bg, render.glyph);
}
}
}
fn main() -> rltk::BError {
let context = rltk::RltkBuilder::simple80x50()
.with_title("冒险游戏")
.build()?;
let mut state = State {
world: World::new(),
};
state.world.register::<Position>();
state.world.register::<Renderable>();
state
.world
.create_entity()
.with(Position { x: 40, y: 25 })
.with(Renderable {
glyph: rltk::to_cp437('@'),
fg: RGB::named(rltk::YELLOW),
bg: RGB::named(rltk::BLACK),
})
.build();
for i in 0..10 {
state
.world
.create_entity()
.with(Position { x: i * 7, y: 20 })
.with(Renderable {
glyph: rltk::to_cp437('☺'),
fg: RGB::named(rltk::RED),
bg: RGB::named(rltk::BLACK),
})
.build();
}
rltk::main_loop(context, state)
}
#[derive(Component)]
struct Position {
x: i32,
y: i32,
}
#[derive(Component)]
struct Renderable {
glyph: rltk::FontCharType,
fg: RGB,
bg: RGB,
}
标签:RLTK,bg,rltk,渲染,RGB,0235,state,world,glyph
From: https://www.cnblogs.com/jiangbo4444/p/18360567