Skip to content

Instantly share code, notes, and snippets.

@suzusime
Created May 20, 2021 15:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save suzusime/df950a0bd64a9288d97ed5f1cb8d89d4 to your computer and use it in GitHub Desktop.
Save suzusime/df950a0bd64a9288d97ed5f1cb8d89d4 to your computer and use it in GitHub Desktop.
『ゲームプログラミングC++』の第一章をもとにrust-sdl2で書いたもの
extern crate sdl2;
use sdl2::event::Event;
use sdl2::keyboard::Keycode;
use sdl2::pixels::Color;
use std::time::Duration;
struct Game {
sdl_context: sdl2::Sdl, // SDL全体オブジェクト
canvas: sdl2::render::Canvas<sdl2::video::Window>, // Rendererの代わり
}
impl Game {
fn new() -> Result<Self, String> {
let sdl_context = sdl2::init()?;
let video_subsystem = sdl_context.video()?;
let window = video_subsystem
.window("えすでぃーえる!", 800, 600)
.position_centered()
.build()
.map_err(|e| e.to_string())?;
let canvas = window.into_canvas().build().map_err(|e| e.to_string())?;
Ok(Self {
sdl_context: sdl_context,
canvas: canvas,
})
}
fn run_roop(&mut self) -> Result<(), String> {
let mut count: u8 = 0;
'mainloop: loop {
// イベント処理
for event in self.sdl_context.event_pump()?.poll_iter() {
match event {
Event::KeyDown {
keycode: Some(Keycode::Escape),
..
}
| Event::Quit { .. } => break 'mainloop,
_ => {}
}
}
self.draw(count);
if count == 255 {
count = 0;
} else {
count += 1;
}
::std::thread::sleep(Duration::new(0, 1_000_000_000u32 / 30));
}
Ok(())
}
fn draw(&mut self, kido: u8) {
self.canvas.set_draw_color(Color::RGB(kido, kido, kido));
self.canvas.clear();
self.canvas.present();
}
}
fn main() -> Result<(), String> {
let mut game = Game::new()?;
game.run_roop()?;
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment