Skip to content

Instantly share code, notes, and snippets.

@nandakoryaaa
Created March 16, 2023 18:19
Show Gist options
  • Save nandakoryaaa/873ac111218e8652515931f138b1008d to your computer and use it in GitHub Desktop.
Save nandakoryaaa/873ac111218e8652515931f138b1008d to your computer and use it in GitHub Desktop.
Apple game initial implementation
extern crate sdl2;
use sdl2::rect::Rect;
use sdl2::pixels::Color;
use sdl2::render::WindowCanvas;
use std::time::Duration;
trait Renderer {
fn render(
& self, canvas: & mut WindowCanvas,
gmo: & GameObject
);
}
struct RendererRect {}
impl Renderer for RendererRect {
fn render(
& self, canvas: & mut WindowCanvas,
gmo: & GameObject
) {
canvas.set_draw_color(gmo.color);
canvas.fill_rect(gmo.rect);
}
}
struct GameObject<'gmo> {
color: Color,
rect: Rect,
// Renderer должен жить не меньше,
// чем GameObject
renderer: &'gmo dyn Renderer
}
impl<'rend> GameObject<'rend> {
fn new(
x: i32, y: i32,
w: u32, h: u32,
color: sdl2::pixels::Color,
renderer: &'rend dyn Renderer
) -> Self {
Self {
color: color,
rect: Rect::new(x, y, w, h),
renderer: renderer
}
}
}
struct Stage<'st> {
w: u32,
h: u32,
canvas: sdl2::render::WindowCanvas,
obj_list: Vec<GameObject<'st>>
}
impl<'st> Stage<'st> {
fn new(w:u32, h:u32) -> Self {
let sdl = sdl2::init().unwrap();
let vss: sdl2::VideoSubsystem = sdl.video().unwrap();
let wb = sdl2::video::WindowBuilder::new(
& vss,
"hello",
w,
h
);
let window: sdl2::video::Window = wb.build().unwrap();
let cb = sdl2::render::CanvasBuilder::new(window);
let canvas = cb.build().unwrap();
Self {
w: w,
h: h,
canvas: canvas,
obj_list: Vec::<GameObject>::new()
}
}
fn draw(& mut self) {
for i in 0..self.obj_list.len() {
let o = & self.obj_list[i];
o.renderer.render(& mut self.canvas, o);
}
self.canvas.present();
}
fn add_child(& mut self, child: GameObject<'st>) {
self.obj_list.push(child);
}
}
fn init_stage<'st>(
stage: & mut Stage<'st>,
renderer: &'st dyn Renderer
) {
for i in 0..6 {
let o = GameObject::new(
(i * 100) as i32, (i * 100) as i32,
(i + 1) * 20, (i + 1) * 20,
Color::RGB(255, (255 - i * 35) as u8, 0),
renderer
);
stage.add_child(o);
}
}
fn main() {
let renderer_rect = RendererRect {};
let mut stage: Stage = Stage::new(800, 600);
init_stage(& mut stage, & renderer_rect);
stage.draw();
std::thread::sleep(Duration::new(0, 3000000000));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment