Compare commits

..

No commits in common. "a00a66ab1eb7308dc0c23a07edd07f79c9f75073" and "f27f783501ec0f4820f8e3e92af20f9c7e8dfbce" have entirely different histories.

9 changed files with 312 additions and 432 deletions

1
.gitignore vendored
View file

@ -1,2 +1 @@
/target /target
/out

34
Cargo.lock generated
View file

@ -216,7 +216,6 @@ dependencies = [
"rand", "rand",
"serde", "serde",
"serde_json", "serde_json",
"wasm-bindgen",
] ]
[[package]] [[package]]
@ -2197,9 +2196,9 @@ dependencies = [
[[package]] [[package]]
name = "js-sys" name = "js-sys"
version = "0.3.69" version = "0.3.70"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29c15563dc2726973df627357ce0c9ddddbea194836909d655df6a75d2cf296d" checksum = "1868808506b929d7b0cfa8f75951347aa71bb21144b7791bae35d9bccfcfe37a"
dependencies = [ dependencies = [
"wasm-bindgen", "wasm-bindgen",
] ]
@ -3624,19 +3623,20 @@ checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
[[package]] [[package]]
name = "wasm-bindgen" name = "wasm-bindgen"
version = "0.2.92" version = "0.2.93"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4be2531df63900aeb2bca0daaaddec08491ee64ceecbee5076636a3b026795a8" checksum = "a82edfc16a6c469f5f44dc7b571814045d60404b55a0ee849f9bcfa2e63dd9b5"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
"once_cell",
"wasm-bindgen-macro", "wasm-bindgen-macro",
] ]
[[package]] [[package]]
name = "wasm-bindgen-backend" name = "wasm-bindgen-backend"
version = "0.2.92" version = "0.2.93"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "614d787b966d3989fa7bb98a654e369c762374fd3213d212cfc0251257e747da" checksum = "9de396da306523044d3302746f1208fa71d7532227f15e347e2d93e4145dd77b"
dependencies = [ dependencies = [
"bumpalo", "bumpalo",
"log", "log",
@ -3649,9 +3649,9 @@ dependencies = [
[[package]] [[package]]
name = "wasm-bindgen-futures" name = "wasm-bindgen-futures"
version = "0.4.42" version = "0.4.43"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "76bc14366121efc8dbb487ab05bcc9d346b3b5ec0eaa76e46594cabbe51762c0" checksum = "61e9300f63a621e96ed275155c108eb6f843b6a26d053f122ab69724559dc8ed"
dependencies = [ dependencies = [
"cfg-if", "cfg-if",
"js-sys", "js-sys",
@ -3661,9 +3661,9 @@ dependencies = [
[[package]] [[package]]
name = "wasm-bindgen-macro" name = "wasm-bindgen-macro"
version = "0.2.92" version = "0.2.93"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a1f8823de937b71b9460c0c34e25f3da88250760bec0ebac694b49997550d726" checksum = "585c4c91a46b072c92e908d99cb1dcdf95c5218eeb6f3bf1efa991ee7a68cccf"
dependencies = [ dependencies = [
"quote", "quote",
"wasm-bindgen-macro-support", "wasm-bindgen-macro-support",
@ -3671,9 +3671,9 @@ dependencies = [
[[package]] [[package]]
name = "wasm-bindgen-macro-support" name = "wasm-bindgen-macro-support"
version = "0.2.92" version = "0.2.93"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e94f17b526d0a461a191c78ea52bbce64071ed5c04c9ffe424dcb38f74171bb7" checksum = "afc340c74d9005395cf9dd098506f7f44e38f2b4a21c6aaacf9a105ea5e1e836"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
@ -3684,15 +3684,15 @@ dependencies = [
[[package]] [[package]]
name = "wasm-bindgen-shared" name = "wasm-bindgen-shared"
version = "0.2.92" version = "0.2.93"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af190c94f2773fdb3729c55b007a722abb5384da03bc0986df4c289bf5567e96" checksum = "c62a0a307cb4a311d3a07867860911ca130c3494e8c2719593806c08bc5d0484"
[[package]] [[package]]
name = "web-sys" name = "web-sys"
version = "0.3.69" version = "0.3.70"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77afa9a11836342370f4817622a2f0f418b134426d91a82dfb48f532d2ec13ef" checksum = "26fdeaafd9bd129f65e7c031593c24d62186301e0c72c8978fa1678be7d532c0"
dependencies = [ dependencies = [
"js-sys", "js-sys",
"wasm-bindgen", "wasm-bindgen",

View file

@ -8,7 +8,6 @@ bevy = { version = "0.14.2", features = [ "dynamic_linking" ] }
rand = "0.8.5" rand = "0.8.5"
serde = {version = "1.0.210", features = ["derive"] } serde = {version = "1.0.210", features = ["derive"] }
serde_json = "1.0.128" serde_json = "1.0.128"
wasm-bindgen = "=0.2.92"
# Enable a small amount of optimization in the dev profile. # Enable a small amount of optimization in the dev profile.
[profile.dev] [profile.dev]
@ -17,6 +16,3 @@ opt-level = 1
# Enable a large amount of optimization in the dev profile for dependencies. # Enable a large amount of optimization in the dev profile for dependencies.
[profile.dev.package."*"] [profile.dev.package."*"]
opt-level = 3 opt-level = 3
[target.wasm32-unknown-unknown]
runner = "wasm-server-runner"

View file

@ -2,6 +2,3 @@
A Stellarium game made for The icam Game jam 2024, using the Bevy game engine A Stellarium game made for The icam Game jam 2024, using the Bevy game engine
Star data from : [YaleBrightStarCatalog (Bretton Wade)](https://github.com/brettonw/YaleBrightStarCatalog/blob/master/bsc5-short.json) (MIT License, Copyright (c) 2016 Bretton Wade)
Constellation data from :[Lizard Tail (Isana Kashiwai)](https://www.lizard-tail.com/isana/lab/starlitnight/)

View file

@ -1,21 +1,22 @@
use bevy::prelude::*; use bevy::prelude::*;
use crate::Player;
use crate::GameState; use crate::GameState;
use crate::GameOver; use crate::GameOver;
use crate::GameData;
pub fn setup( pub fn setup(
mut commands: Commands, mut commands: Commands,
_asset_server: Res<AssetServer>, _asset_server: Res<AssetServer>,
game_data: Res<GameData>, mut player_query: Query<&mut Player>
) { ) {
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), width: Val::Percent(100.0), // Full width of the screen
height: Val::Percent(100.0), height: Val::Percent(100.0), // Full height of the screen
flex_direction: FlexDirection::Column, flex_direction: FlexDirection::Column, // Arrange children in a column (vertical)
justify_content: JustifyContent::Center, justify_content: JustifyContent::Center, // Center vertically
align_items: AlignItems::Center, align_items: AlignItems::Center, // Center horizontally
..default() ..default()
}, },
..default() ..default()
@ -23,34 +24,40 @@ 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, font_size: 50.0, // Larger font size
color: Color::WHITE, color: Color::WHITE,
// font: asset_server.load("fonts/FiraSans-Bold.ttf"), // 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, font_size: 30.0, // Smaller font size
color: Color::WHITE, color: Color::WHITE,
// font: asset_server.load("fonts/FiraSans-Regular.ttf"), // 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(
"Game Over", "Game Over", // Text for the top section
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 : {}", game_data.score), format!("final score : {}", player.score), // Text for the bottom section
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();
commands.entity(container).push_children(&[top_text, bottom_text]); commands.entity(container).push_children(&[top_text, bottom_text]);
}
} }
pub fn player_interact( pub fn player_interact(

View file

@ -1,70 +0,0 @@
use bevy::prelude::*;
use crate::Player;
pub fn player_mouse_move (
buttons: Res<ButtonInput<MouseButton>>,
mut player_query: Query<(&mut Player, &Camera, &mut GlobalTransform)>,
window_query: Query<&Window, With<bevy::window::PrimaryWindow>>,
) {
let Ok((mut player, camera, global_transform)) = player_query.get_single_mut() else {
return;
};
let local_transform = &global_transform.compute_transform();
if !buttons.pressed(MouseButton::Left) {
player.dragging_pos = None;
return;
}
let window = window_query.single();
let Some(new_cursor) = window.cursor_position() else {
return;
};
let Some(old_cursor) = player.dragging_pos else {
player.dragging_pos = Some(new_cursor);
return;
};
if old_cursor.distance(new_cursor) < 3.0 {
return;
}
let Some(old_ray) = camera.viewport_to_world(&global_transform, old_cursor) else {
return;
};
let Some(new_ray) = camera.viewport_to_world(&global_transform, new_cursor) else {
return;
};
let delta_rotation = rotate_to_align(new_ray, old_ray);
player.target_rotation = Some(delta_rotation * local_transform.rotation );
player.dragging_pos = Some(new_cursor);
}
fn rotate_to_align(ray_1: Ray3d, ray_2: Ray3d) -> Quat {
let pos_1 = ray_1.get_point(1.0);
let pos_2 = ray_2.get_point(1.0);
let dir_1 = pos_1.normalize();
let dir_2 = pos_2.normalize();
let axis_of_rotation = dir_1.cross(dir_2).normalize();
if axis_of_rotation.length_squared() < f32::EPSILON {
return Quat::IDENTITY;
}
let dot_product = dir_1.dot(dir_2).clamp(-1.0, 1.0);
let angle_of_rotation = dot_product.acos() * 6.0;
if angle_of_rotation.is_nan() || angle_of_rotation.is_infinite() {
return Quat::IDENTITY;
}
Quat::from_axis_angle(axis_of_rotation, angle_of_rotation)
}

View file

@ -7,10 +7,8 @@ use crate::Player;
use crate::GameState; use crate::GameState;
use crate::MainGame; use crate::MainGame;
use crate::Sky; use crate::Sky;
use crate::Constellation;
use crate::ConstellationLine; use crate::ConstellationLine;
use crate::PlayerState; use crate::PlayerState;
use crate::GameData;
use crate::celestial_to_cartesian; use crate::celestial_to_cartesian;
use crate::spawn_cons_lines; use crate::spawn_cons_lines;
@ -31,36 +29,36 @@ pub struct ScoreLabel;
#[derive(Component)] #[derive(Component)]
pub struct HintLabel; pub struct HintLabel;
pub fn setup( pub fn setup(mut commands: Commands, _asset_server: Res<AssetServer>) {
mut commands: Commands, // Create a container node that places its children (buttons) at the bottom of the screen
mut game_data: ResMut<GameData>,
sky: Res<Sky>,
) {
let container_node = NodeBundle { let container_node = NodeBundle {
style: Style { style: Style {
width: Val::Percent(100.0), width: Val::Percent(100.0), // Full width of the screen
height: Val::Percent(100.0), height: Val::Percent(100.0), // Full height of the screen
flex_direction: FlexDirection::Row, flex_direction: FlexDirection::Row, // Arrange children in a row (horizontal)
justify_content: JustifyContent::Center, justify_content: JustifyContent::Center, // Center horizontally
align_items: AlignItems::FlexEnd, align_items: AlignItems::FlexEnd, // Place at the bottom of the screen
padding: UiRect::all(Val::Px(10.0)), padding: UiRect::all(Val::Px(10.0)), // Optional padding
..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)), margin: UiRect::all(Val::Px(10.0)), // Add margin between buttons
justify_content: JustifyContent::Center, justify_content: JustifyContent::Center, // Center text horizontally
align_items: AlignItems::Center, align_items: AlignItems::Center, // Center text vertically
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(),
@ -79,6 +77,7 @@ pub fn setup(
}, },
); );
// 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();
@ -86,11 +85,12 @@ pub fn setup(
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, position_type: PositionType::Absolute, // Absolute positioning
width: Val::Auto, width: Val::Auto, // Auto width to fit text
height: Val::Auto, height: Val::Auto, // Auto height to fit text
margin: UiRect::all(Val::Px(10.0)), margin: UiRect::all(Val::Px(10.0)), // Margin around the text
..default() ..default()
}; };
@ -103,7 +103,7 @@ pub fn setup(
..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 +123,7 @@ pub fn setup(
..label_style.clone() ..label_style.clone()
}, },
text: Text::from_section( text: Text::from_section(
"0", "0", // 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,
@ -134,13 +134,14 @@ pub fn setup(
..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), width: Val::Percent(100.0), // Full width
top: Val::Px(20.0), top: Val::Px(20.0), // Positioned at the top
justify_content: JustifyContent::Center, justify_content: JustifyContent::Center, // Center horizontally
align_items: AlignItems::Center, align_items: AlignItems::Center, // Center vertically
..default() ..default()
}, },
..default() ..default()
@ -157,89 +158,63 @@ pub fn setup(
}, },
); );
// 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();
commands.entity(centered_container).push_children(&[hint_label]); commands.entity(centered_container).push_children(&[hint_label]);
*game_data = GameData::default();
game_data.content = sky.as_string();
} }
pub fn player_interact( pub fn player_interact(
keys: Res<ButtonInput<KeyCode>>, keys: Res<ButtonInput<KeyCode>>,
mut player_query: Query<(&mut Player, &mut Transform)>, mut player_query: Query<(&mut Player, &mut Transform)>, // Query to get Player and Transform
mut game_data: ResMut<GameData>, 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>>, button_query: Query<(&mut BackgroundColor, &mut BorderColor), With<Button>>, // Query to reset button colors
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>>,
meshes: ResMut<Assets<Mesh>>, meshes: ResMut<Assets<Mesh>>,
materials: ResMut<Assets<StandardMaterial>>, materials: ResMut<Assets<StandardMaterial>>,
) { ) {
let Ok((mut player, mut transform)) = player_query.get_single_mut() else { if let Ok((mut player, mut transform)) = player_query.get_single_mut() {
return // If the space key was just pressed
}; 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);
if keys.just_pressed(KeyCode::Space) || game_data.target_cons_name.is_none() {
choose_constellation(&mut player, sky, text_query, button_query, constellation_line_query, commands, game_state, game_data);
return return
} }
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); rotation *= Quat::from_rotation_y((PI / 60.0) as f32); // Rotate by 3 degrees (PI/60 radians)
} }
// 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); rotation *= Quat::from_rotation_y((-PI / 60.0) as f32); // Rotate by -3 degrees
} }
if keys.pressed(KeyCode::KeyI) && game_data.state == PlayerState::Playing { if keys.pressed(KeyCode::KeyI) && player.state == PlayerState::Playing {
if let Some(target_cons) = game_data.target_cons_name.clone() { if let Some(target_cons) = player.target_cons_name.clone() {
game_data.state = PlayerState::Hinted; player.state = PlayerState::Hinted;
spawn_cons_lines(commands, meshes, materials, sky, target_cons); spawn_cons_lines(commands, meshes, materials, sky, target_cons);
return
} }
} }
// Apply the rotation to the transform
if rotation != Quat::IDENTITY { if rotation != Quat::IDENTITY {
transform.rotation *= rotation; transform.rotation *= rotation; // Apply the rotation
player.target_rotation = None; player.target_rotation = None;
} }
if keys.pressed(KeyCode::KeyR) {
if let Some(target_constellation_name) = game_data.target_cons_name.clone() {
let mut target_constellation = sky.content[0].clone();
for constellation in sky.content.clone() {
if constellation.name == target_constellation_name {
target_constellation = constellation
}
}
player.target_rotation = Some(constellation_center(target_constellation));
}
}
if keys.pressed(KeyCode::KeyW) {
let target_constellation_name: String = "Ursa Minor".into();
let mut target_constellation = sky.content[0].clone();
for constellation in sky.content.clone() {
if constellation.name == target_constellation_name {
target_constellation = constellation
}
}
player.target_rotation = Some(constellation_center(target_constellation));
}
if let Some(target_rotation) = player.target_rotation { if let Some(target_rotation) = player.target_rotation {
let current_rotation = transform.rotation; let current_rotation = transform.rotation;
@ -249,31 +224,38 @@ pub fn player_interact(
player.target_rotation = None; player.target_rotation = None;
} }
} }
}
} }
pub fn ui_labels( pub fn ui_labels(
mut param_set: ParamSet<( mut param_set: ParamSet<(
Query<&mut Text, With<HealthLabel>>, Query<&mut Text, With<HealthLabel>>,
Query<&mut Text, With<ScoreLabel>>, Query<&mut Text, With<ScoreLabel>>,
Query<&mut Text, With<HintLabel>>, Query<&mut Text, With<HintLabel>>,
)>, )>,
game_data: Res<GameData> mut player_query: Query<(&mut Player, &mut Transform)>,
) { ) {
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(game_data.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!("{}", game_data.score); score_text.sections[0].value = format!("{}", player.score);
} }
if let Ok(mut hint_text) = param_set.p2().get_single_mut() { if let Ok(mut hint_text) = param_set.p2().get_single_mut() {
if game_data.state == PlayerState::Answered { if player.state == PlayerState::Answered {
hint_text.sections[0].value = "press space to continue".into(); hint_text.sections[0].value = "press space to continue".into();
} else { } else {
hint_text.sections[0].value = "press i to get an hint".into(); hint_text.sections[0].value = "press i to get an hint".into();
} }
} }
}
} }
@ -288,14 +270,15 @@ pub fn ui_buttons(
With<Button>, With<Button>,
>, >,
mut text_query: Query<&mut Text, With<AnswerButton>>, mut text_query: Query<&mut Text, With<AnswerButton>>,
mut game_data: ResMut<GameData>, mut player_query: Query<&mut Player>,
commands: Commands, commands: Commands,
meshes: ResMut<Assets<Mesh>>, meshes: ResMut<Assets<Mesh>>,
materials: ResMut<Assets<StandardMaterial>>, materials: ResMut<Assets<StandardMaterial>>,
sky: Res<Sky> sky: Res<Sky>
) { ) {
if game_data.state == PlayerState::Answered { if let Ok(mut player) = player_query.get_single_mut() {
return; if player.state == PlayerState::Answered {
return
} }
let mut pressed_button: Option<String> = None; let mut pressed_button: Option<String> = None;
@ -313,31 +296,23 @@ pub fn ui_buttons(
} }
} }
let Some(selected_cons) = pressed_button else { if let Some(selected_cons) = pressed_button {
return; if let Some(target_cons) = player.target_cons_name.clone() {
}; if player.state == PlayerState::Playing {
let Some(target_cons) = game_data.target_cons_name.clone() else {
return;
};
if game_data.state == PlayerState::Playing {
spawn_cons_lines(commands, meshes, materials, sky, target_cons.clone()); spawn_cons_lines(commands, meshes, materials, sky, target_cons.clone());
} }
if target_cons == selected_cons { if target_cons == selected_cons {
if game_data.state == PlayerState::Hinted { if player.state == PlayerState::Hinted {
game_data.score += 20; player.score += 20;
} else { } else {
game_data.score += 100; player.score += 100;
} }
} else { } else {
game_data.health -= 1; player.health -= 1;
} }
game_data.content.retain(|x| x != &target_cons); player.state = PlayerState::Answered;
game_data.state = PlayerState::Answered;
for ( for (
_interaction, _interaction,
@ -361,41 +336,49 @@ pub fn ui_buttons(
}; };
} }
} }
}
}
}
} }
fn choose_constellation( fn choose_constellation(
player: &mut Player, player: &mut Player,
sky: Res<Sky>, sky: Res<Sky>, // Res to access the Sky resource
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>>, mut button_query: Query<(&mut BackgroundColor, &mut BorderColor), With<Button>>, // Query to reset button colors
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>>
mut game_data: ResMut<GameData>,
) { ) {
if game_data.health == 0 { if player.health == 0 {
info!("dead");
game_state.set(GameState::End); game_state.set(GameState::End);
} }
if sky.content.len() >= 4 {
if game_data.content.len() < 4 {
game_state.set(GameState::End);
}
let mut rng = rand::thread_rng(); let mut rng = rand::thread_rng();
let mut cons_names = game_data.content.clone(); let mut selected_constellations = sky.content.clone();
cons_names.shuffle(&mut rng); selected_constellations.shuffle(&mut rng);
let selected_cons_names = &cons_names[0..4]; let constellations = &selected_constellations[0..4];
let target_index = rng.next_u32().rem_euclid(4) as usize; let target_index = rng.next_u32().rem_euclid(4) as usize;
let target_constellation = sky.get_constellation(&selected_cons_names[target_index]); let target_constellation = &constellations[target_index];
player.target_rotation = Some(constellation_center(target_constellation.clone())); let mut mean_pos = Vec3::ZERO;
game_data.target_cons_name = Some(target_constellation.name.clone()); for star in target_constellation.stars.clone() {
mean_pos += celestial_to_cartesian(star.rah, star.dec)
}
let target_rotation = Quat::from_rotation_arc(
Vec3::Z,
-mean_pos*(1.0/target_constellation.stars.len() as f32),
);
player.target_rotation = Some(target_rotation);
player.target_cons_name = Some(target_constellation.name.clone());
info!("Target constellation: {}", target_constellation.name); info!("Target constellation: {}", target_constellation.name);
for (i, mut text) in text_query.iter_mut().enumerate() { for (i, mut text) in text_query.iter_mut().enumerate() {
text.sections[0].value = selected_cons_names[i].clone(); text.sections[0].value = constellations[i].name.clone();
} }
for (mut bg_color, mut border_color) in &mut button_query { for (mut bg_color, mut border_color) in &mut button_query {
@ -407,20 +390,8 @@ fn choose_constellation(
commands.entity(entity).despawn(); commands.entity(entity).despawn();
} }
game_data.state = PlayerState::Playing; player.state = PlayerState::Playing;
} } else {
info!("Not enough constellations in the sky (need 4)");
fn constellation_center(target_constellation: Constellation) -> Quat {
let mut mean_pos = Vec3::ZERO;
for star in target_constellation.stars.clone() {
mean_pos += celestial_to_cartesian(star.rah, star.dec)
} }
Quat::from_rotation_arc(
Vec3::Z,
-mean_pos*(1.0/target_constellation.stars.len() as f32),
)
} }

View file

@ -2,13 +2,14 @@ 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;
mod end_state; mod end_state;
mod start_state; mod start_state;
mod game_state; mod game_state;
mod explo_state;
const NORMAL_BUTTON: Color = Color::srgb(0.15, 0.15, 0.15); const NORMAL_BUTTON: Color = Color::srgb(0.15, 0.15, 0.15);
const WRONG_BUTTON: Color = Color::srgb(0.50, 0.15, 0.15); const WRONG_BUTTON: Color = Color::srgb(0.50, 0.15, 0.15);
@ -41,30 +42,11 @@ struct StarData {
name: Option<String>, name: Option<String>,
} }
#[derive(Resource, Default, Clone)] #[derive(Resource, Default)]
struct Sky { struct Sky {
content: Vec<Constellation>, content: Vec<Constellation>,
} }
impl Sky {
fn as_string(&self) -> Vec<String> {
let mut cons_names : Vec<String> = vec![];
for cons in self.content.clone() {
cons_names.push(cons.name.clone());
}
return cons_names;
}
fn get_constellation(&self, name: &str) -> Constellation {
for cons in self.content.clone() {
if &cons.name == name {
return cons;
}
}
return self.content[0].clone();
}
}
#[derive(Serialize, Deserialize, Debug, Clone)] #[derive(Serialize, Deserialize, Debug, Clone)]
struct Constellation { struct Constellation {
#[serde(rename = "Name")] #[serde(rename = "Name")]
@ -103,36 +85,17 @@ struct MainGame;
#[derive(Component)] #[derive(Component)]
struct GameOver; struct GameOver;
#[derive(Component, Default)] #[derive(Component)]
struct Player { struct Player {
target_rotation: Option<Quat>, target_rotation: Option<Quat>,
dragging_pos: Option<Vec2>, target_cons_name: Option<String>,
}
#[derive(Resource)]
struct GameData {
content: Vec<String>,
score: usize, score: usize,
health: usize, health: usize,
state: PlayerState, state: PlayerState,
target_cons_name: Option<String>,
} }
impl Default for GameData { #[derive(PartialEq)]
fn default() -> Self {
GameData {
content: vec![],
score: 0,
health: 3,
state: PlayerState::Playing,
target_cons_name: None,
}
}
}
#[derive(Default, PartialEq)]
enum PlayerState { enum PlayerState {
#[default]
Playing, Playing,
Hinted, Hinted,
Answered, Answered,
@ -150,7 +113,6 @@ fn main() {
App::new() App::new()
.add_plugins(DefaultPlugins) .add_plugins(DefaultPlugins)
.insert_resource(Sky::default()) .insert_resource(Sky::default())
.insert_resource(GameData::default())
.init_state::<GameState>() .init_state::<GameState>()
.add_systems(Startup, star_setup) .add_systems(Startup, star_setup)
.add_systems(Startup, cons_setup) .add_systems(Startup, cons_setup)
@ -160,7 +122,6 @@ fn main() {
.add_systems(OnExit(GameState::Start), despawn_screen::<StartMenu>) .add_systems(OnExit(GameState::Start), despawn_screen::<StartMenu>)
.add_systems(OnEnter(GameState::Game), game_state::setup) .add_systems(OnEnter(GameState::Game), game_state::setup)
.add_systems(Update, game_state::player_interact.run_if(in_state(GameState::Game))) .add_systems(Update, game_state::player_interact.run_if(in_state(GameState::Game)))
.add_systems(Update, explo_state::player_mouse_move.run_if(in_state(GameState::Game)))
.add_systems(Update, game_state::ui_buttons.run_if(in_state(GameState::Game))) .add_systems(Update, game_state::ui_buttons.run_if(in_state(GameState::Game)))
.add_systems(Update, game_state::ui_labels.run_if(in_state(GameState::Game))) .add_systems(Update, game_state::ui_labels.run_if(in_state(GameState::Game)))
.add_systems(OnExit(GameState::Game), despawn_screen::<MainGame>) .add_systems(OnExit(GameState::Game), despawn_screen::<MainGame>)
@ -177,8 +138,9 @@ 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), emissive: LinearRgba::rgb(0.5, 0.5, 1.0), // Red color for the line
..default() ..default()
}); });
@ -198,6 +160,7 @@ 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);
@ -205,7 +168,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(), transform: Transform::default(), // Position and scale for the line
..default() ..default()
}, },
ConstellationLine, ConstellationLine,
@ -218,12 +181,14 @@ 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()
@ -250,18 +215,12 @@ fn star_setup(
Star, Star,
)); ));
} }
commands.spawn((
Camera3dBundle {
transform: Transform::from_xyz(0.0, 0.0, 0.0),
..default()
},
Player::default(),
));
} }
fn get_stars() -> std::io::Result<Vec<StarData>> { fn get_stars() -> std::io::Result<Vec<StarData>> {
let data = include_str!("../data/stars.json"); let mut file = File::open("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();
@ -307,7 +266,9 @@ fn cons_setup(mut sky: ResMut<Sky>) {
} }
fn get_cons() -> std::io::Result<Vec<Constellation>> { fn get_cons() -> std::io::Result<Vec<Constellation>> {
let data = include_str!("../data/constellations.json"); let mut file = File::open("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

@ -1,82 +1,101 @@
use bevy::prelude::*; use bevy::prelude::*;
use std::f64::consts::PI; use std::f64::consts::PI;
//use bevy::input::mouse::MouseMotion;
use crate::GameState;
use crate::StartMenu;
use crate::Player; use crate::Player;
use crate::GameState;
#[derive(Component)] use crate::GameOver;
struct AudioPlayer; use crate::StartMenu;
use crate::PlayerState;
pub fn audio_setup(asset_server: Res<AssetServer>, mut commands: Commands) { pub fn audio_setup(asset_server: Res<AssetServer>, mut commands: Commands) {
commands.spawn((AudioBundle { commands.spawn(AudioBundle {
source: asset_server.load("Banjo.ogg"), source: asset_server.load("Banjo.ogg"),
settings: PlaybackSettings::LOOP, settings: PlaybackSettings::LOOP,
}, AudioPlayer)); });
info!("audio started"); info!("audio started");
} }
pub fn setup( pub fn setup(mut commands: Commands, _asset_server: Res<AssetServer>) {
mut commands: Commands, // 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), width: Val::Percent(100.0), // Full width of the screen
height: Val::Percent(100.0), height: Val::Percent(100.0), // Full height of the screen
flex_direction: FlexDirection::Column, flex_direction: FlexDirection::Column, // Arrange children in a column (vertical)
justify_content: JustifyContent::Center, justify_content: JustifyContent::Center, // Center vertically
align_items: AlignItems::Center, align_items: AlignItems::Center, // Center horizontally
..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, font_size: 50.0, // Larger font size
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, font_size: 30.0, // Smaller font size
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", "Astraea", // Text for the top section
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", "Press Space to Begin", // Text for the bottom section
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();
commands.entity(container).push_children(&[top_text, bottom_text]); commands.entity(container).push_children(&[top_text, bottom_text]);
commands.spawn((
Camera3dBundle {
transform: Transform::from_xyz(0.0, 0.0, 0.0),
..default()
},
Player {
target_rotation: None,
target_cons_name: None,
score: 0,
health: 3,
state: PlayerState::Playing,
},
GameOver,
));
} }
pub fn player_interact( pub fn player_interact(
keys: Res<ButtonInput<KeyCode>>, keys: Res<ButtonInput<KeyCode>>,
mut game_state: ResMut<NextState<GameState>>, mut game_state: ResMut<NextState<GameState>>,
mut player_query: Query<(&mut Player, &mut Transform)>, mut player_query: Query<(&mut Player, &mut Transform)>
) { ) {
if keys.just_pressed(KeyCode::Space) { if keys.just_pressed(KeyCode::Space) {
info!("start space"); info!("start space");
game_state.set(GameState::Game); game_state.set(GameState::Game);
} }
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); rotation *= Quat::from_rotation_y((PI / 6000.0) as f32); // Rotate by 3 degrees (PI/60 radians)
rotation *= Quat::from_rotation_x((-PI / 2000.0) as f32); rotation *= Quat::from_rotation_x((-PI / 2000.0) as f32); // Rotate by -3 degrees
transform.rotation *= rotation; transform.rotation *= rotation; // Apply the rotation
} }
} }