wasm + include json

This commit is contained in:
WanderingPenwing 2024-10-07 09:28:32 +02:00
parent f27f783501
commit efdb86c081
4 changed files with 56 additions and 94 deletions

View file

@ -9,14 +9,13 @@ pub fn setup(
mut player_query: Query<&mut Player> mut player_query: Query<&mut Player>
) { ) {
if let Ok(player) = player_query.get_single_mut() { if let Ok(player) = player_query.get_single_mut() {
// Create a container node that places its children (text areas) in a vertical column and centers them
let container_node = NodeBundle { let container_node = NodeBundle {
style: Style { style: Style {
width: Val::Percent(100.0), // Full width of the screen width: Val::Percent(100.0),
height: Val::Percent(100.0), // Full height of the screen height: Val::Percent(100.0),
flex_direction: FlexDirection::Column, // Arrange children in a column (vertical) flex_direction: FlexDirection::Column,
justify_content: JustifyContent::Center, // Center vertically justify_content: JustifyContent::Center,
align_items: AlignItems::Center, // Center horizontally align_items: AlignItems::Center,
..default() ..default()
}, },
..default() ..default()
@ -24,35 +23,30 @@ pub fn setup(
let container = commands.spawn(container_node).id(); let container = commands.spawn(container_node).id();
// TextStyle for the top text (larger font)
let top_text_style = TextStyle { let top_text_style = TextStyle {
font_size: 50.0, // Larger font size font_size: 50.0,
color: Color::WHITE, color: Color::WHITE,
// font: asset_server.load("fonts/FiraSans-Bold.ttf"), // Load font if needed // font: asset_server.load("fonts/FiraSans-Bold.ttf"),
..default() ..default()
}; };
// TextStyle for the bottom text (smaller font)
let bottom_text_style = TextStyle { let bottom_text_style = TextStyle {
font_size: 30.0, // Smaller font size font_size: 30.0,
color: Color::WHITE, color: Color::WHITE,
// font: asset_server.load("fonts/FiraSans-Regular.ttf"), // Load font if needed // font: asset_server.load("fonts/FiraSans-Regular.ttf"),
..default() ..default()
}; };
// TextBundle for the top text
let top_text_node = TextBundle::from_section( let top_text_node = TextBundle::from_section(
"Game Over", // Text for the top section "Game Over",
top_text_style, top_text_style,
); );
// TextBundle for the bottom text
let bottom_text_node = TextBundle::from_section( let bottom_text_node = TextBundle::from_section(
format!("final score : {}", player.score), // Text for the bottom section format!("final score : {}", player.score),
bottom_text_style, bottom_text_style,
); );
// Spawn the text nodes and add them as children to the container
let top_text = commands.spawn((top_text_node, GameOver)).id(); let top_text = commands.spawn((top_text_node, GameOver)).id();
let bottom_text = commands.spawn((bottom_text_node, GameOver)).id(); let bottom_text = commands.spawn((bottom_text_node, GameOver)).id();

View file

@ -30,35 +30,31 @@ pub struct ScoreLabel;
pub struct HintLabel; pub struct HintLabel;
pub fn setup(mut commands: Commands, _asset_server: Res<AssetServer>) { pub fn setup(mut commands: Commands, _asset_server: Res<AssetServer>) {
// Create a container node that places its children (buttons) at the bottom of the screen
let container_node = NodeBundle { let container_node = NodeBundle {
style: Style { style: Style {
width: Val::Percent(100.0), // Full width of the screen width: Val::Percent(100.0),
height: Val::Percent(100.0), // Full height of the screen height: Val::Percent(100.0),
flex_direction: FlexDirection::Row, // Arrange children in a row (horizontal) flex_direction: FlexDirection::Row,
justify_content: JustifyContent::Center, // Center horizontally justify_content: JustifyContent::Center,
align_items: AlignItems::FlexEnd, // Place at the bottom of the screen align_items: AlignItems::FlexEnd,
padding: UiRect::all(Val::Px(10.0)), // Optional padding padding: UiRect::all(Val::Px(10.0)),
..default() ..default()
}, },
..default() ..default()
}; };
// Button style (same for all buttons)
let button_style = Style { let button_style = Style {
width: Val::Px(150.0), width: Val::Px(150.0),
height: Val::Px(65.0), height: Val::Px(65.0),
margin: UiRect::all(Val::Px(10.0)), // Add margin between buttons margin: UiRect::all(Val::Px(10.0)),
justify_content: JustifyContent::Center, // Center text horizontally justify_content: JustifyContent::Center,
align_items: AlignItems::Center, // Center text vertically align_items: AlignItems::Center,
border: UiRect::all(Val::Px(5.0)), border: UiRect::all(Val::Px(5.0)),
..default() ..default()
}; };
// Create the container for the buttons
let container = commands.spawn(container_node).id(); let container = commands.spawn(container_node).id();
// Function to create buttons with different text
for _i in 1..=4 { for _i in 1..=4 {
let button_node = ButtonBundle { let button_node = ButtonBundle {
style: button_style.clone(), style: button_style.clone(),
@ -77,7 +73,6 @@ pub fn setup(mut commands: Commands, _asset_server: Res<AssetServer>) {
}, },
); );
// Spawn the button and its text as children of the container
let button = commands.spawn((button_node, MainGame)).id(); let button = commands.spawn((button_node, MainGame)).id();
let button_text = commands.spawn((button_text_node, AnswerButton, MainGame)).id(); let button_text = commands.spawn((button_text_node, AnswerButton, MainGame)).id();
@ -85,12 +80,11 @@ pub fn setup(mut commands: Commands, _asset_server: Res<AssetServer>) {
commands.entity(container).push_children(&[button]); commands.entity(container).push_children(&[button]);
} }
// Label style for top corners
let label_style = Style { let label_style = Style {
position_type: PositionType::Absolute, // Absolute positioning position_type: PositionType::Absolute,
width: Val::Auto, // Auto width to fit text width: Val::Auto,
height: Val::Auto, // Auto height to fit text height: Val::Auto,
margin: UiRect::all(Val::Px(10.0)), // Margin around the text margin: UiRect::all(Val::Px(10.0)),
..default() ..default()
}; };
@ -103,7 +97,7 @@ pub fn setup(mut commands: Commands, _asset_server: Res<AssetServer>) {
..label_style.clone() ..label_style.clone()
}, },
text: Text::from_section( text: Text::from_section(
"* * *", // Text content "* * *",
TextStyle { TextStyle {
// font: asset_server.load("fonts/FiraSans-Bold.ttf"), // font: asset_server.load("fonts/FiraSans-Bold.ttf"),
font_size: 30.0, font_size: 30.0,
@ -123,7 +117,7 @@ pub fn setup(mut commands: Commands, _asset_server: Res<AssetServer>) {
..label_style.clone() ..label_style.clone()
}, },
text: Text::from_section( text: Text::from_section(
"0", // Text content "0",
TextStyle { TextStyle {
// font: asset_server.load("fonts/FiraSans-Bold.ttf"), // font: asset_server.load("fonts/FiraSans-Bold.ttf"),
font_size: 30.0, font_size: 30.0,
@ -134,14 +128,13 @@ pub fn setup(mut commands: Commands, _asset_server: Res<AssetServer>) {
..default() ..default()
}; };
// Centered container for the "Hint" label
let centered_container_node = NodeBundle { let centered_container_node = NodeBundle {
style: Style { style: Style {
position_type: PositionType::Absolute, position_type: PositionType::Absolute,
width: Val::Percent(100.0), // Full width width: Val::Percent(100.0),
top: Val::Px(20.0), // Positioned at the top top: Val::Px(20.0),
justify_content: JustifyContent::Center, // Center horizontally justify_content: JustifyContent::Center,
align_items: AlignItems::Center, // Center vertically align_items: AlignItems::Center,
..default() ..default()
}, },
..default() ..default()
@ -158,11 +151,9 @@ pub fn setup(mut commands: Commands, _asset_server: Res<AssetServer>) {
}, },
); );
// Spawn the top left and top right labels
commands.spawn((top_left_label_node, MainGame, HealthLabel)); commands.spawn((top_left_label_node, MainGame, HealthLabel));
commands.spawn((top_right_label_node, MainGame, ScoreLabel)); commands.spawn((top_right_label_node, MainGame, ScoreLabel));
// Create a parent container and then spawn the hint label inside it
let centered_container = commands.spawn(centered_container_node).id(); let centered_container = commands.spawn(centered_container_node).id();
let hint_label = commands.spawn((hint_label_node, MainGame, HintLabel)).id(); let hint_label = commands.spawn((hint_label_node, MainGame, HintLabel)).id();
@ -173,10 +164,10 @@ pub fn setup(mut commands: Commands, _asset_server: Res<AssetServer>) {
pub fn player_interact( pub fn player_interact(
keys: Res<ButtonInput<KeyCode>>, keys: Res<ButtonInput<KeyCode>>,
mut player_query: Query<(&mut Player, &mut Transform)>, // Query to get Player and Transform mut player_query: Query<(&mut Player, &mut Transform)>,
sky: Res<Sky>, // Res to access the Sky resource sky: Res<Sky>,
text_query: Query<&mut Text, With<AnswerButton>>, text_query: Query<&mut Text, With<AnswerButton>>,
button_query: Query<(&mut BackgroundColor, &mut BorderColor), With<Button>>, // Query to reset button colors button_query: Query<(&mut BackgroundColor, &mut BorderColor), With<Button>>,
constellation_line_query : Query<(Entity, &ConstellationLine)>, constellation_line_query : Query<(Entity, &ConstellationLine)>,
commands: Commands, commands: Commands,
game_state: ResMut<NextState<GameState>>, game_state: ResMut<NextState<GameState>>,
@ -184,7 +175,7 @@ pub fn player_interact(
materials: ResMut<Assets<StandardMaterial>>, materials: ResMut<Assets<StandardMaterial>>,
) { ) {
if let Ok((mut player, mut transform)) = player_query.get_single_mut() { if let Ok((mut player, mut transform)) = player_query.get_single_mut() {
// If the space key was just pressed
if keys.just_pressed(KeyCode::Space) || player.target_cons_name.is_none() { if keys.just_pressed(KeyCode::Space) || player.target_cons_name.is_none() {
choose_constellation(&mut player, sky, text_query, button_query, constellation_line_query, commands, game_state); choose_constellation(&mut player, sky, text_query, button_query, constellation_line_query, commands, game_state);
return return
@ -192,14 +183,12 @@ pub fn player_interact(
let mut rotation = Quat::IDENTITY; let mut rotation = Quat::IDENTITY;
// Rotate left when the A key is pressed
if keys.pressed(KeyCode::KeyA) { if keys.pressed(KeyCode::KeyA) {
rotation *= Quat::from_rotation_y((PI / 60.0) as f32); // Rotate by 3 degrees (PI/60 radians) rotation *= Quat::from_rotation_y((PI / 60.0) as f32);
} }
// Rotate right when the D key is pressed
if keys.pressed(KeyCode::KeyD) { if keys.pressed(KeyCode::KeyD) {
rotation *= Quat::from_rotation_y((-PI / 60.0) as f32); // Rotate by -3 degrees rotation *= Quat::from_rotation_y((-PI / 60.0) as f32);
} }
if keys.pressed(KeyCode::KeyI) && player.state == PlayerState::Playing { if keys.pressed(KeyCode::KeyI) && player.state == PlayerState::Playing {
@ -209,9 +198,8 @@ pub fn player_interact(
} }
} }
// Apply the rotation to the transform
if rotation != Quat::IDENTITY { if rotation != Quat::IDENTITY {
transform.rotation *= rotation; // Apply the rotation transform.rotation *= rotation;
player.target_rotation = None; player.target_rotation = None;
} }
@ -238,12 +226,10 @@ pub fn ui_labels(
mut player_query: Query<(&mut Player, &mut Transform)>, mut player_query: Query<(&mut Player, &mut Transform)>,
) { ) {
if let Ok((player, _)) = player_query.get_single_mut() { if let Ok((player, _)) = player_query.get_single_mut() {
// Update the health label
if let Ok(mut health_text) = param_set.p0().get_single_mut() { if let Ok(mut health_text) = param_set.p0().get_single_mut() {
health_text.sections[0].value = "# ".repeat(player.health); health_text.sections[0].value = "# ".repeat(player.health);
} }
// Update the score label
if let Ok(mut score_text) = param_set.p1().get_single_mut() { if let Ok(mut score_text) = param_set.p1().get_single_mut() {
score_text.sections[0].value = format!("{}", player.score); score_text.sections[0].value = format!("{}", player.score);
} }
@ -343,15 +329,14 @@ pub fn ui_buttons(
fn choose_constellation( fn choose_constellation(
player: &mut Player, player: &mut Player,
sky: Res<Sky>, // Res to access the Sky resource sky: Res<Sky>,
mut text_query: Query<&mut Text, With<AnswerButton>>, mut text_query: Query<&mut Text, With<AnswerButton>>,
mut button_query: Query<(&mut BackgroundColor, &mut BorderColor), With<Button>>, // Query to reset button colors mut button_query: Query<(&mut BackgroundColor, &mut BorderColor), With<Button>>,
constellation_line_query : Query<(Entity, &ConstellationLine)>, constellation_line_query : Query<(Entity, &ConstellationLine)>,
mut commands: Commands, mut commands: Commands,
mut game_state: ResMut<NextState<GameState>> mut game_state: ResMut<NextState<GameState>>
) { ) {
if player.health == 0 { if player.health == 0 {
info!("dead");
game_state.set(GameState::End); game_state.set(GameState::End);
} }
if sky.content.len() >= 4 { if sky.content.len() >= 4 {

View file

@ -2,8 +2,6 @@ use bevy::prelude::*;
use bevy::math::*; use bevy::math::*;
use bevy::render::render_resource::PrimitiveTopology; use bevy::render::render_resource::PrimitiveTopology;
use bevy::render::render_asset::RenderAssetUsages; use bevy::render::render_asset::RenderAssetUsages;
use std::fs::File;
use std::io::Read;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::f64::consts::PI; use std::f64::consts::PI;
@ -138,9 +136,8 @@ fn spawn_cons_lines(
sky: Res<Sky>, sky: Res<Sky>,
target_constellation_name: String, target_constellation_name: String,
) { ) {
// Create a material for the line
let line_material = materials.add(StandardMaterial { let line_material = materials.add(StandardMaterial {
emissive: LinearRgba::rgb(0.5, 0.5, 1.0), // Red color for the line emissive: LinearRgba::rgb(0.5, 0.5, 1.0),
..default() ..default()
}); });
@ -160,7 +157,6 @@ fn spawn_cons_lines(
} }
} }
// Create the mesh and add the vertices
let mut mesh = Mesh::new(PrimitiveTopology::LineList, RenderAssetUsages::RENDER_WORLD); let mut mesh = Mesh::new(PrimitiveTopology::LineList, RenderAssetUsages::RENDER_WORLD);
mesh.insert_attribute(Mesh::ATTRIBUTE_POSITION, vertices); mesh.insert_attribute(Mesh::ATTRIBUTE_POSITION, vertices);
@ -168,7 +164,7 @@ fn spawn_cons_lines(
PbrBundle { PbrBundle {
mesh: meshes.add(mesh), mesh: meshes.add(mesh),
material: line_material.clone(), material: line_material.clone(),
transform: Transform::default(), // Position and scale for the line transform: Transform::default(),
..default() ..default()
}, },
ConstellationLine, ConstellationLine,
@ -181,14 +177,12 @@ fn star_setup(
mut meshes: ResMut<Assets<Mesh>>, mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>, mut materials: ResMut<Assets<StandardMaterial>>,
) { ) {
// plane
commands.insert_resource(ClearColor(Color::BLACK)); commands.insert_resource(ClearColor(Color::BLACK));
let stars = get_stars().unwrap(); let stars = get_stars().unwrap();
//let mesh = meshes.add(Cuboid::new(star_size, star_size, star_size));
let star_mesh = meshes.add(Sphere::new(1.0).mesh().ico(3).unwrap()); let star_mesh = meshes.add(Sphere::new(1.0).mesh().ico(3).unwrap());
//let material = materials.add(Color::srgb(1.0, 1.0, 1.0));
let star_material = materials.add(StandardMaterial { let star_material = materials.add(StandardMaterial {
emissive: LinearRgba::rgb(1.0, 1.0, 1.0), emissive: LinearRgba::rgb(1.0, 1.0, 1.0),
..default() ..default()
@ -218,9 +212,7 @@ fn star_setup(
} }
fn get_stars() -> std::io::Result<Vec<StarData>> { fn get_stars() -> std::io::Result<Vec<StarData>> {
let mut file = File::open("data/stars.json")?; let data = include_str!("../data/stars.json");
let mut data = String::new();
file.read_to_string(&mut data)?;
let stars: Vec<StarData> = serde_json::from_str(&data).unwrap(); let stars: Vec<StarData> = serde_json::from_str(&data).unwrap();
@ -266,9 +258,7 @@ fn cons_setup(mut sky: ResMut<Sky>) {
} }
fn get_cons() -> std::io::Result<Vec<Constellation>> { fn get_cons() -> std::io::Result<Vec<Constellation>> {
let mut file = File::open("data/constellations.json")?; let data = include_str!("../data/constellations.json");
let mut data = String::new();
file.read_to_string(&mut data)?;
let sky_data: Vec<Constellation> = serde_json::from_str(&data).unwrap(); let sky_data: Vec<Constellation> = serde_json::from_str(&data).unwrap();

View file

@ -15,51 +15,44 @@ pub fn audio_setup(asset_server: Res<AssetServer>, mut commands: Commands) {
} }
pub fn setup(mut commands: Commands, _asset_server: Res<AssetServer>) { pub fn setup(mut commands: Commands, _asset_server: Res<AssetServer>) {
// Create a container node that places its children (text areas) in a vertical column and centers them
let container_node = NodeBundle { let container_node = NodeBundle {
style: Style { style: Style {
width: Val::Percent(100.0), // Full width of the screen width: Val::Percent(100.0),
height: Val::Percent(100.0), // Full height of the screen height: Val::Percent(100.0),
flex_direction: FlexDirection::Column, // Arrange children in a column (vertical) flex_direction: FlexDirection::Column,
justify_content: JustifyContent::Center, // Center vertically justify_content: JustifyContent::Center,
align_items: AlignItems::Center, // Center horizontally align_items: AlignItems::Center,
..default() ..default()
}, },
..default() ..default()
}; };
// Create the container for the text areas
let container = commands.spawn(container_node).id(); let container = commands.spawn(container_node).id();
// TextStyle for the top text (larger font)
let top_text_style = TextStyle { let top_text_style = TextStyle {
font_size: 50.0, // Larger font size font_size: 50.0,
color: Color::WHITE, color: Color::WHITE,
// font: asset_server.load("fonts/FiraSans-Bold.ttf"), // Load font if needed // font: asset_server.load("fonts/FiraSans-Bold.ttf"), // Load font if needed
..default() ..default()
}; };
// TextStyle for the bottom text (smaller font)
let bottom_text_style = TextStyle { let bottom_text_style = TextStyle {
font_size: 30.0, // Smaller font size font_size: 30.0,
color: Color::WHITE, color: Color::WHITE,
// font: asset_server.load("fonts/FiraSans-Regular.ttf"), // Load font if needed // font: asset_server.load("fonts/FiraSans-Regular.ttf"), // Load font if needed
..default() ..default()
}; };
// TextBundle for the top text
let top_text_node = TextBundle::from_section( let top_text_node = TextBundle::from_section(
"Astraea", // Text for the top section "Astraea",
top_text_style, top_text_style,
); );
// TextBundle for the bottom text
let bottom_text_node = TextBundle::from_section( let bottom_text_node = TextBundle::from_section(
"Press Space to Begin", // Text for the bottom section "Press Space to Begin",
bottom_text_style, bottom_text_style,
); );
// Spawn the text nodes and add them as children to the container
let top_text = commands.spawn((top_text_node, StartMenu)).id(); let top_text = commands.spawn((top_text_node, StartMenu)).id();
let bottom_text = commands.spawn((bottom_text_node, StartMenu)).id(); let bottom_text = commands.spawn((bottom_text_node, StartMenu)).id();
@ -94,8 +87,8 @@ pub fn player_interact(
if let Ok((_player, mut transform)) = player_query.get_single_mut() { if let Ok((_player, mut transform)) = player_query.get_single_mut() {
let mut rotation = Quat::IDENTITY; let mut rotation = Quat::IDENTITY;
rotation *= Quat::from_rotation_y((PI / 6000.0) as f32); // Rotate by 3 degrees (PI/60 radians) rotation *= Quat::from_rotation_y((PI / 6000.0) as f32);
rotation *= Quat::from_rotation_x((-PI / 2000.0) as f32); // Rotate by -3 degrees rotation *= Quat::from_rotation_x((-PI / 2000.0) as f32);
transform.rotation *= rotation; // Apply the rotation transform.rotation *= rotation;
} }
} }