├── src ├── float-hasher.rs ├── sound.rs ├── traits.rs ├── direction.rs ├── bounds.rs ├── timer.rs ├── main.rs ├── macros.rs ├── healthbar.rs ├── panel.rs ├── animation.rs ├── projectile.rs ├── textures.rs ├── resources.rs ├── player.rs ├── oneoffanim.rs ├── background.rs ├── enemy.rs ├── humanoid.rs ├── powerup.rs └── gamestate.rs ├── .gitignore ├── resources ├── fonts │ └── bitpotion.ttf └── sprites │ ├── boot │ └── boot.png │ ├── boss │ └── boss.png │ ├── hero │ ├── hero.png │ ├── hero-angry.png │ ├── hero-forward.png │ └── hero-invincible.png │ ├── ring │ └── ring.png │ ├── grass │ ├── grass1.png │ ├── grass2.png │ ├── grass-top.png │ ├── grass-left.png │ ├── grass-lower.png │ ├── grass-right.png │ ├── grass-top-left.png │ ├── grass-lower-left.png │ ├── grass-lower-right.png │ └── grass-top-right.png │ ├── panel │ └── panel.png │ ├── rocks │ ├── rock1.png │ ├── rock2.png │ └── rock3.png │ ├── scrolls │ └── fire.png │ ├── spark │ └── spark.png │ ├── explosion │ ├── smoke.png │ └── explosion.png │ ├── hearts │ ├── heart16.png │ └── heart32.png │ ├── fireball │ └── fireball.png │ ├── basic-grunts │ ├── grunt1.png │ ├── grunt2.png │ ├── grunt3.png │ ├── grunt4.png │ ├── grunt5.png │ ├── grunt6.png │ └── grunt7.png │ ├── cannonball │ └── cannonball.png │ ├── badass-grunts │ ├── badass-grunt1.png │ ├── badass-grunt2.png │ └── badass-grunt3.png │ ├── flowers │ └── generic-rpg-flower01.png │ └── stronger-grunts │ ├── stronger-grunt-1.png │ ├── stronger-grunt-2.png │ └── stronger-grunt-3.png ├── .rustfmt.toml ├── Cargo.toml ├── README.md └── LICENSE /src/float-hasher.rs: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /src/sound.rs: -------------------------------------------------------------------------------- 1 | // pub struct SoundManager { 2 | // power_up_sound: 3 | // } -------------------------------------------------------------------------------- /resources/fonts/bitpotion.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vrmiguel/endless-trial/HEAD/resources/fonts/bitpotion.ttf -------------------------------------------------------------------------------- /resources/sprites/boot/boot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vrmiguel/endless-trial/HEAD/resources/sprites/boot/boot.png -------------------------------------------------------------------------------- /resources/sprites/boss/boss.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vrmiguel/endless-trial/HEAD/resources/sprites/boss/boss.png -------------------------------------------------------------------------------- /resources/sprites/hero/hero.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vrmiguel/endless-trial/HEAD/resources/sprites/hero/hero.png -------------------------------------------------------------------------------- /resources/sprites/ring/ring.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vrmiguel/endless-trial/HEAD/resources/sprites/ring/ring.png -------------------------------------------------------------------------------- /resources/sprites/grass/grass1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vrmiguel/endless-trial/HEAD/resources/sprites/grass/grass1.png -------------------------------------------------------------------------------- /resources/sprites/grass/grass2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vrmiguel/endless-trial/HEAD/resources/sprites/grass/grass2.png -------------------------------------------------------------------------------- /resources/sprites/panel/panel.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vrmiguel/endless-trial/HEAD/resources/sprites/panel/panel.png -------------------------------------------------------------------------------- /resources/sprites/rocks/rock1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vrmiguel/endless-trial/HEAD/resources/sprites/rocks/rock1.png -------------------------------------------------------------------------------- /resources/sprites/rocks/rock2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vrmiguel/endless-trial/HEAD/resources/sprites/rocks/rock2.png -------------------------------------------------------------------------------- /resources/sprites/rocks/rock3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vrmiguel/endless-trial/HEAD/resources/sprites/rocks/rock3.png -------------------------------------------------------------------------------- /resources/sprites/scrolls/fire.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vrmiguel/endless-trial/HEAD/resources/sprites/scrolls/fire.png -------------------------------------------------------------------------------- /resources/sprites/spark/spark.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vrmiguel/endless-trial/HEAD/resources/sprites/spark/spark.png -------------------------------------------------------------------------------- /resources/sprites/explosion/smoke.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vrmiguel/endless-trial/HEAD/resources/sprites/explosion/smoke.png -------------------------------------------------------------------------------- /resources/sprites/grass/grass-top.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vrmiguel/endless-trial/HEAD/resources/sprites/grass/grass-top.png -------------------------------------------------------------------------------- /resources/sprites/hearts/heart16.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vrmiguel/endless-trial/HEAD/resources/sprites/hearts/heart16.png -------------------------------------------------------------------------------- /resources/sprites/hearts/heart32.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vrmiguel/endless-trial/HEAD/resources/sprites/hearts/heart32.png -------------------------------------------------------------------------------- /resources/sprites/hero/hero-angry.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vrmiguel/endless-trial/HEAD/resources/sprites/hero/hero-angry.png -------------------------------------------------------------------------------- /resources/sprites/fireball/fireball.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vrmiguel/endless-trial/HEAD/resources/sprites/fireball/fireball.png -------------------------------------------------------------------------------- /resources/sprites/grass/grass-left.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vrmiguel/endless-trial/HEAD/resources/sprites/grass/grass-left.png -------------------------------------------------------------------------------- /resources/sprites/grass/grass-lower.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vrmiguel/endless-trial/HEAD/resources/sprites/grass/grass-lower.png -------------------------------------------------------------------------------- /resources/sprites/grass/grass-right.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vrmiguel/endless-trial/HEAD/resources/sprites/grass/grass-right.png -------------------------------------------------------------------------------- /resources/sprites/hero/hero-forward.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vrmiguel/endless-trial/HEAD/resources/sprites/hero/hero-forward.png -------------------------------------------------------------------------------- /src/traits.rs: -------------------------------------------------------------------------------- 1 | /// A trait for cleaning up no longer needed entities. 2 | pub trait Cleanable { 3 | fn clean_up(&mut self); 4 | } 5 | -------------------------------------------------------------------------------- /resources/sprites/basic-grunts/grunt1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vrmiguel/endless-trial/HEAD/resources/sprites/basic-grunts/grunt1.png -------------------------------------------------------------------------------- /resources/sprites/basic-grunts/grunt2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vrmiguel/endless-trial/HEAD/resources/sprites/basic-grunts/grunt2.png -------------------------------------------------------------------------------- /resources/sprites/basic-grunts/grunt3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vrmiguel/endless-trial/HEAD/resources/sprites/basic-grunts/grunt3.png -------------------------------------------------------------------------------- /resources/sprites/basic-grunts/grunt4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vrmiguel/endless-trial/HEAD/resources/sprites/basic-grunts/grunt4.png -------------------------------------------------------------------------------- /resources/sprites/basic-grunts/grunt5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vrmiguel/endless-trial/HEAD/resources/sprites/basic-grunts/grunt5.png -------------------------------------------------------------------------------- /resources/sprites/basic-grunts/grunt6.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vrmiguel/endless-trial/HEAD/resources/sprites/basic-grunts/grunt6.png -------------------------------------------------------------------------------- /resources/sprites/basic-grunts/grunt7.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vrmiguel/endless-trial/HEAD/resources/sprites/basic-grunts/grunt7.png -------------------------------------------------------------------------------- /resources/sprites/explosion/explosion.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vrmiguel/endless-trial/HEAD/resources/sprites/explosion/explosion.png -------------------------------------------------------------------------------- /resources/sprites/grass/grass-top-left.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vrmiguel/endless-trial/HEAD/resources/sprites/grass/grass-top-left.png -------------------------------------------------------------------------------- /resources/sprites/hero/hero-invincible.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vrmiguel/endless-trial/HEAD/resources/sprites/hero/hero-invincible.png -------------------------------------------------------------------------------- /resources/sprites/cannonball/cannonball.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vrmiguel/endless-trial/HEAD/resources/sprites/cannonball/cannonball.png -------------------------------------------------------------------------------- /resources/sprites/grass/grass-lower-left.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vrmiguel/endless-trial/HEAD/resources/sprites/grass/grass-lower-left.png -------------------------------------------------------------------------------- /resources/sprites/grass/grass-lower-right.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vrmiguel/endless-trial/HEAD/resources/sprites/grass/grass-lower-right.png -------------------------------------------------------------------------------- /resources/sprites/grass/grass-top-right.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vrmiguel/endless-trial/HEAD/resources/sprites/grass/grass-top-right.png -------------------------------------------------------------------------------- /src/direction.rs: -------------------------------------------------------------------------------- 1 | #[derive(Copy, Clone, PartialEq, Eq)] 2 | pub enum Direction { 3 | North, 4 | West, 5 | East, 6 | South, 7 | } 8 | -------------------------------------------------------------------------------- /resources/sprites/badass-grunts/badass-grunt1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vrmiguel/endless-trial/HEAD/resources/sprites/badass-grunts/badass-grunt1.png -------------------------------------------------------------------------------- /resources/sprites/badass-grunts/badass-grunt2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vrmiguel/endless-trial/HEAD/resources/sprites/badass-grunts/badass-grunt2.png -------------------------------------------------------------------------------- /resources/sprites/badass-grunts/badass-grunt3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vrmiguel/endless-trial/HEAD/resources/sprites/badass-grunts/badass-grunt3.png -------------------------------------------------------------------------------- /resources/sprites/flowers/generic-rpg-flower01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vrmiguel/endless-trial/HEAD/resources/sprites/flowers/generic-rpg-flower01.png -------------------------------------------------------------------------------- /resources/sprites/stronger-grunts/stronger-grunt-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vrmiguel/endless-trial/HEAD/resources/sprites/stronger-grunts/stronger-grunt-1.png -------------------------------------------------------------------------------- /resources/sprites/stronger-grunts/stronger-grunt-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vrmiguel/endless-trial/HEAD/resources/sprites/stronger-grunts/stronger-grunt-2.png -------------------------------------------------------------------------------- /resources/sprites/stronger-grunts/stronger-grunt-3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vrmiguel/endless-trial/HEAD/resources/sprites/stronger-grunts/stronger-grunt-3.png -------------------------------------------------------------------------------- /.rustfmt.toml: -------------------------------------------------------------------------------- 1 | edition = "2021" 2 | imports_granularity = "Crate" 3 | newline_style = "Unix" 4 | wrap_comments = true 5 | reorder_imports = true 6 | group_imports = "StdExternalCrate" 7 | fn_call_width = 50 8 | max_width = 65 9 | -------------------------------------------------------------------------------- /src/bounds.rs: -------------------------------------------------------------------------------- 1 | use tetra::{graphics::Rectangle, math::Vec2}; 2 | 3 | pub struct Bounds { 4 | boundaries: Rectangle, 5 | } 6 | 7 | impl Bounds { 8 | pub const fn new(width: f32, height: f32) -> Self { 9 | Self { 10 | boundaries: Rectangle::new(0.0, 0.0, width, height), 11 | } 12 | } 13 | 14 | pub fn contains(&self, pos: Vec2) -> bool { 15 | pos.x <= self.boundaries.width 16 | && pos.y <= self.boundaries.height 17 | && pos.x >= 0. 18 | && pos.y >= 0. 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "endless-trial" 3 | version = "0.1.0" 4 | authors = ["Vinícius Miguel "] 5 | edition = "2018" 6 | 7 | [dependencies] 8 | arrayvec = "0.7.2" 9 | 10 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 11 | 12 | [dependencies.rand] 13 | version = "0.8.5" 14 | default-features = false 15 | features = ["alloc", "small_rng", "getrandom"] 16 | 17 | [dependencies.tetra] 18 | version = "0.7.0" 19 | default-features = false 20 | features = ['texture_png', 'font_ttf', 'sdl2_bundled','sdl2_static_link'] 21 | 22 | [profile.release] 23 | lto = true 24 | codegen-units = 1 25 | opt-level = 3 26 | -------------------------------------------------------------------------------- /src/timer.rs: -------------------------------------------------------------------------------- 1 | use std::time::{Duration, Instant}; 2 | 3 | #[derive(Debug, Clone, Copy)] 4 | pub struct Timer { 5 | interval: Duration, 6 | last_ticked: Instant, 7 | } 8 | 9 | impl Timer { 10 | pub fn start_now_with_interval(interval: Duration) -> Self { 11 | Self { 12 | interval, 13 | last_ticked: Instant::now(), 14 | } 15 | } 16 | 17 | pub fn is_ready(&self) -> bool { 18 | self.last_ticked.elapsed() >= self.interval 19 | } 20 | 21 | pub fn reset(&mut self) { 22 | self.last_ticked = Instant::now() 23 | } 24 | 25 | pub fn elapsed(&self) -> Duration { 26 | self.last_ticked.elapsed() 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | mod animation; 2 | mod background; 3 | mod bounds; 4 | mod direction; 5 | mod enemy; 6 | mod gamestate; 7 | mod healthbar; 8 | mod humanoid; 9 | mod macros; 10 | mod oneoffanim; 11 | mod panel; 12 | mod player; 13 | mod powerup; 14 | mod projectile; 15 | mod resources; 16 | mod textures; 17 | mod timer; 18 | mod traits; 19 | 20 | use bounds::Bounds; 21 | use direction::Direction; 22 | use gamestate::GameState; 23 | use tetra::ContextBuilder; 24 | 25 | const WIDTH: i32 = 800; 26 | const HEIGHT: i32 = 800; 27 | const BOUNDS: Bounds = Bounds::new(800.0, 800.0); 28 | 29 | const VERSION: &str = "0.1.0"; 30 | 31 | fn main() -> tetra::Result { 32 | println!("Endless Trial v{VERSION}"); 33 | ContextBuilder::new("Endless Trial", WIDTH, HEIGHT) 34 | .quit_on_escape(true) 35 | .debug_info(true) 36 | .resizable(true) 37 | .build()? 38 | .run(GameState::new) 39 | } 40 | -------------------------------------------------------------------------------- /src/macros.rs: -------------------------------------------------------------------------------- 1 | #[macro_export] 2 | macro_rules! left { 3 | ( $ctx:expr) => {{ 4 | tetra::input::is_key_down($ctx, tetra::input::Key::Left) 5 | }}; 6 | } 7 | 8 | #[macro_export] 9 | macro_rules! right { 10 | ( $ctx:expr) => {{ 11 | tetra::input::is_key_down($ctx, tetra::input::Key::Right) 12 | }}; 13 | } 14 | 15 | #[macro_export] 16 | macro_rules! up { 17 | ( $ctx:expr) => {{ 18 | tetra::input::is_key_down($ctx, tetra::input::Key::Up) 19 | }}; 20 | } 21 | 22 | #[macro_export] 23 | macro_rules! down { 24 | ( $ctx:expr) => {{ 25 | tetra::input::is_key_down($ctx, tetra::input::Key::Down) 26 | }}; 27 | } 28 | 29 | #[macro_export] 30 | #[cfg(debug_assertions)] 31 | macro_rules! debug_println { 32 | ($($arg:tt)*) => (println!($($arg)*)); 33 | } 34 | 35 | #[macro_export] 36 | #[cfg(not(debug_assertions))] 37 | macro_rules! debug_println { 38 | ($($arg:tt)*) => {}; 39 | } 40 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Endless Trial 2 | 3 | Endless Trial is a simple 2D bullet-hell-like game made in Rust with [Tetra](https://github.com/17cupsofcoffee/tetra). 4 | 5 | ![Screenshot](https://user-images.githubusercontent.com/36349314/142258988-beb07f32-6d36-4aef-8c92-c3887b7637ce.png) 6 | 7 | [Click here](https://streamable.com/hnnjb5) for a small video showing the gameplay 8 | 9 | 10 | ## To-do 11 | 12 | - [ ] Sound 13 | 14 | 15 | ## Credits 16 | 17 | This project uses several free sprites: 18 | 19 | * [RPG Pack by Estúdio Vaca Roxa](https://bakudas.itch.io/generic-rpg-pack) 20 | * [Serene Village by LimeZu](https://limezu.itch.io/serenevillagerevamped) 21 | * [FX062](https://kvsr.itch.io/fx062) and [Fireball](https://kvsr.itch.io/fireball-animation) by NYKNCK. 22 | * [Heart Pixel Art](https://opengameart.org/content/heart-pixel-art) by Dan Sevenstar 23 | * [PX UI - Basic](https://karwisch.itch.io/pxui-basic) by Karwisch 24 | * [BitPotion](https:/https://joebrogers.itch.io/bitpotion) font by Joeb Rogers 25 | * [Ninja Adventure](https://pixel-boy.itch.io/ninja-adventure-asset-pack) by pixel-boy 26 | * [Fire Spell Effect 02](https://pimen.itch.io/fire-spell-effect-02) by pimen 27 | * [16x16 RPG Item Pack](https://alexs-assets.itch.io/16x16-rpg-item-pack) by Alex's Assets 28 | 29 | Characters were made with 0x72's [2-bit Character Generator](https://0x72.itch.io/2bitcharactergenerator) 30 | -------------------------------------------------------------------------------- /src/healthbar.rs: -------------------------------------------------------------------------------- 1 | use tetra::{ 2 | graphics::{DrawParams, Texture}, 3 | math::Vec2, 4 | Context, 5 | }; 6 | 7 | use crate::{panel::Panel, resources}; 8 | 9 | // A small utility struct to draw hearts on the screen 10 | pub struct HealthBar { 11 | panel: Panel, 12 | heart_sprite: Texture, 13 | } 14 | 15 | impl HealthBar { 16 | pub fn new(ctx: &mut Context) -> Self { 17 | let heart_sprite = 18 | Texture::from_encoded(ctx, resources::HEART_16X) 19 | .expect("could not load built-in heart sprite"); 20 | 21 | Self { 22 | panel: Panel::new(ctx), 23 | heart_sprite, 24 | } 25 | } 26 | 27 | pub fn draw(&self, ctx: &mut Context, number_of_hearts: u8) { 28 | let width = (number_of_hearts as f32) * 16.0 + 10.5; 29 | self.panel.sprite.draw_nine_slice( 30 | ctx, 31 | &self.panel.config, 32 | width, 33 | 26.0, 34 | DrawParams::new() 35 | .position(Vec2::new(768.0 - width, 32.0)), 36 | ); 37 | 38 | for spacing in 0..number_of_hearts { 39 | let spacing = spacing as f32; 40 | self.heart_sprite.draw( 41 | ctx, 42 | DrawParams::new().position(Vec2::new( 43 | 746.0 - 16.0 * spacing, 44 | 36.0, 45 | )), 46 | ); 47 | } 48 | 49 | // self.heart_sprite 50 | // .draw(ctx, 51 | // DrawParams::new().position(Vec2::new(746.0 - 16.0, 52 | // 36.0))) 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/panel.rs: -------------------------------------------------------------------------------- 1 | use tetra::{ 2 | graphics::{ 3 | text::{Font, Text}, 4 | NineSlice, Rectangle, Texture, 5 | }, 6 | math::Vec2, 7 | Context, 8 | }; 9 | 10 | use crate::resources; 11 | 12 | pub struct Panel { 13 | pub sprite: Texture, 14 | pub config: NineSlice, 15 | } 16 | 17 | impl Panel { 18 | pub fn new(ctx: &mut Context) -> Self { 19 | let sprite = 20 | Texture::from_encoded(ctx, resources::PANEL) 21 | .expect("failed to load built-in panel sprite"); 22 | 23 | Self { 24 | sprite, 25 | config: NineSlice::with_border( 26 | Rectangle::new(0.0, 0.0, 32.0, 32.0), 27 | 4.0, 28 | ), 29 | } 30 | } 31 | } 32 | 33 | pub struct GameOverPanel { 34 | panel: Panel, 35 | text: Text, 36 | } 37 | 38 | impl GameOverPanel { 39 | pub fn new(ctx: &mut Context) -> Self { 40 | let panel = Panel::new(ctx); 41 | let text = Text::new( 42 | "Game over!", 43 | Font::from_vector_file_data( 44 | ctx, 45 | resources::BITPOTION_FONT, 46 | 64.0, 47 | ) 48 | .expect("Failed to instantiate font"), 49 | ); 50 | 51 | Self { panel, text } 52 | } 53 | 54 | pub fn draw(&mut self, ctx: &mut Context) { 55 | self.panel.sprite.draw_nine_slice( 56 | ctx, 57 | &self.panel.config, 58 | 206.0, 59 | 80., 60 | Vec2 { x: 320.0, y: 320.0 }, 61 | ); 62 | 63 | self.text.draw( 64 | ctx, 65 | Vec2 { 66 | x: 320.0 + 8.0, 67 | y: 320.0 + 8.0, 68 | }, 69 | ); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/animation.rs: -------------------------------------------------------------------------------- 1 | use std::time::Duration; 2 | 3 | use tetra::{ 4 | graphics::{animation::Animation, Rectangle, Texture}, 5 | Context, 6 | }; 7 | 8 | use crate::resources::{CANNONBALL, FIREBALL}; 9 | 10 | /// Animation for the player and grunts 11 | pub struct HumanoidAnimation { 12 | // Front-side walking animation 13 | pub frontside: Animation, 14 | // Back-side walking animation 15 | pub backside: Animation, 16 | // "Left-side" walking animation 17 | pub leftside: Animation, 18 | } 19 | 20 | impl HumanoidAnimation { 21 | pub fn new(texture: Texture) -> Self { 22 | let frontside = Animation::new( 23 | texture.clone(), 24 | vec![ 25 | Rectangle::new(0., 0., 16., 16.), 26 | Rectangle::new(48., 0., 16., 16.), 27 | ], 28 | Duration::from_secs_f64(0.5), 29 | ); 30 | 31 | let backside = Animation::new( 32 | texture.clone(), 33 | vec![ 34 | Rectangle::new(16., 0., 16., 16.), 35 | Rectangle::new(64., 0., 16., 16.), 36 | ], 37 | Duration::from_secs_f64(0.5), 38 | ); 39 | 40 | let leftside = Animation::new( 41 | texture, 42 | vec![ 43 | Rectangle::new(32., 0., 16., 16.), 44 | Rectangle::new(80., 0., 16., 16.), 45 | ], 46 | Duration::from_secs_f64(0.5), 47 | ); 48 | 49 | Self { 50 | frontside, 51 | leftside, 52 | backside, 53 | } 54 | } 55 | } 56 | 57 | pub struct FireballAnimation; 58 | 59 | impl FireballAnimation { 60 | pub fn build(ctx: &mut Context) -> Animation { 61 | let fireball_texture = 62 | Texture::from_encoded(ctx, FIREBALL) 63 | .expect("couldn't read the fireball sprite"); 64 | Animation::new( 65 | fireball_texture, 66 | Rectangle::row(0., 0., 32., 32.).take(5).collect(), 67 | Duration::from_secs_f64(0.10), 68 | ) 69 | } 70 | } 71 | 72 | pub struct CannonballAnimation; 73 | 74 | impl CannonballAnimation { 75 | pub fn build(ctx: &mut Context) -> Animation { 76 | let cannonball_texture = 77 | Texture::from_encoded(ctx, CANNONBALL) 78 | .expect("couldn't read the cannonball sprite"); 79 | 80 | Animation::new( 81 | cannonball_texture, 82 | Rectangle::row(0., 0., 32., 32.).take(5).collect(), 83 | Duration::from_secs_f64(0.10), 84 | ) 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /src/projectile.rs: -------------------------------------------------------------------------------- 1 | use core::f32; 2 | 3 | use tetra::{ 4 | graphics::{animation::Animation, DrawParams}, 5 | math::Vec2, 6 | Context, 7 | }; 8 | 9 | use crate::{traits::Cleanable, BOUNDS}; 10 | 11 | #[derive(Clone)] 12 | pub struct Projectile { 13 | position: Vec2, 14 | velocity: Vec2, 15 | angle_rad: f32, 16 | } 17 | 18 | impl Projectile { 19 | pub fn position(&self) -> Vec2 { 20 | self.position 21 | } 22 | } 23 | 24 | pub struct ProjectileManager { 25 | projectiles: Vec, 26 | animation: Animation, 27 | } 28 | 29 | impl Cleanable for ProjectileManager { 30 | /// Remove projectiles that have gone out of bounds 31 | fn clean_up(&mut self) { 32 | let is_in_bounds = |fireball: &Projectile| { 33 | BOUNDS.contains(fireball.position()) 34 | }; 35 | 36 | self.projectiles.retain(is_in_bounds); 37 | } 38 | } 39 | 40 | impl ProjectileManager { 41 | pub fn new(animation: Animation) -> Self { 42 | Self { 43 | projectiles: Vec::with_capacity(48), 44 | animation, 45 | } 46 | } 47 | 48 | pub fn shoot( 49 | &mut self, 50 | is_triple_shooting: bool, 51 | angle: f32, 52 | position: Vec2, 53 | velocity: Vec2, 54 | ) { 55 | if is_triple_shooting { 56 | self.send_triple_shot(angle, position, velocity); 57 | } else { 58 | self.add_projectile(angle, position, velocity) 59 | } 60 | } 61 | 62 | fn send_triple_shot( 63 | &mut self, 64 | angle: f32, 65 | position: Vec2, 66 | velocity: Vec2, 67 | ) { 68 | for deviation in [-45.0, 0.0, 45.0] { 69 | self.add_projectile( 70 | angle + deviation, 71 | position, 72 | velocity, 73 | ); 74 | } 75 | } 76 | 77 | /// Adds a projectile to this `ProjectileManager`. 78 | /// The angle supplied should be in degrees. 79 | pub fn add_projectile( 80 | &mut self, 81 | angle: f32, 82 | position: Vec2, 83 | velocity: Vec2, 84 | ) { 85 | let angle_rad = angle.to_radians(); 86 | 87 | let fireball = Projectile { 88 | position, 89 | angle_rad, 90 | velocity, 91 | }; 92 | 93 | self.projectiles.push(fireball); 94 | } 95 | 96 | pub fn advance_animation(&mut self, ctx: &mut Context) { 97 | self.animation.advance(ctx); 98 | 99 | self.clean_up(); 100 | 101 | for fireball in &mut self.projectiles { 102 | let ang_rad = fireball.angle_rad; 103 | fireball.position += 104 | Vec2::new(f32::cos(ang_rad), -f32::sin(ang_rad)) 105 | * fireball.velocity; 106 | } 107 | } 108 | 109 | pub fn projectiles(&self) -> &[Projectile] { 110 | &self.projectiles 111 | } 112 | 113 | pub fn draw(&self, ctx: &mut Context) { 114 | for fireball in &self.projectiles { 115 | self.animation.draw( 116 | ctx, 117 | DrawParams::new() 118 | .position(fireball.position) 119 | .origin(Vec2::new(16.0, 16.0)) 120 | .rotation(fireball.angle_rad), 121 | ) 122 | } 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /src/textures.rs: -------------------------------------------------------------------------------- 1 | use std::time::Instant; 2 | 3 | use arrayvec::ArrayVec; 4 | use rand::{seq::SliceRandom, Rng}; 5 | use tetra::{graphics::Texture, Context}; 6 | 7 | use crate::{ 8 | humanoid::HumanoidType, 9 | resources::{ 10 | self, BADASS_GRUNTS, BASIC_GRUNTS, BOSS, STRONGER_GRUNTS, 11 | }, 12 | }; 13 | 14 | /// Loads all grunt sprites into memory to avoid 15 | /// recreating the texture when spawning enemies 16 | pub struct GruntTextures { 17 | basic_grunts: [Texture; BASIC_GRUNTS.len()], 18 | stronger_grunts: [Texture; STRONGER_GRUNTS.len()], 19 | badass_grunts: [Texture; BADASS_GRUNTS.len()], 20 | boss: Texture, 21 | } 22 | 23 | impl GruntTextures { 24 | fn load_textures( 25 | ctx: &mut Context, 26 | sprites: &[&[u8]], 27 | ) -> [Texture; N] { 28 | let mut textures: ArrayVec = ArrayVec::new(); 29 | 30 | for sprite in sprites { 31 | textures.push( 32 | Texture::from_encoded(ctx, sprite).unwrap(), 33 | ); 34 | } 35 | 36 | textures.into_inner().unwrap() 37 | } 38 | 39 | pub fn load(ctx: &mut Context) -> Self { 40 | let now = Instant::now(); 41 | 42 | let textures = Self { 43 | basic_grunts: Self::load_textures(ctx, BASIC_GRUNTS), 44 | stronger_grunts: Self::load_textures( 45 | ctx, 46 | STRONGER_GRUNTS, 47 | ), 48 | badass_grunts: Self::load_textures( 49 | ctx, 50 | BADASS_GRUNTS, 51 | ), 52 | boss: Texture::from_encoded(ctx, BOSS).unwrap(), 53 | }; 54 | 55 | println!( 56 | "Loaded all enemy textures into GPU memory in {}ms", 57 | now.elapsed().as_millis() 58 | ); 59 | 60 | textures 61 | } 62 | 63 | /// Choose a random texture of the given enemy kind 64 | pub fn choose_enemy_from_kind( 65 | &self, 66 | kind: HumanoidType, 67 | rng: &mut R, 68 | ) -> Texture { 69 | match kind { 70 | HumanoidType::Player => unreachable!( 71 | "An enemy cannot have the player's sprite" 72 | ), 73 | HumanoidType::BasicEnemy => { 74 | self.basic_grunts.choose(rng).unwrap() 75 | } 76 | HumanoidType::StrongerEnemy => { 77 | self.stronger_grunts.choose(rng).unwrap() 78 | } 79 | HumanoidType::BadassEnemy => { 80 | self.badass_grunts.choose(rng).unwrap() 81 | } 82 | HumanoidType::Boss => &self.boss, 83 | } 84 | .clone() // Texture is an Rc so this clone is cheap 85 | } 86 | } 87 | 88 | pub struct PowerUpTextures { 89 | pub fire_scroll_sprite: Texture, 90 | pub heart_sprite: Texture, 91 | pub boot_sprite: Texture, 92 | pub ring_sprite: Texture, 93 | } 94 | 95 | impl PowerUpTextures { 96 | pub fn load(ctx: &mut Context) -> Self { 97 | Self { 98 | fire_scroll_sprite: Texture::from_encoded( 99 | ctx, 100 | resources::FIRE_SCROLL, 101 | ) 102 | .unwrap(), 103 | heart_sprite: Texture::from_encoded( 104 | ctx, 105 | resources::HEART_32X, 106 | ) 107 | .unwrap(), 108 | boot_sprite: Texture::from_encoded( 109 | ctx, 110 | resources::BOOT, 111 | ) 112 | .unwrap(), 113 | ring_sprite: Texture::from_encoded( 114 | ctx, 115 | resources::RING, 116 | ) 117 | .unwrap(), 118 | } 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /src/resources.rs: -------------------------------------------------------------------------------- 1 | pub const HERO: &[u8] = 2 | include_bytes!("../resources/sprites/hero/hero.png"); 3 | // pub const HERO_INVINCIBLE: &[u8] = 4 | // include_bytes!("../resources/sprites/hero/hero-invincible.png" 5 | // ); 6 | 7 | pub const ROCK1: &[u8] = 8 | include_bytes!("../resources/sprites/rocks/rock1.png"); 9 | pub const ROCK2: &[u8] = 10 | include_bytes!("../resources/sprites/rocks/rock2.png"); 11 | // pub const ROCK3: &[u8] = 12 | // include_bytes!("../resources/sprites/rocks/rock3.png"); 13 | 14 | pub const GRASS_LOWER_RIGHT: &[u8] = include_bytes!( 15 | "../resources/sprites/grass/grass-lower-right.png" 16 | ); 17 | pub const GRASS_LEFT: &[u8] = 18 | include_bytes!("../resources/sprites/grass/grass-left.png"); 19 | pub const GRASS_LOWER_LEFT: &[u8] = include_bytes!( 20 | "../resources/sprites/grass/grass-lower-left.png" 21 | ); 22 | pub const GRASS_LOWER: &[u8] = 23 | include_bytes!("../resources/sprites/grass/grass-lower.png"); 24 | pub const GRASS_TOP_LEFT: &[u8] = include_bytes!( 25 | "../resources/sprites/grass/grass-top-left.png" 26 | ); 27 | pub const GRASS_TOP: &[u8] = 28 | include_bytes!("../resources/sprites/grass/grass-top.png"); 29 | pub const GRASS_TOP_RIGHT: &[u8] = include_bytes!( 30 | "../resources/sprites/grass/grass-top-right.png" 31 | ); 32 | pub const GRASS_RIGHT: &[u8] = 33 | include_bytes!("../resources/sprites/grass/grass-right.png"); 34 | pub const GRASS_DETAIL_1: &[u8] = 35 | include_bytes!("../resources/sprites/grass/grass1.png"); 36 | pub const GRASS_DETAIL_2: &[u8] = 37 | include_bytes!("../resources/sprites/grass/grass2.png"); 38 | 39 | pub const FIREBALL: &[u8] = 40 | include_bytes!("../resources/sprites/fireball/fireball.png"); 41 | pub const CANNONBALL: &[u8] = include_bytes!( 42 | "../resources/sprites/cannonball/cannonball.png" 43 | ); 44 | 45 | pub const BASIC_GRUNTS: &[&[u8]] = &[ 46 | include_bytes!( 47 | "../resources/sprites/basic-grunts/grunt1.png" 48 | ), 49 | include_bytes!( 50 | "../resources/sprites/basic-grunts/grunt2.png" 51 | ), 52 | include_bytes!( 53 | "../resources/sprites/basic-grunts/grunt3.png" 54 | ), 55 | include_bytes!( 56 | "../resources/sprites/basic-grunts/grunt4.png" 57 | ), 58 | include_bytes!( 59 | "../resources/sprites/basic-grunts/grunt5.png" 60 | ), 61 | include_bytes!( 62 | "../resources/sprites/basic-grunts/grunt6.png" 63 | ), 64 | include_bytes!( 65 | "../resources/sprites/basic-grunts/grunt7.png" 66 | ), 67 | ]; 68 | 69 | pub const STRONGER_GRUNTS: &[&[u8]] = &[ 70 | include_bytes!("../resources/sprites/stronger-grunts/stronger-grunt-1.png"), 71 | include_bytes!("../resources/sprites/stronger-grunts/stronger-grunt-2.png"), 72 | include_bytes!("../resources/sprites/stronger-grunts/stronger-grunt-3.png"), 73 | ]; 74 | 75 | pub const BADASS_GRUNTS: &[&[u8]] = &[ 76 | include_bytes!( 77 | "../resources/sprites/badass-grunts/badass-grunt1.png" 78 | ), 79 | include_bytes!( 80 | "../resources/sprites/badass-grunts/badass-grunt2.png" 81 | ), 82 | include_bytes!( 83 | "../resources/sprites/badass-grunts/badass-grunt3.png" 84 | ), 85 | ]; 86 | 87 | pub const BOSS: &[u8] = 88 | include_bytes!("../resources/sprites/boss/boss.png"); 89 | 90 | pub const HEART_16X: &[u8] = 91 | include_bytes!("../resources/sprites/hearts/heart16.png"); 92 | pub const HEART_32X: &[u8] = 93 | include_bytes!("../resources/sprites/hearts/heart32.png"); 94 | pub const FIRE_SCROLL: &[u8] = 95 | include_bytes!("../resources/sprites/scrolls/fire.png"); 96 | 97 | pub const PANEL: &[u8] = 98 | include_bytes!("../resources/sprites/panel/panel.png"); 99 | 100 | pub const BITPOTION_FONT: &[u8] = 101 | include_bytes!("../resources/fonts/bitpotion.ttf"); 102 | 103 | pub const EXPLOSION: &[u8] = include_bytes!( 104 | "../resources/sprites/explosion/explosion.png" 105 | ); 106 | pub const SMOKE: &[u8] = 107 | include_bytes!("../resources/sprites/explosion/smoke.png"); 108 | 109 | pub const BOOT: &[u8] = 110 | include_bytes!("../resources/sprites/boot/boot.png"); 111 | 112 | pub const RING: &[u8] = 113 | include_bytes!("../resources/sprites/ring/ring.png"); 114 | -------------------------------------------------------------------------------- /src/player.rs: -------------------------------------------------------------------------------- 1 | use std::time::{Duration, Instant}; 2 | 3 | use tetra::{graphics::Texture, math::Vec2, Context}; 4 | 5 | use crate::{ 6 | animation::FireballAnimation, 7 | down, 8 | humanoid::{Humanoid, HumanoidType}, 9 | left, 10 | projectile::{Projectile, ProjectileManager}, 11 | resources, right, 12 | traits::Cleanable, 13 | up, 14 | }; 15 | 16 | pub struct PlayerManager { 17 | player: Humanoid, 18 | fireball_mgr: ProjectileManager, 19 | } 20 | 21 | impl PlayerManager { 22 | pub fn is_player_dead(&self) -> bool { 23 | self.player.is_dead() 24 | } 25 | 26 | pub fn hearts(&self) -> u8 { 27 | self.player.hearts 28 | } 29 | 30 | pub fn player_position(&self) -> Vec2 { 31 | self.player.position 32 | } 33 | 34 | pub fn register_hit(&mut self) { 35 | self.player.take_hit() 36 | } 37 | 38 | pub fn player_mut(&mut self) -> &mut Humanoid { 39 | &mut self.player 40 | } 41 | 42 | pub fn fireballs(&self) -> &[Projectile] { 43 | self.fireball_mgr.projectiles() 44 | } 45 | 46 | pub fn update(&mut self, ctx: &mut Context) { 47 | self.player.clean_up(); 48 | 49 | let ( 50 | faster_shooting_active, 51 | triple_shooting_active, 52 | faster_running_active, 53 | ) = self.player.power_ups.currently_active(); 54 | 55 | let wait_time = if faster_shooting_active { 56 | Duration::from_secs_f32(0.08) 57 | } else { 58 | Duration::from_secs_f32(0.25) 59 | }; 60 | 61 | self.player 62 | .shooting_behavior 63 | .set_shooting_wait_time(wait_time); 64 | 65 | if self.player.can_fire() { 66 | if let Some(angle) = Self::check_for_fire(ctx) { 67 | self.fireball_mgr.shoot( 68 | triple_shooting_active, 69 | angle, 70 | self.player.position, 71 | Vec2 { x: 5.5, y: 5.5 }, 72 | ); 73 | 74 | self.player.shooting_behavior.register_fire(); 75 | } 76 | } 77 | 78 | let hero_speed = 79 | if faster_running_active { 4.5 } else { 2.1 }; 80 | 81 | // Checks for WASD presses and updates player location 82 | self.player.update_from_key_press(ctx, hero_speed); 83 | } 84 | 85 | pub fn new(ctx: &mut Context) -> Self { 86 | let now = Instant::now(); 87 | 88 | let player_texture = 89 | Texture::from_encoded(ctx, resources::HERO).unwrap(); 90 | 91 | let fireball_animation = FireballAnimation::build(ctx); 92 | 93 | let player_mgr = Self { 94 | player: Humanoid::new( 95 | 2, 96 | player_texture, 97 | Vec2::new(240.0, 160.0), 98 | Vec2::new(0.0, 0.0), 99 | true, 100 | Duration::from_secs_f32(0.25), 101 | HumanoidType::Player, 102 | ), 103 | fireball_mgr: ProjectileManager::new( 104 | fireball_animation, 105 | ), 106 | }; 107 | 108 | println!( 109 | "Built PlayerManager in {}ms", 110 | now.elapsed().as_millis() 111 | ); 112 | 113 | player_mgr 114 | } 115 | 116 | // TODO: there's probably a nicer solution to this with 117 | // algebra 118 | pub fn check_for_fire(ctx: &mut Context) -> Option { 119 | match (left!(ctx), right!(ctx), up!(ctx), down!(ctx)) { 120 | // These first cases are kind of nonsensical so I'm 121 | // going to explicitly ignore them 122 | (true, true, _, _) => None, 123 | (_, _, true, true) => None, 124 | (true, false, true, false) => { 125 | // Left and Up -> 135 deg 126 | Some(135.0) 127 | } 128 | (true, false, false, true) => { 129 | // Left and Down -> 225 deg 130 | Some(225.0) 131 | } 132 | (false, true, false, true) => { 133 | // Right and Down -> 315 deg 134 | Some(315.0) 135 | } 136 | (false, true, true, false) => { 137 | // Right and Up -> 45 deg 138 | Some(45.0) 139 | } 140 | (true, false, false, false) => { 141 | // Only Left -> 180 deg 142 | Some(180.0) 143 | } 144 | (false, true, false, false) => { 145 | // Only Right -> 0 deg 146 | Some(0.0) 147 | } 148 | (false, false, true, false) => { 149 | // Only Up -> 90 deg 150 | Some(90.0) 151 | } 152 | (false, false, false, true) => { 153 | // Only Down -> 270 deg 154 | Some(270.0) 155 | } 156 | (false, false, false, false) => { 157 | // No arrow buttons pressed 158 | None 159 | } 160 | } 161 | } 162 | 163 | pub fn draw(&mut self, ctx: &mut Context) { 164 | self.player.advance_animation(ctx); 165 | self.fireball_mgr.advance_animation(ctx); 166 | 167 | self.player.draw(ctx); 168 | self.fireball_mgr.draw(ctx); 169 | } 170 | } 171 | -------------------------------------------------------------------------------- /src/oneoffanim.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | time::{Duration, Instant}, 3 | usize, 4 | }; 5 | 6 | use tetra::{ 7 | graphics::{ 8 | animation::Animation, DrawParams, Rectangle, Texture, 9 | }, 10 | math::Vec2, 11 | Context, 12 | }; 13 | 14 | use crate::{ 15 | resources::{EXPLOSION, SMOKE}, 16 | traits::Cleanable, 17 | }; 18 | 19 | struct OneOffAnimation { 20 | current_frame: u8, 21 | position: Vec2, 22 | } 23 | 24 | impl OneOffAnimation { 25 | pub fn new(position: Vec2) -> Self { 26 | Self { 27 | position, 28 | current_frame: 0, 29 | } 30 | } 31 | } 32 | 33 | pub struct OneOffAnimationManager { 34 | last_updated_time: Instant, 35 | last_smoke_added_time: Instant, 36 | last_explosion_added_time: Instant, 37 | explosion_anim: Animation, 38 | explosion_anim_frames: u8, 39 | smoke_anim: Animation, 40 | smoke_anim_frames: u8, 41 | explosions: Vec, 42 | smokes: Vec, 43 | } 44 | 45 | impl Cleanable for OneOffAnimationManager { 46 | /// Remove animations that have finished 47 | fn clean_up(&mut self) { 48 | let explosion_final_frame = 49 | self.explosion_anim_frames - 1; 50 | let smoke_final_frame = self.smoke_anim_frames - 1; 51 | 52 | self.explosions.retain(|x| { 53 | x.current_frame != explosion_final_frame 54 | }); 55 | 56 | self.smokes 57 | .retain(|x| x.current_frame != smoke_final_frame); 58 | } 59 | } 60 | 61 | impl OneOffAnimationManager { 62 | pub fn new(ctx: &mut Context) -> Self { 63 | let now = Instant::now(); 64 | 65 | let explosion_sprite = Texture::from_encoded( 66 | ctx, EXPLOSION, 67 | ) 68 | .expect("Failed to load built-in explosion sprite"); 69 | 70 | let smoke_sprite = Texture::from_encoded(ctx, SMOKE) 71 | .expect("Failed to load built-in smoke sprite"); 72 | 73 | let explosion_anim = Animation::new( 74 | explosion_sprite, 75 | Rectangle::row(0.0, 0.0, 64.0, 64.0) 76 | .take(10) 77 | .collect(), 78 | Duration::from_secs_f32(0.05), 79 | ); 80 | 81 | let explosion_anim_frames = 82 | explosion_anim.frames().len() as u8; 83 | 84 | let smoke_anim = Animation::new( 85 | smoke_sprite, 86 | Rectangle::row(0.0, 0.0, 64.0, 64.0) 87 | .take(6) 88 | .collect(), 89 | Duration::from_secs_f32(0.05), 90 | ); 91 | 92 | let smoke_anim_frames = smoke_anim.frames().len() as u8; 93 | 94 | let mgr = Self { 95 | last_updated_time: Instant::now(), 96 | last_explosion_added_time: Instant::now(), 97 | last_smoke_added_time: Instant::now(), 98 | explosion_anim, 99 | explosion_anim_frames, 100 | smoke_anim, 101 | smoke_anim_frames, 102 | explosions: Vec::with_capacity(12), 103 | smokes: Vec::with_capacity(12), 104 | }; 105 | 106 | println!( 107 | "Built OneOffAnimationManager in {}ms", 108 | now.elapsed().as_millis() 109 | ); 110 | 111 | mgr 112 | } 113 | 114 | pub fn add_explosion(&mut self, position: Vec2) { 115 | if !self.can_add_explosion() { 116 | return; 117 | } 118 | self.last_explosion_added_time = Instant::now(); 119 | let explosion_anim = OneOffAnimation::new(position); 120 | self.explosions.push(explosion_anim); 121 | } 122 | 123 | fn can_add_smoke(&self) -> bool { 124 | let elapsed = self.last_smoke_added_time.elapsed(); 125 | 126 | elapsed > Duration::from_secs_f32(0.2) 127 | } 128 | 129 | fn can_add_explosion(&self) -> bool { 130 | let elapsed = self.last_explosion_added_time.elapsed(); 131 | 132 | elapsed > Duration::from_secs_f32(0.2) 133 | } 134 | 135 | pub fn add_smoke(&mut self, position: Vec2) { 136 | if !self.can_add_smoke() { 137 | // Avoid spawning many smoke animations in the same 138 | // place (e.g. if the fireball hits the 139 | // enemy but he doesn't die) 140 | return; 141 | } 142 | self.last_smoke_added_time = Instant::now(); 143 | let smoke_anim = OneOffAnimation::new(position); 144 | self.smokes.push(smoke_anim); 145 | } 146 | 147 | pub fn update(&mut self) { 148 | self.clean_up(); 149 | 150 | if !self.can_update_frames() { 151 | return; 152 | } 153 | 154 | self.last_updated_time = Instant::now(); 155 | 156 | for explosion in &mut self.explosions { 157 | explosion.current_frame += 1; 158 | } 159 | 160 | for smoke in &mut self.smokes { 161 | smoke.current_frame += 1; 162 | } 163 | } 164 | 165 | fn can_update_frames(&self) -> bool { 166 | let elapsed = self.last_updated_time.elapsed(); 167 | 168 | elapsed > Duration::from_secs_f32(0.10) 169 | } 170 | 171 | pub fn draw(&mut self, ctx: &mut Context) { 172 | for explosion in &self.explosions { 173 | self.explosion_anim.set_current_frame_index( 174 | explosion.current_frame as usize, 175 | ); 176 | self.explosion_anim.draw( 177 | ctx, 178 | DrawParams::new() 179 | .position(explosion.position) 180 | .origin(Vec2::new(16.0, 16.0)), 181 | ); 182 | } 183 | 184 | for smoke in &self.smokes { 185 | self.smoke_anim.set_current_frame_index( 186 | smoke.current_frame as usize, 187 | ); 188 | self.smoke_anim.draw( 189 | ctx, 190 | DrawParams::new() 191 | .position(smoke.position) 192 | .origin(Vec2::new(16.0, 16.0)), 193 | ); 194 | } 195 | } 196 | } 197 | -------------------------------------------------------------------------------- /src/background.rs: -------------------------------------------------------------------------------- 1 | use tetra::{ 2 | graphics::{self, Color, DrawParams, Texture}, 3 | math::Vec2, 4 | Context, 5 | }; 6 | 7 | use crate::resources; 8 | 9 | pub struct Background { 10 | /// Actual grass background textures 11 | grass: Grass, 12 | grass_1: Texture, 13 | grass_2: Texture, 14 | rock_1: Texture, 15 | rock_2: Texture, 16 | } 17 | 18 | struct Grass { 19 | left: Texture, 20 | lower_right: Texture, 21 | lower_left: Texture, 22 | lower: Texture, 23 | top_left: Texture, 24 | top: Texture, 25 | top_right: Texture, 26 | right: Texture, 27 | } 28 | 29 | impl Grass { 30 | pub fn load(ctx: &mut Context) -> Self { 31 | Self { 32 | left: Texture::from_encoded( 33 | ctx, 34 | resources::GRASS_LEFT, 35 | ) 36 | .unwrap(), 37 | lower: Texture::from_encoded( 38 | ctx, 39 | resources::GRASS_LOWER, 40 | ) 41 | .unwrap(), 42 | lower_left: Texture::from_encoded( 43 | ctx, 44 | resources::GRASS_LOWER_LEFT, 45 | ) 46 | .unwrap(), 47 | lower_right: Texture::from_encoded( 48 | ctx, 49 | resources::GRASS_LOWER_RIGHT, 50 | ) 51 | .unwrap(), 52 | top_left: Texture::from_encoded( 53 | ctx, 54 | resources::GRASS_TOP_LEFT, 55 | ) 56 | .unwrap(), 57 | top: Texture::from_encoded( 58 | ctx, 59 | resources::GRASS_TOP, 60 | ) 61 | .unwrap(), 62 | top_right: Texture::from_encoded( 63 | ctx, 64 | resources::GRASS_TOP_RIGHT, 65 | ) 66 | .unwrap(), 67 | right: Texture::from_encoded( 68 | ctx, 69 | resources::GRASS_RIGHT, 70 | ) 71 | .unwrap(), 72 | } 73 | } 74 | 75 | pub fn draw(&self, ctx: &mut Context) { 76 | for x in (32..725).step_by(75) { 77 | self.lower.draw( 78 | ctx, 79 | DrawParams::new() 80 | .position(Vec2::new(x as f32, 768.0)), 81 | ); 82 | } 83 | 84 | for y in (32..768).step_by(32) { 85 | self.left.draw( 86 | ctx, 87 | DrawParams::new() 88 | .position(Vec2::new(0.0, y as f32)), 89 | ); 90 | } 91 | 92 | for y in (32..768).step_by(32) { 93 | self.right.draw( 94 | ctx, 95 | DrawParams::new() 96 | .position(Vec2::new(768., y as f32)), 97 | ); 98 | } 99 | 100 | for x in (32..770).step_by(70) { 101 | self.top.draw( 102 | ctx, 103 | DrawParams::new() 104 | .position(Vec2::new(x as f32, 0.0)), 105 | ); 106 | } 107 | 108 | self.lower_left.draw( 109 | ctx, 110 | DrawParams::new().position(Vec2::new(0.0, 768.0)), 111 | ); 112 | self.lower_right.draw( 113 | ctx, 114 | DrawParams::new().position(Vec2::new(768.0, 768.0)), 115 | ); 116 | self.top_left.draw( 117 | ctx, 118 | DrawParams::new().position(Vec2::new(0., 0.)), 119 | ); 120 | self.top_right.draw( 121 | ctx, 122 | DrawParams::new().position(Vec2::new(768., 0.0)), 123 | ); 124 | } 125 | } 126 | 127 | const ROCK_1_POINTS: [Vec2; 4] = [ 128 | Vec2::new(50.0, 60.), 129 | Vec2::new(150.0, 260.), 130 | Vec2::new(350.0, 260.), 131 | Vec2::new(50.0, 660.), 132 | ]; 133 | 134 | const ROCK_2_POINTS: [Vec2; 3] = [ 135 | Vec2::new(120.0, 502.), 136 | Vec2::new(320.0, 132.), 137 | Vec2::new(650.0, 660.), 138 | ]; 139 | 140 | const GRASS_1_POINTS: [Vec2; 6] = [ 141 | Vec2::new(150.0, 160.), 142 | Vec2::new(220.0, 120.), 143 | Vec2::new(290.0, 520.), 144 | Vec2::new(720.0, 730.), 145 | Vec2::new(750.0, 260.), 146 | Vec2::new(675.0, 360.), 147 | ]; 148 | 149 | const GRASS_2_POINTS: [Vec2; 4] = [ 150 | Vec2::new(320.0, 520.), 151 | Vec2::new(520.0, 530.), 152 | Vec2::new(150.0, 260.), 153 | Vec2::new(575.0, 660.), 154 | ]; 155 | 156 | impl Background { 157 | pub fn new(ctx: &mut Context) -> Self { 158 | Self { 159 | grass: Grass::load(ctx), 160 | grass_1: Texture::from_encoded( 161 | ctx, 162 | resources::GRASS_DETAIL_1, 163 | ) 164 | .unwrap(), 165 | grass_2: Texture::from_encoded( 166 | ctx, 167 | resources::GRASS_DETAIL_2, 168 | ) 169 | .unwrap(), 170 | rock_1: Texture::from_encoded(ctx, resources::ROCK1) 171 | .unwrap(), 172 | rock_2: Texture::from_encoded(ctx, resources::ROCK2) 173 | .unwrap(), 174 | } 175 | } 176 | 177 | pub fn draw(&self, ctx: &mut Context) { 178 | let scale = Vec2::new(1.5, 1.5); 179 | 180 | graphics::clear( 181 | ctx, 182 | Color::rgb( 183 | 118.0 / 255.0, 184 | 197.0 / 255.0, 185 | 100.0 / 255.0, 186 | ), 187 | ); 188 | 189 | self.grass.draw(ctx); 190 | 191 | for point in &GRASS_1_POINTS { 192 | self.grass_1.draw( 193 | ctx, 194 | DrawParams::new() 195 | .position(*point) 196 | .scale(scale) 197 | .color(Color::BLUE), 198 | ); 199 | } 200 | 201 | for point in &GRASS_2_POINTS { 202 | self.grass_2.draw( 203 | ctx, 204 | DrawParams::new() 205 | .position(*point) 206 | .scale(scale) 207 | .color(Color::BLUE), 208 | ); 209 | } 210 | 211 | for point in &ROCK_1_POINTS { 212 | self.rock_1.draw( 213 | ctx, 214 | DrawParams::new().position(*point).scale(scale), 215 | ); 216 | } 217 | 218 | for point in &ROCK_2_POINTS { 219 | self.rock_2.draw( 220 | ctx, 221 | DrawParams::new().position(*point).scale(scale), 222 | ); 223 | } 224 | } 225 | } 226 | -------------------------------------------------------------------------------- /src/enemy.rs: -------------------------------------------------------------------------------- 1 | use std::time::Duration; 2 | 3 | use rand::{ 4 | distributions::Uniform, prelude::Distribution, 5 | seq::SliceRandom, Rng, 6 | }; 7 | use tetra::{graphics::Rectangle, math::Vec2, Context}; 8 | 9 | use crate::{ 10 | animation::CannonballAnimation, 11 | debug_println, 12 | humanoid::{Humanoid, HumanoidType}, 13 | oneoffanim::OneOffAnimationManager, 14 | projectile::{Projectile, ProjectileManager}, 15 | textures::GruntTextures, 16 | timer::Timer, 17 | traits::Cleanable, 18 | }; 19 | 20 | pub struct EnemyManager { 21 | /// All enemies currently spawned 22 | pub enemies: Vec, 23 | /// Times the interval in which enemies can be spawned 24 | spawn_timer: Timer, 25 | /// Average enemy velocity 26 | avg_enemy_vel: f32, 27 | /// Spawns and cleans up projectiles coming from enemies 28 | projectile_mgr: ProjectileManager, 29 | /// All enemy textures already loaded into memory 30 | textures: GruntTextures, 31 | } 32 | 33 | impl Cleanable for EnemyManager { 34 | fn clean_up(&mut self) { 35 | let enemies_before = self.enemies.len(); 36 | 37 | self.enemies.retain(|enemy| !enemy.is_dead()); 38 | 39 | if self.enemies.len() < enemies_before { 40 | debug_println!( 41 | "[LOG] {} enemies dropped", 42 | enemies_before - self.enemies.len() 43 | ); 44 | } 45 | } 46 | } 47 | 48 | impl EnemyManager { 49 | pub fn new(ctx: &mut Context) -> Self { 50 | let cannonball_animation = 51 | CannonballAnimation::build(ctx); 52 | 53 | Self { 54 | enemies: Vec::with_capacity(24), 55 | avg_enemy_vel: 1.0, 56 | spawn_timer: Timer::start_now_with_interval( 57 | Duration::from_secs_f64(1.5), 58 | ), 59 | projectile_mgr: ProjectileManager::new( 60 | cannonball_animation, 61 | ), 62 | textures: GruntTextures::load(ctx), 63 | } 64 | } 65 | 66 | fn generate_spawn_location( 67 | rng: &mut R, 68 | ) -> (f32, f32) { 69 | // These unwraps here are all safe 70 | let boundary = *[0., 800.].choose(rng).unwrap(); 71 | 72 | let range = Uniform::from(0. ..=800.); 73 | let pos = range.sample(rng); 74 | 75 | if rng.gen_bool(0.5) { 76 | (pos, boundary) 77 | } else { 78 | (boundary, pos) 79 | } 80 | } 81 | 82 | pub fn calc_score(&self) -> u64 { 83 | let enemy_score = |kind| match kind { 84 | HumanoidType::BasicEnemy => 100, 85 | HumanoidType::StrongerEnemy => 250, 86 | HumanoidType::BadassEnemy => 500, 87 | HumanoidType::Boss => 1250, 88 | HumanoidType::Player => unreachable!(), 89 | }; 90 | 91 | self.enemies 92 | .iter() 93 | .map(|e| e.kind()) 94 | .map(enemy_score) 95 | .sum() 96 | } 97 | 98 | pub fn spawn_enemy( 99 | &mut self, 100 | kind: HumanoidType, 101 | rng: &mut R, 102 | ) { 103 | self.spawn_timer.reset(); 104 | 105 | let (lives, allowed_to_shoot, shooting_wait_time) = 106 | match kind { 107 | HumanoidType::Player => unreachable!(), 108 | HumanoidType::BasicEnemy => { 109 | (1, false, Duration::from_secs_f32(0.0)) 110 | } 111 | HumanoidType::StrongerEnemy => { 112 | (2, true, Duration::from_secs_f32(1.0)) 113 | } 114 | HumanoidType::BadassEnemy => { 115 | (3, true, Duration::from_secs_f32(0.25)) 116 | } 117 | HumanoidType::Boss => { 118 | (10, true, Duration::from_secs_f32(0.10)) 119 | } 120 | }; 121 | 122 | let texture = 123 | self.textures.choose_enemy_from_kind(kind, rng); 124 | 125 | let enemy_vel = Vec2::new( 126 | rng.gen_range(0.3..0.7) + self.avg_enemy_vel, 127 | rng.gen_range(0.3..0.7) + self.avg_enemy_vel, 128 | ); 129 | 130 | self.avg_enemy_vel += 131 | (enemy_vel.x + enemy_vel.y) / 256.0; 132 | 133 | let (x, y) = Self::generate_spawn_location(rng); 134 | 135 | let enemy = Humanoid::new( 136 | lives, 137 | texture, 138 | Vec2::new(x, y), 139 | enemy_vel, 140 | allowed_to_shoot, 141 | shooting_wait_time, 142 | kind, 143 | ); 144 | self.enemies.push(enemy); 145 | } 146 | 147 | pub fn can_spawn(&self) -> bool { 148 | self.spawn_timer.is_ready() 149 | } 150 | 151 | pub fn update( 152 | &mut self, 153 | ctx: &mut Context, 154 | player_pos: Vec2, 155 | ) { 156 | // Clean up dead enemies 157 | self.clean_up(); 158 | 159 | self.projectile_mgr.advance_animation(ctx); 160 | 161 | for enemy in &mut self.enemies { 162 | 163 | let ( 164 | is_fast_shooting, 165 | is_fast_running, 166 | is_triple_shooting, 167 | ) = enemy.power_ups.currently_active(); 168 | let velocity = if is_fast_shooting { 169 | Vec2 { x: 7.5, y: 7.5 } 170 | } else { 171 | Vec2 { x: 4.5, y: 4.5 } 172 | }; 173 | 174 | if enemy.can_fire() { 175 | let angle_to_player_deg = 176 | enemy.angle_to_pos(player_pos).to_degrees(); 177 | self.projectile_mgr.shoot( 178 | is_triple_shooting, 179 | angle_to_player_deg, 180 | enemy.position, 181 | velocity, 182 | ); 183 | enemy.shooting_behavior.register_fire(); 184 | } 185 | 186 | // Advance the animation of all enemies and update 187 | // their locations 188 | enemy.advance_animation(ctx); 189 | enemy.head_to(is_fast_running, player_pos); 190 | } 191 | } 192 | 193 | pub fn check_for_fireball_collisions( 194 | &mut self, 195 | enemy_rects: &[Rectangle], 196 | fireballs: &[Projectile], 197 | one_off_anim_mgr: &mut OneOffAnimationManager, 198 | ) { 199 | let fireball_rects = fireballs 200 | .iter() 201 | .map(Projectile::position) 202 | .map(Vec2::into_tuple) 203 | .map(|(x, y)| { 204 | Rectangle::new(x + 5.0, y + 5.0, 32.0, 32.0) 205 | }); 206 | 207 | for fireball in fireball_rects { 208 | for (enemy, enemy_rect) in 209 | self.enemies.iter_mut().zip(enemy_rects) 210 | { 211 | if enemy_rect.intersects(&fireball) { 212 | let (x, y) = 213 | (fireball.x + 5.0, fireball.y + 5.0); 214 | one_off_anim_mgr 215 | .add_explosion(Vec2 { x, y }); 216 | 217 | enemy.take_hit(); 218 | } 219 | } 220 | } 221 | } 222 | 223 | pub fn check_for_cannonball_collisions( 224 | &self, 225 | player: &mut Humanoid, 226 | one_off_anim_mgr: &mut OneOffAnimationManager, 227 | ) { 228 | let player_rect = player.rectangle(); 229 | for cannon in self.projectile_mgr.projectiles() { 230 | let cannon_pos = cannon.position(); 231 | let cannon_rect = Rectangle::new( 232 | cannon_pos.x, 233 | cannon_pos.y, 234 | 16.0, 235 | 16.0, 236 | ); 237 | if cannon_rect.intersects(&player_rect) { 238 | player.take_hit(); 239 | one_off_anim_mgr.add_smoke(cannon_pos); 240 | } 241 | } 242 | } 243 | 244 | pub fn draw(&mut self, ctx: &mut Context) { 245 | for enemy in self.enemies.iter_mut() { 246 | enemy.draw(ctx); 247 | } 248 | self.projectile_mgr.draw(ctx); 249 | } 250 | } 251 | -------------------------------------------------------------------------------- /src/humanoid.rs: -------------------------------------------------------------------------------- 1 | use std::time::{Duration, Instant}; 2 | 3 | use tetra::{ 4 | graphics::{ 5 | animation::Animation, DrawParams, Rectangle, Texture, 6 | }, 7 | input::{self, Key}, 8 | math::Vec2, 9 | Context, 10 | }; 11 | 12 | use crate::{ 13 | animation::HumanoidAnimation, powerup::ActivePowerUps, 14 | traits::Cleanable, Direction, BOUNDS, 15 | }; 16 | 17 | #[derive(Clone, Copy)] 18 | pub enum HumanoidType { 19 | Player, 20 | BasicEnemy, 21 | StrongerEnemy, 22 | BadassEnemy, 23 | Boss, 24 | } 25 | 26 | pub struct ShootingBehavior { 27 | /// Determines if the humanoid can shoot 28 | pub allowed_to_shoot: bool, 29 | /// The last moment that this humanoid shot a projectile 30 | last_projectile_thrown_time: Instant, 31 | /// The interval in which this humanoid can shoot 32 | shooting_wait_time: Duration, 33 | } 34 | 35 | impl ShootingBehavior { 36 | pub fn new( 37 | allowed_to_shoot: bool, 38 | shooting_wait_time: Duration, 39 | ) -> Self { 40 | Self { 41 | allowed_to_shoot, 42 | last_projectile_thrown_time: Instant::now(), 43 | shooting_wait_time, 44 | } 45 | } 46 | 47 | pub fn can_fire(&self) -> bool { 48 | let time_since_last_thrown = 49 | self.last_projectile_thrown_time.elapsed(); 50 | 51 | self.allowed_to_shoot 52 | && time_since_last_thrown >= self.shooting_wait_time 53 | } 54 | 55 | pub fn register_fire(&mut self) { 56 | self.last_projectile_thrown_time = Instant::now(); 57 | } 58 | 59 | pub fn set_shooting_wait_time( 60 | &mut self, 61 | duration: Duration, 62 | ) { 63 | self.shooting_wait_time = duration; 64 | } 65 | } 66 | 67 | /// A humanoid: either the player or enemies.s 68 | pub struct Humanoid { 69 | pub hearts: u8, 70 | pub direction: Direction, 71 | pub animation: HumanoidAnimation, 72 | pub power_ups: ActivePowerUps, 73 | pub position: Vec2, 74 | pub velocity: Vec2, 75 | pub shooting_behavior: ShootingBehavior, 76 | /// Set when the humanoid should 'flicker', such as when the 77 | /// player is hit 78 | pub flickering: u16, 79 | pub kind: HumanoidType, 80 | } 81 | 82 | impl Cleanable for Humanoid { 83 | fn clean_up(&mut self) { 84 | for power_up in self.power_ups.slots.iter_mut() { 85 | if let Some(moment_started) = power_up { 86 | if moment_started.elapsed() 87 | >= Duration::from_secs(5) 88 | { 89 | *power_up = None; 90 | } 91 | } 92 | } 93 | } 94 | } 95 | 96 | impl Humanoid { 97 | pub fn new( 98 | hearts: u8, 99 | texture: Texture, 100 | position: Vec2, 101 | velocity: Vec2, 102 | allowed_to_shoot: bool, 103 | shooting_wait_time: Duration, 104 | kind: HumanoidType, 105 | ) -> Self { 106 | Self { 107 | hearts, 108 | flickering: 0, 109 | direction: Direction::North, 110 | animation: HumanoidAnimation::new(texture), 111 | shooting_behavior: ShootingBehavior::new( 112 | allowed_to_shoot, 113 | shooting_wait_time, 114 | ), 115 | power_ups: ActivePowerUps::new(), 116 | position, 117 | velocity, 118 | kind, 119 | } 120 | } 121 | 122 | pub fn can_fire(&self) -> bool { 123 | self.shooting_behavior.can_fire() 124 | } 125 | 126 | pub fn kind(&self) -> HumanoidType { 127 | self.kind 128 | } 129 | 130 | pub fn advance_animation(&mut self, ctx: &mut Context) { 131 | match self.direction { 132 | Direction::North => { 133 | self.animation.backside.advance(ctx) 134 | } 135 | Direction::West | Direction::East => { 136 | self.animation.leftside.advance(ctx) 137 | } 138 | Direction::South => { 139 | self.animation.frontside.advance(ctx) 140 | } 141 | } 142 | } 143 | 144 | fn get_animation_ref(&self) -> (&Animation, Vec2) { 145 | let scale = Vec2::new(3., 3.); 146 | match self.direction { 147 | Direction::North => { 148 | (&self.animation.backside, scale) 149 | } 150 | Direction::West => (&self.animation.leftside, scale), 151 | Direction::East => ( 152 | &self.animation.leftside, 153 | Vec2 { x: -3., y: 3. }, 154 | ), 155 | Direction::South => { 156 | (&self.animation.frontside, scale) 157 | } 158 | } 159 | } 160 | 161 | pub fn draw(&mut self, ctx: &mut Context) { 162 | if self.flickering > 0 { 163 | self.flickering -= 1; 164 | if self.flickering % 2 == 0 { 165 | return; 166 | } 167 | } 168 | 169 | let (animation, scale) = self.get_animation_ref(); 170 | 171 | animation.draw( 172 | ctx, 173 | DrawParams::new() 174 | .position(self.position) 175 | .origin(Vec2::new(8.0, 8.0)) 176 | .scale(scale), 177 | ); 178 | } 179 | 180 | pub fn update_from_key_press( 181 | &mut self, 182 | ctx: &mut Context, 183 | hero_speed: f32, 184 | ) { 185 | // Drag is only applied to the previous frame movement 186 | const HERO_MOVING_DRAG: f32 = 1.4; 187 | const HERO_STOPPING_DRAG: f32 = 1.9; 188 | 189 | let is_key_pressed_f32 = 190 | |key| input::is_key_down(ctx, key) as u8 as f32; 191 | // Movement for the axis x and y, can be -1, 0 or 1 192 | // We assume that 1.0 - 1.0 is always perfectly 0.0 193 | let x = is_key_pressed_f32(Key::D) 194 | - is_key_pressed_f32(Key::A); 195 | let y = is_key_pressed_f32(Key::S) 196 | - is_key_pressed_f32(Key::W); 197 | 198 | // Will be added to self.velocity 199 | let mut new_velocity = Vec2 { x, y }; 200 | 201 | let dir = match (x as i32, y as i32) { 202 | (-1, 0) => Direction::West, 203 | (0, 1) => Direction::South, 204 | (1, 0) => Direction::East, 205 | (0, -1) => Direction::North, 206 | (1, 1) => Direction::South, 207 | (1, -1) => Direction::East, 208 | (_, _) => self.direction, 209 | }; 210 | 211 | self.direction = dir; 212 | 213 | // Movement is in diagonal if both x and y contain 214 | // non-zero values 215 | let is_diagonal = x != 0.0 && y != 0.0; 216 | // Moving in the diagonal shouldn't be faster than in 217 | // vertical or horizontal, so we make sure that 218 | // the length of this Vec2 is always 1 (x² + y² == 1) 219 | // X and Y will equal to 0.707106... 220 | // 221 | // Need if because .normalize() on Vec2 {0, 0} is chaotic 222 | if is_diagonal { 223 | new_velocity.normalize(); 224 | } 225 | 226 | // Apply drag. 227 | // This way of applying drag depends on the framerate, 228 | // but that's not a huge problem, 229 | // because currently all our movement does. 230 | if new_velocity.magnitude() == 0.0 { 231 | // If no input was added, apply more drag to stop the 232 | // hero 233 | self.velocity /= HERO_STOPPING_DRAG; 234 | } else { 235 | self.velocity /= HERO_MOVING_DRAG; 236 | } 237 | 238 | let new_pos = self.position 239 | + new_velocity 240 | + self.velocity * hero_speed; 241 | 242 | if BOUNDS.contains(new_pos) { 243 | self.position = new_pos; 244 | self.velocity += new_velocity; 245 | } 246 | } 247 | 248 | /// Make this [`Humanoid`] look in the given direction (in 249 | /// degrees) 250 | pub fn look_to(&mut self, direction_deg: f32) { 251 | let direction = |mut angle: f32| -> i32 { 252 | // Clamp angle to avoid results not in 0..=3 253 | if angle < 0. { 254 | angle += 360.; 255 | } 256 | let angle = angle as i32; 257 | (45 + angle) % 360 / 90 258 | }; 259 | 260 | self.direction = match direction(direction_deg) { 261 | 0 => Direction::East, 262 | 1 => Direction::North, 263 | 2 => Direction::West, 264 | 3 => Direction::South, 265 | _ => unreachable!(), 266 | } 267 | } 268 | 269 | /// Returns the angle between the current position of this 270 | /// `Humanoid` and `destination'. 271 | pub fn angle_to_pos(&self, destination: Vec2) -> f32 { 272 | let pos = self.position; 273 | 274 | let delta_x = destination.x - pos.x; 275 | let delta_y = pos.y - destination.y; 276 | 277 | // in radians! 278 | f32::atan2(delta_y, delta_x) 279 | } 280 | 281 | pub fn rectangle(&self) -> Rectangle { 282 | Rectangle::new( 283 | self.position.x, 284 | self.position.y, 285 | 16.0, 286 | 16.0, 287 | ) 288 | } 289 | 290 | pub fn head_to(&mut self, is_running_fast: bool, destination: Vec2) { 291 | let modifier = if is_running_fast { 1.5 } else { 1.0 }; 292 | let theta_rad = self.angle_to_pos(destination); 293 | 294 | self.position += 295 | Vec2::new(f32::cos(theta_rad), -f32::sin(theta_rad)) 296 | * self.velocity * modifier; 297 | 298 | // Sets the Humanoid's Direction according to the 299 | // calculated angle 300 | self.look_to(theta_rad.to_degrees()); 301 | } 302 | 303 | /// Checks if the sprite of `self` collided with one of the 304 | /// given `Humanoid`s. 305 | pub fn collided_with_bodies( 306 | &self, 307 | bodies: &[Humanoid], 308 | ) -> (bool, Vec) { 309 | let player_rect = self.rectangle(); 310 | let body_rects: Vec<_> = bodies 311 | .iter() 312 | .map(|e| e.position) 313 | .map(Vec2::into_tuple) 314 | .map(|(x, y)| Rectangle::new(x, y, 16.0, 16.0)) 315 | .collect(); 316 | 317 | for body_rect in &body_rects { 318 | if player_rect.intersects(body_rect) { 319 | return (true, body_rects); 320 | } 321 | } 322 | 323 | (false, body_rects) 324 | } 325 | 326 | pub fn is_dead(&self) -> bool { 327 | self.hearts == 0 328 | } 329 | 330 | pub fn take_hit(&mut self) { 331 | if self.flickering == 0 { 332 | if self.hearts > 0 { 333 | self.hearts -= 1; 334 | } 335 | self.flickering = 30; 336 | } 337 | } 338 | } 339 | -------------------------------------------------------------------------------- /src/powerup.rs: -------------------------------------------------------------------------------- 1 | use std::time::{Duration, Instant}; 2 | 3 | use arrayvec::ArrayVec; 4 | use rand::{ 5 | distributions::Standard, prelude::Distribution, Rng, 6 | }; 7 | use tetra::{ 8 | graphics::{DrawParams, Rectangle}, 9 | math::Vec2, 10 | Context, 11 | }; 12 | 13 | use crate::{ 14 | humanoid::Humanoid, panel::Panel, textures::PowerUpTextures, 15 | timer::Timer, 16 | }; 17 | 18 | /// New power-ups spawn every 5 seconds 19 | const POWER_UP_SPAWN_INTERVAL: Duration = Duration::from_secs(3); 20 | 21 | /// Power-ups, after spawned, are available to be picked up 22 | /// within 10 seconds from spawning 23 | const POWER_UP_AVAILABILITY_INTERVAL: Duration = 24 | Duration::from_secs(10); 25 | 26 | #[derive(Debug, Hash, Clone, Copy, Eq, PartialEq)] 27 | #[repr(C)] 28 | pub enum PowerUpKind { 29 | AdditionalHeart, 30 | FasterShooting, 31 | FasterRunning, 32 | TripleShooting, 33 | } 34 | 35 | impl From for u8 { 36 | fn from(kind: PowerUpKind) -> Self { 37 | match kind { 38 | PowerUpKind::AdditionalHeart => 0, 39 | PowerUpKind::FasterShooting => 1, 40 | PowerUpKind::FasterRunning => 2, 41 | PowerUpKind::TripleShooting => 3, 42 | } 43 | } 44 | } 45 | 46 | pub struct ActivePowerUps { 47 | pub slots: [Option; 3], 48 | } 49 | 50 | impl ActivePowerUps { 51 | pub fn new() -> Self { 52 | Self { slots: [None; 3] } 53 | } 54 | 55 | pub fn currently_active(&self) -> (bool, bool, bool) { 56 | ( 57 | self.get(PowerUpKind::FasterShooting).is_some(), 58 | self.get(PowerUpKind::FasterRunning).is_some(), 59 | self.get(PowerUpKind::TripleShooting).is_some(), 60 | ) 61 | } 62 | 63 | /// How many kinds of power-ups are currently active 64 | pub fn len(&self) -> usize { 65 | let (a, b, c) = self.currently_active(); 66 | 67 | ((a as u8) + (b as u8) + (c as u8)) as usize 68 | } 69 | 70 | /// An iterator of all active power-ups when called 71 | pub fn iter(&self) -> impl Iterator { 72 | let mut power_ups: ArrayVec = 73 | ArrayVec::new(); 74 | 75 | let (fast_shooting, fast_running, triple_shooting) = 76 | self.currently_active(); 77 | 78 | if fast_running { 79 | power_ups.push(PowerUpKind::FasterRunning) 80 | } 81 | 82 | if fast_shooting { 83 | power_ups.push(PowerUpKind::FasterShooting) 84 | } 85 | 86 | if triple_shooting { 87 | power_ups.push(PowerUpKind::TripleShooting) 88 | } 89 | 90 | power_ups.into_iter() 91 | } 92 | 93 | pub fn activate_power_up(&mut self, kind: PowerUpKind) { 94 | let idx: u8 = kind.into(); 95 | 96 | self.slots[idx as usize - 1] = Some(Instant::now()); 97 | } 98 | 99 | fn get(&self, kind: PowerUpKind) -> Option { 100 | let idx: u8 = kind.into(); 101 | 102 | self.slots[idx as usize - 1] 103 | } 104 | } 105 | 106 | #[derive(Debug)] 107 | struct PowerUp { 108 | /// What sort of power-up this iss 109 | kind: PowerUpKind, 110 | /// Times how long this power-up will be available for 111 | expiration_timer: Timer, 112 | /// The position the power-up was spawned in 113 | position: Vec2, 114 | /// Whether or not this power-up has been consumed 115 | was_consumed: bool, 116 | /// Set if the power-up is flickering (that is, next to 117 | /// expirating) 118 | flickering: u8, 119 | } 120 | 121 | impl PowerUp { 122 | pub fn is_expired(&self) -> bool { 123 | self.expiration_timer.is_ready() 124 | } 125 | 126 | pub fn flicker_if_almost_expiring(&mut self) { 127 | // If flickering is already set then do nothing 128 | if self.flickering > 0 { 129 | return; 130 | } 131 | 132 | let elapsed = self.expiration_timer.elapsed(); 133 | if elapsed > Duration::from_secs(8) { 134 | // Only two more seconds available to get the 135 | // power-up, so we'll signal this to the 136 | // player through flickering 137 | self.flickering = 120; 138 | } 139 | } 140 | } 141 | 142 | impl Distribution for Standard { 143 | fn sample( 144 | &self, 145 | rng: &mut R, 146 | ) -> PowerUpKind { 147 | match rng.gen_range(0..=3) { 148 | 0 => PowerUpKind::AdditionalHeart, 149 | 1 => PowerUpKind::FasterShooting, 150 | 2 => PowerUpKind::TripleShooting, 151 | _ => PowerUpKind::FasterRunning, 152 | } 153 | } 154 | } 155 | 156 | pub struct PowerUpManager { 157 | // The power-ups laying on the ground 158 | powerups: Vec, 159 | spawn_timer: Timer, 160 | panel: Panel, 161 | power_up_textures: PowerUpTextures, 162 | } 163 | 164 | impl PowerUpManager { 165 | pub fn new(ctx: &mut Context) -> Self { 166 | Self { 167 | power_up_textures: PowerUpTextures::load(ctx), 168 | powerups: Vec::with_capacity(5), 169 | spawn_timer: Timer::start_now_with_interval( 170 | POWER_UP_SPAWN_INTERVAL, 171 | ), 172 | panel: Panel::new(ctx), 173 | } 174 | } 175 | 176 | /// Check if the given humanoid collided with a power-up 177 | /// laying in the ground. 178 | pub fn check_for_collision( 179 | &mut self, 180 | humanoid: &mut Humanoid, 181 | ) { 182 | let pos = humanoid.position; 183 | let rect = Rectangle::new(pos.x, pos.y, 16.0, 16.0); 184 | for powerup in &mut self.powerups { 185 | let powerup_rect = Rectangle::new( 186 | powerup.position.x, 187 | powerup.position.y, 188 | 32.0, 189 | 32.0, 190 | ); 191 | 192 | if powerup_rect.intersects(&rect) { 193 | powerup.was_consumed = true; 194 | match powerup.kind { 195 | PowerUpKind::AdditionalHeart => { 196 | humanoid.hearts += 1 197 | } 198 | power_up => { 199 | humanoid 200 | .power_ups 201 | .activate_power_up(power_up); 202 | } 203 | } 204 | } 205 | } 206 | } 207 | 208 | pub fn can_spawn(&self) -> bool { 209 | self.spawn_timer.is_ready() 210 | } 211 | 212 | fn draw_powerup_bar( 213 | &self, 214 | ctx: &mut Context, 215 | player_power_ups: &ActivePowerUps, 216 | ) { 217 | let active_powerups_no = player_power_ups.len(); 218 | if active_powerups_no == 0 { 219 | return; 220 | } 221 | 222 | let width = (active_powerups_no as f32) * 16.0 + 10.5; 223 | 224 | self.panel.sprite.draw_nine_slice( 225 | ctx, 226 | &self.panel.config, 227 | width, 228 | 26.0, 229 | DrawParams::new() 230 | .position(Vec2::new(768.0 - width, 60.0)), 231 | ); 232 | 233 | for (kind, spacing) in 234 | player_power_ups.iter().zip(0..active_powerups_no) 235 | { 236 | let spacing = spacing as f32; 237 | match kind { 238 | PowerUpKind::AdditionalHeart => unreachable!(), 239 | PowerUpKind::FasterShooting => self 240 | .power_up_textures 241 | .fire_scroll_sprite 242 | .draw( 243 | ctx, 244 | DrawParams::new().position(Vec2 { 245 | x: 746. - 16.0 * spacing, 246 | y: 60. + 4., 247 | }), 248 | ), 249 | PowerUpKind::FasterRunning => { 250 | self.power_up_textures.boot_sprite.draw( 251 | ctx, 252 | DrawParams::new().position(Vec2 { 253 | x: 746. - 16.0 * spacing, 254 | y: 60. + 4., 255 | }), 256 | ) 257 | } 258 | PowerUpKind::TripleShooting => { 259 | self.power_up_textures.ring_sprite.draw( 260 | ctx, 261 | DrawParams::new().position(Vec2 { 262 | x: 746. - 16.0 * spacing, 263 | y: 60. + 4., 264 | }), 265 | ) 266 | } 267 | } 268 | } 269 | } 270 | 271 | pub fn draw( 272 | &mut self, 273 | ctx: &mut Context, 274 | player_power_ups: &ActivePowerUps, 275 | ) { 276 | self.draw_powerup_bar(ctx, player_power_ups); 277 | 278 | for powerup in self.powerups.iter_mut() { 279 | if powerup.flickering > 0 { 280 | powerup.flickering -= 1; 281 | if powerup.flickering % 2 == 0 { 282 | continue; 283 | } 284 | } 285 | 286 | match powerup.kind { 287 | PowerUpKind::AdditionalHeart => { 288 | self.power_up_textures.heart_sprite.draw( 289 | ctx, 290 | DrawParams::new() 291 | .position(powerup.position), 292 | ) 293 | } 294 | PowerUpKind::FasterShooting => self 295 | .power_up_textures 296 | .fire_scroll_sprite 297 | .draw( 298 | ctx, 299 | DrawParams::new() 300 | .position(powerup.position) 301 | .scale(Vec2::new(2.5, 2.5)), 302 | ), 303 | PowerUpKind::FasterRunning => { 304 | self.power_up_textures.boot_sprite.draw( 305 | ctx, 306 | DrawParams::new() 307 | .position(powerup.position) 308 | .scale(Vec2::new(2.5, 2.5)), 309 | ) 310 | } 311 | PowerUpKind::TripleShooting => { 312 | self.power_up_textures.ring_sprite.draw( 313 | ctx, 314 | DrawParams::new() 315 | .position(powerup.position) 316 | .scale(Vec2::new(2.5, 2.5)), 317 | ) 318 | } 319 | } 320 | } 321 | } 322 | 323 | pub fn update(&mut self) { 324 | self.powerups 325 | .retain(|p| !p.was_consumed && !p.is_expired()); 326 | 327 | self.powerups 328 | .iter_mut() 329 | .for_each(PowerUp::flicker_if_almost_expiring); 330 | } 331 | 332 | pub fn advance( 333 | &mut self, 334 | rng: &mut R, 335 | player: &mut Humanoid, 336 | ) { 337 | if self.can_spawn() { 338 | self.spawn_power_up(rng); 339 | } 340 | 341 | self.check_for_collision(player); 342 | } 343 | 344 | pub fn spawn_power_up(&mut self, rng: &mut R) { 345 | self.spawn_timer.reset(); 346 | 347 | let position = Vec2 { 348 | x: rng.gen_range(0.0..200.0) * 4.0, 349 | y: rng.gen_range(0.0..200.0) * 4.0, 350 | }; 351 | 352 | let power_up = PowerUp { 353 | kind: rng.gen(), 354 | position, 355 | expiration_timer: Timer::start_now_with_interval( 356 | POWER_UP_AVAILABILITY_INTERVAL, 357 | ), 358 | was_consumed: false, 359 | flickering: 0, 360 | }; 361 | 362 | self.powerups.push(power_up); 363 | } 364 | } 365 | -------------------------------------------------------------------------------- /src/gamestate.rs: -------------------------------------------------------------------------------- 1 | use std::time::{Duration, Instant}; 2 | 3 | use rand::{ 4 | prelude::{SliceRandom, SmallRng}, 5 | SeedableRng, 6 | }; 7 | use tetra::{ 8 | graphics, 9 | graphics::scaling::{ScalingMode, ScreenScaler}, 10 | input::{self, Key}, 11 | time, window, Context, Event, State, 12 | }; 13 | 14 | use crate::{ 15 | background::Background, enemy::EnemyManager, 16 | healthbar::HealthBar, humanoid::HumanoidType, 17 | oneoffanim::OneOffAnimationManager, panel::GameOverPanel, 18 | player::PlayerManager, powerup::PowerUpManager, 19 | timer::Timer, HEIGHT, WIDTH, 20 | }; 21 | 22 | /// Enemy types and their spawn rate percentages for each wave 23 | const WAVES: &[[(HumanoidType, f32); 4]] = &[ 24 | [ 25 | (HumanoidType::BasicEnemy, 0.85), 26 | (HumanoidType::StrongerEnemy, 0.10), 27 | (HumanoidType::BadassEnemy, 0.05), 28 | (HumanoidType::Boss, 0.0), 29 | ], 30 | [ 31 | (HumanoidType::BasicEnemy, 0.75), 32 | (HumanoidType::StrongerEnemy, 0.20), 33 | (HumanoidType::BadassEnemy, 0.05), 34 | (HumanoidType::Boss, 0.0), 35 | ], 36 | [ 37 | (HumanoidType::BasicEnemy, 0.75), 38 | (HumanoidType::StrongerEnemy, 0.20), 39 | (HumanoidType::BadassEnemy, 0.05), 40 | (HumanoidType::Boss, 0.0), 41 | ], 42 | [ 43 | (HumanoidType::BasicEnemy, 0.4), 44 | (HumanoidType::StrongerEnemy, 0.5), 45 | (HumanoidType::BadassEnemy, 0.1), 46 | (HumanoidType::Boss, 0.0), 47 | ], 48 | [ 49 | (HumanoidType::BasicEnemy, 0.1), 50 | (HumanoidType::StrongerEnemy, 0.6), 51 | (HumanoidType::BadassEnemy, 0.3), 52 | (HumanoidType::Boss, 0.0), 53 | ], 54 | [ 55 | (HumanoidType::BasicEnemy, 0.0), 56 | (HumanoidType::StrongerEnemy, 0.55), 57 | (HumanoidType::BadassEnemy, 0.35), 58 | (HumanoidType::Boss, 0.1), 59 | ], 60 | [ 61 | (HumanoidType::BasicEnemy, 0.0), 62 | (HumanoidType::StrongerEnemy, 0.55), 63 | (HumanoidType::BadassEnemy, 0.25), 64 | (HumanoidType::Boss, 0.2), 65 | ], 66 | ]; 67 | 68 | pub struct GameState { 69 | /// The active screen scaler 70 | scaler: ScreenScaler, 71 | /// The textures of the game's background 72 | background: Background, 73 | health_bar: HealthBar, 74 | player_manager: PlayerManager, 75 | power_up_mgr: PowerUpManager, 76 | enemy_mgr: EnemyManager, 77 | one_off_anim_mgr: OneOffAnimationManager, 78 | game_over_panel: GameOverPanel, 79 | rng: SmallRng, 80 | game_score: u64, 81 | current_wave: u8, 82 | /// How long every wave lasts 83 | wave_timer: Timer, 84 | window_title_update_timer: Timer, 85 | #[cfg(debug_assertions)] 86 | diagnostics: Diagnostics, 87 | } 88 | 89 | impl GameState { 90 | pub fn new(ctx: &mut Context) -> tetra::Result { 91 | let now = Instant::now(); 92 | 93 | let game_state = GameState { 94 | player_manager: PlayerManager::new(ctx), 95 | background: Background::new(ctx), 96 | health_bar: HealthBar::new(ctx), 97 | power_up_mgr: PowerUpManager::new(ctx), 98 | scaler: ScreenScaler::with_window_size( 99 | ctx, 100 | WIDTH, 101 | HEIGHT, 102 | ScalingMode::ShowAll, 103 | )?, 104 | game_over_panel: GameOverPanel::new(ctx), 105 | enemy_mgr: EnemyManager::new(ctx), 106 | one_off_anim_mgr: OneOffAnimationManager::new(ctx), 107 | rng: SmallRng::from_entropy(), 108 | game_score: 0, 109 | current_wave: 0, 110 | wave_timer: Timer::start_now_with_interval( 111 | Duration::from_secs(30), 112 | ), 113 | #[cfg(debug_assertions)] 114 | diagnostics: Diagnostics::new(), 115 | window_title_update_timer: 116 | Timer::start_now_with_interval( 117 | Duration::from_secs(1), 118 | ), 119 | }; 120 | 121 | // How long we took to instantiate all textures into GPU 122 | // memory and build the managers 123 | println!( 124 | "Built initial GameState in {}ms", 125 | now.elapsed().as_millis() 126 | ); 127 | 128 | Ok(game_state) 129 | } 130 | 131 | fn check_for_wave_change(&mut self) { 132 | if self.wave_timer.is_ready() 133 | && self.current_wave < (WAVES.len() as u8 - 1) 134 | { 135 | self.current_wave += 1; 136 | self.wave_timer.reset(); 137 | println!( 138 | "Commencing wave {}", 139 | self.current_wave + 1 140 | ); 141 | } 142 | } 143 | 144 | fn check_for_scale_change(&mut self, ctx: &mut Context) { 145 | if input::is_key_pressed(ctx, Key::F1) { 146 | let next = match self.scaler.mode() { 147 | ScalingMode::Fixed => ScalingMode::Stretch, 148 | ScalingMode::Stretch => ScalingMode::ShowAll, 149 | ScalingMode::ShowAll => { 150 | ScalingMode::ShowAllPixelPerfect 151 | } 152 | ScalingMode::ShowAllPixelPerfect => { 153 | ScalingMode::Crop 154 | } 155 | ScalingMode::Crop => { 156 | ScalingMode::CropPixelPerfect 157 | } 158 | ScalingMode::CropPixelPerfect => { 159 | ScalingMode::Fixed 160 | } 161 | _ => ScalingMode::Fixed, 162 | }; 163 | 164 | println!("[LOG] Scaling mode changed to {next:?}"); 165 | 166 | self.scaler.set_mode(next); 167 | } 168 | } 169 | 170 | pub fn is_game_over(&self) -> bool { 171 | self.player_manager.is_player_dead() 172 | } 173 | } 174 | 175 | impl State for GameState { 176 | fn draw(&mut self, ctx: &mut Context) -> tetra::Result { 177 | #[cfg(debug_assertions)] 178 | self.diagnostics.start_polling(); 179 | 180 | graphics::set_canvas(ctx, self.scaler.canvas()); 181 | 182 | self.background.draw(ctx); 183 | 184 | self.player_manager.draw(ctx); 185 | self.enemy_mgr.draw(ctx); 186 | self.power_up_mgr.draw( 187 | ctx, 188 | &self.player_manager.player_mut().power_ups, 189 | ); 190 | self.health_bar.draw(ctx, self.player_manager.hearts()); 191 | self.one_off_anim_mgr.draw(ctx); 192 | 193 | if self.is_game_over() { 194 | self.game_over_panel.draw(ctx); 195 | } 196 | 197 | graphics::reset_canvas(ctx); 198 | self.scaler.draw(ctx); 199 | 200 | // Update the window title only once per second 201 | if self.window_title_update_timer.is_ready() { 202 | self.window_title_update_timer.reset(); 203 | 204 | window::set_title( 205 | ctx, 206 | &format!( 207 | "Endless Trial - {:.0} FPS - Wave: {} - Score: {}", 208 | time::get_fps(ctx), 209 | self.current_wave + 1, 210 | self.game_score 211 | ), 212 | ); 213 | } 214 | 215 | #[cfg(debug_assertions)] 216 | self.diagnostics.finish_polling(PollKind::Drawing); 217 | 218 | Ok(()) 219 | } 220 | 221 | fn update(&mut self, ctx: &mut Context) -> tetra::Result { 222 | #[cfg(debug_assertions)] 223 | self.diagnostics.start_polling(); 224 | 225 | // Checks if the player changed the screen scaling method 226 | self.check_for_scale_change(ctx); 227 | 228 | // Freeze the game logic if the game is over 229 | if self.is_game_over() { 230 | return Ok(()); 231 | } 232 | 233 | // Checks if the current wave is over 234 | self.check_for_wave_change(); 235 | 236 | // Check if the player collided with an enemy. 237 | // 238 | // We return `enemy_rects` here (Vec of Retangles for 239 | // each enemy) in order to reuse it in 240 | // `check_for_fireball_collisions` 241 | let (collided_with_an_enemy, enemy_rects) = self 242 | .player_manager 243 | .player_mut() 244 | .collided_with_bodies(&self.enemy_mgr.enemies); 245 | 246 | if collided_with_an_enemy { 247 | self.player_manager.register_hit(); 248 | } 249 | 250 | // Check if an enemy was hit with a fireball from the 251 | // player 252 | self.enemy_mgr.check_for_fireball_collisions( 253 | &enemy_rects, 254 | self.player_manager.fireballs(), 255 | &mut self.one_off_anim_mgr, 256 | ); 257 | 258 | // Check if the player was hit with a cannonball from an 259 | // enemy 260 | self.enemy_mgr.check_for_cannonball_collisions( 261 | self.player_manager.player_mut(), 262 | &mut self.one_off_anim_mgr, 263 | ); 264 | 265 | // Check if any enemy got a power-up 266 | for enemy in self.enemy_mgr.enemies.iter_mut() { 267 | self.power_up_mgr.check_for_collision(enemy); 268 | } 269 | 270 | self.power_up_mgr.advance( 271 | &mut self.rng, 272 | self.player_manager.player_mut(), 273 | ); 274 | 275 | self.player_manager.update(ctx); 276 | 277 | if self.enemy_mgr.can_spawn() { 278 | let kind = WAVES[self.current_wave as usize] 279 | .choose_weighted(&mut self.rng, |x| x.1) 280 | .expect("WAVES should not be empty") 281 | .0; 282 | self.enemy_mgr.spawn_enemy(kind, &mut self.rng); 283 | } 284 | 285 | // Calculate the enemy score now that new enemies have 286 | // been spawned 287 | let enemy_score = self.enemy_mgr.calc_score(); 288 | 289 | self.one_off_anim_mgr.update(); 290 | 291 | self.enemy_mgr 292 | .update(ctx, self.player_manager.player_position()); 293 | 294 | self.power_up_mgr.update(); 295 | 296 | // If the game score has decreased then enemies have been 297 | // killed, which adds to the game score 298 | self.game_score += 299 | enemy_score - self.enemy_mgr.calc_score(); 300 | 301 | #[cfg(debug_assertions)] 302 | self.diagnostics.finish_polling(PollKind::Update); 303 | 304 | Ok(()) 305 | } 306 | 307 | fn event( 308 | &mut self, 309 | _ctx: &mut Context, 310 | event: Event, 311 | ) -> tetra::Result { 312 | if let Event::Resized { width, height } = event { 313 | self.scaler.set_outer_size(width, height); 314 | } 315 | 316 | Ok(()) 317 | } 318 | } 319 | 320 | #[cfg(debug_assertions)] 321 | struct Diagnostics { 322 | /// How often we print the game diagnostics 323 | /// to stdout 324 | flush_timer: Timer, 325 | /// How much it took in average to draw a new frame 326 | /// during the last polling interval 327 | avg_draw_time: Duration, 328 | /// How much it took in average to update the game state 329 | /// during the last polling interval 330 | avg_update_time: Duration, 331 | current_polling_started: Instant, 332 | times_polled: u32, 333 | } 334 | 335 | #[cfg(debug_assertions)] 336 | impl Diagnostics { 337 | pub fn new() -> Self { 338 | Self { 339 | flush_timer: Timer::start_now_with_interval( 340 | Duration::from_secs(15), 341 | ), 342 | avg_draw_time: Duration::new(0, 0), 343 | avg_update_time: Duration::new(0, 0), 344 | current_polling_started: Instant::now(), 345 | times_polled: 0, 346 | } 347 | } 348 | 349 | pub fn start_polling(&mut self) { 350 | self.current_polling_started = Instant::now() 351 | } 352 | 353 | pub fn finish_polling(&mut self, kind: PollKind) { 354 | self.times_polled += 1; 355 | 356 | let elapsed = self.current_polling_started.elapsed(); 357 | 358 | if self.times_polled == 1 { 359 | match kind { 360 | PollKind::Drawing => { 361 | self.avg_draw_time = elapsed 362 | } 363 | PollKind::Update => { 364 | self.avg_update_time = elapsed 365 | } 366 | } 367 | return; 368 | } 369 | 370 | match kind { 371 | PollKind::Drawing => { 372 | self.avg_draw_time += elapsed; 373 | } 374 | PollKind::Update => { 375 | self.avg_update_time += elapsed; 376 | } 377 | } 378 | 379 | if self.flush_timer.is_ready() { 380 | self.flush_timer.reset(); 381 | let avg_draw_time = 382 | self.avg_draw_time / self.times_polled; 383 | let avg_update_time = 384 | self.avg_update_time / self.times_polled; 385 | 386 | println!("Last {} frames: avg. draw {}ns, avg. update {}ns", self.times_polled, avg_draw_time.as_nanos(), avg_update_time.as_nanos()); 387 | } 388 | } 389 | } 390 | 391 | #[cfg(debug_assertions)] 392 | #[derive(Clone, Copy)] 393 | enum PollKind { 394 | Drawing, 395 | Update, 396 | } 397 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | --------------------------------------------------------------------------------