Compare commits

...

8 commits

Author SHA1 Message Date
WanderingPenwing a00a66ab1e do not repeat already guessed cons 2024-10-07 18:28:21 +02:00
WanderingPenwing 447dfc9f22 biiig cleanup 2024-10-07 17:57:44 +02:00
WanderingPenwing ab804fb9b5 cleaned up 2024-10-07 17:05:22 +02:00
WanderingPenwing f4440dd06e rotaatiooon 2024-10-07 16:58:44 +02:00
WanderingPenwing e267e26f1c good rotation but infinite 2024-10-07 13:30:19 +02:00
WanderingPenwing 7dde61a98d drag but bad rotation 2024-10-07 12:53:51 +02:00
WanderingPenwing cb74487f1b press R to look to current constellation 2024-10-07 11:03:05 +02:00
WanderingPenwing efdb86c081 wasm + include json 2024-10-07 09:28:32 +02:00
9 changed files with 435 additions and 315 deletions

1
.gitignore vendored
View file

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

34
Cargo.lock generated
View file

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

View file

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

View file

@ -2,3 +2,6 @@
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,22 +1,21 @@
use bevy::prelude::*;
use crate::Player;
use crate::GameState;
use crate::GameOver;
use crate::GameData;
pub fn setup(
mut commands: Commands,
_asset_server: Res<AssetServer>,
mut player_query: Query<&mut Player>
game_data: Res<GameData>,
) {
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 {
style: Style {
width: Val::Percent(100.0), // Full width of the screen
height: Val::Percent(100.0), // Full height of the screen
flex_direction: FlexDirection::Column, // Arrange children in a column (vertical)
justify_content: JustifyContent::Center, // Center vertically
align_items: AlignItems::Center, // Center horizontally
width: Val::Percent(100.0),
height: Val::Percent(100.0),
flex_direction: FlexDirection::Column,
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
..default()
},
..default()
@ -24,41 +23,35 @@ pub fn setup(
let container = commands.spawn(container_node).id();
// TextStyle for the top text (larger font)
let top_text_style = TextStyle {
font_size: 50.0, // Larger font size
font_size: 50.0,
color: Color::WHITE,
// font: asset_server.load("fonts/FiraSans-Bold.ttf"), // Load font if needed
// font: asset_server.load("fonts/FiraSans-Bold.ttf"),
..default()
};
// TextStyle for the bottom text (smaller font)
let bottom_text_style = TextStyle {
font_size: 30.0, // Smaller font size
font_size: 30.0,
color: Color::WHITE,
// font: asset_server.load("fonts/FiraSans-Regular.ttf"), // Load font if needed
// font: asset_server.load("fonts/FiraSans-Regular.ttf"),
..default()
};
// TextBundle for the top text
let top_text_node = TextBundle::from_section(
"Game Over", // Text for the top section
"Game Over",
top_text_style,
);
// TextBundle for the bottom text
let bottom_text_node = TextBundle::from_section(
format!("final score : {}", player.score), // Text for the bottom section
format!("final score : {}", game_data.score),
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 bottom_text = commands.spawn((bottom_text_node, GameOver)).id();
commands.entity(container).push_children(&[top_text, bottom_text]);
}
}
pub fn player_interact(
keys: Res<ButtonInput<KeyCode>>,

70
src/explo_state.rs Normal file
View file

@ -0,0 +1,70 @@
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,8 +7,10 @@ use crate::Player;
use crate::GameState;
use crate::MainGame;
use crate::Sky;
use crate::Constellation;
use crate::ConstellationLine;
use crate::PlayerState;
use crate::GameData;
use crate::celestial_to_cartesian;
use crate::spawn_cons_lines;
@ -29,36 +31,36 @@ pub struct ScoreLabel;
#[derive(Component)]
pub struct HintLabel;
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
pub fn setup(
mut commands: Commands,
mut game_data: ResMut<GameData>,
sky: Res<Sky>,
) {
let container_node = NodeBundle {
style: Style {
width: Val::Percent(100.0), // Full width of the screen
height: Val::Percent(100.0), // Full height of the screen
flex_direction: FlexDirection::Row, // Arrange children in a row (horizontal)
justify_content: JustifyContent::Center, // Center horizontally
align_items: AlignItems::FlexEnd, // Place at the bottom of the screen
padding: UiRect::all(Val::Px(10.0)), // Optional padding
width: Val::Percent(100.0),
height: Val::Percent(100.0),
flex_direction: FlexDirection::Row,
justify_content: JustifyContent::Center,
align_items: AlignItems::FlexEnd,
padding: UiRect::all(Val::Px(10.0)),
..default()
},
..default()
};
// Button style (same for all buttons)
let button_style = Style {
width: Val::Px(150.0),
height: Val::Px(65.0),
margin: UiRect::all(Val::Px(10.0)), // Add margin between buttons
justify_content: JustifyContent::Center, // Center text horizontally
align_items: AlignItems::Center, // Center text vertically
margin: UiRect::all(Val::Px(10.0)),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
border: UiRect::all(Val::Px(5.0)),
..default()
};
// Create the container for the buttons
let container = commands.spawn(container_node).id();
// Function to create buttons with different text
for _i in 1..=4 {
let button_node = ButtonBundle {
style: button_style.clone(),
@ -77,7 +79,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_text = commands.spawn((button_text_node, AnswerButton, MainGame)).id();
@ -85,12 +86,11 @@ pub fn setup(mut commands: Commands, _asset_server: Res<AssetServer>) {
commands.entity(container).push_children(&[button]);
}
// Label style for top corners
let label_style = Style {
position_type: PositionType::Absolute, // Absolute positioning
width: Val::Auto, // Auto width to fit text
height: Val::Auto, // Auto height to fit text
margin: UiRect::all(Val::Px(10.0)), // Margin around the text
position_type: PositionType::Absolute,
width: Val::Auto,
height: Val::Auto,
margin: UiRect::all(Val::Px(10.0)),
..default()
};
@ -103,7 +103,7 @@ pub fn setup(mut commands: Commands, _asset_server: Res<AssetServer>) {
..label_style.clone()
},
text: Text::from_section(
"* * *", // Text content
"* * *",
TextStyle {
// font: asset_server.load("fonts/FiraSans-Bold.ttf"),
font_size: 30.0,
@ -123,7 +123,7 @@ pub fn setup(mut commands: Commands, _asset_server: Res<AssetServer>) {
..label_style.clone()
},
text: Text::from_section(
"0", // Text content
"0",
TextStyle {
// font: asset_server.load("fonts/FiraSans-Bold.ttf"),
font_size: 30.0,
@ -134,14 +134,13 @@ pub fn setup(mut commands: Commands, _asset_server: Res<AssetServer>) {
..default()
};
// Centered container for the "Hint" label
let centered_container_node = NodeBundle {
style: Style {
position_type: PositionType::Absolute,
width: Val::Percent(100.0), // Full width
top: Val::Px(20.0), // Positioned at the top
justify_content: JustifyContent::Center, // Center horizontally
align_items: AlignItems::Center, // Center vertically
width: Val::Percent(100.0),
top: Val::Px(20.0),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
..default()
},
..default()
@ -158,63 +157,89 @@ 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_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 hint_label = commands.spawn((hint_label_node, MainGame, HintLabel)).id();
commands.entity(centered_container).push_children(&[hint_label]);
*game_data = GameData::default();
game_data.content = sky.as_string();
}
pub fn player_interact(
keys: Res<ButtonInput<KeyCode>>,
mut player_query: Query<(&mut Player, &mut Transform)>, // Query to get Player and Transform
sky: Res<Sky>, // Res to access the Sky resource
mut player_query: Query<(&mut Player, &mut Transform)>,
mut game_data: ResMut<GameData>,
sky: Res<Sky>,
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)>,
commands: Commands,
game_state: ResMut<NextState<GameState>>,
meshes: ResMut<Assets<Mesh>>,
materials: ResMut<Assets<StandardMaterial>>,
) {
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() {
choose_constellation(&mut player, sky, text_query, button_query, constellation_line_query, commands, game_state);
let Ok((mut player, mut transform)) = player_query.get_single_mut() else {
return
};
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
}
let mut rotation = Quat::IDENTITY;
// Rotate left when the A key is pressed
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) {
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 let Some(target_cons) = player.target_cons_name.clone() {
player.state = PlayerState::Hinted;
if keys.pressed(KeyCode::KeyI) && game_data.state == PlayerState::Playing {
if let Some(target_cons) = game_data.target_cons_name.clone() {
game_data.state = PlayerState::Hinted;
spawn_cons_lines(commands, meshes, materials, sky, target_cons);
return
}
}
// Apply the rotation to the transform
if rotation != Quat::IDENTITY {
transform.rotation *= rotation; // Apply the rotation
transform.rotation *= rotation;
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 {
let current_rotation = transform.rotation;
@ -225,9 +250,6 @@ pub fn player_interact(
}
}
}
}
pub fn ui_labels(
mut param_set: ParamSet<(
@ -235,28 +257,24 @@ pub fn ui_labels(
Query<&mut Text, With<ScoreLabel>>,
Query<&mut Text, With<HintLabel>>,
)>,
mut player_query: Query<(&mut Player, &mut Transform)>,
game_data: Res<GameData>
) {
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() {
health_text.sections[0].value = "# ".repeat(player.health);
health_text.sections[0].value = "# ".repeat(game_data.health);
}
// Update the score label
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!("{}", game_data.score);
}
if let Ok(mut hint_text) = param_set.p2().get_single_mut() {
if player.state == PlayerState::Answered {
if game_data.state == PlayerState::Answered {
hint_text.sections[0].value = "press space to continue".into();
} else {
hint_text.sections[0].value = "press i to get an hint".into();
}
}
}
}
pub fn ui_buttons(
@ -270,15 +288,14 @@ pub fn ui_buttons(
With<Button>,
>,
mut text_query: Query<&mut Text, With<AnswerButton>>,
mut player_query: Query<&mut Player>,
mut game_data: ResMut<GameData>,
commands: Commands,
meshes: ResMut<Assets<Mesh>>,
materials: ResMut<Assets<StandardMaterial>>,
sky: Res<Sky>
) {
if let Ok(mut player) = player_query.get_single_mut() {
if player.state == PlayerState::Answered {
return
if game_data.state == PlayerState::Answered {
return;
}
let mut pressed_button: Option<String> = None;
@ -296,23 +313,31 @@ pub fn ui_buttons(
}
}
if let Some(selected_cons) = pressed_button {
if let Some(target_cons) = player.target_cons_name.clone() {
if player.state == PlayerState::Playing {
let Some(selected_cons) = pressed_button else {
return;
};
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());
}
if target_cons == selected_cons {
if player.state == PlayerState::Hinted {
player.score += 20;
if game_data.state == PlayerState::Hinted {
game_data.score += 20;
} else {
player.score += 100;
game_data.score += 100;
}
} else {
player.health -= 1;
game_data.health -= 1;
}
player.state = PlayerState::Answered;
game_data.content.retain(|x| x != &target_cons);
game_data.state = PlayerState::Answered;
for (
_interaction,
@ -337,48 +362,40 @@ pub fn ui_buttons(
}
}
}
}
}
}
fn choose_constellation(
player: &mut Player,
sky: Res<Sky>, // Res to access the Sky resource
sky: Res<Sky>,
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)>,
mut commands: Commands,
mut game_state: ResMut<NextState<GameState>>
mut game_state: ResMut<NextState<GameState>>,
mut game_data: ResMut<GameData>,
) {
if player.health == 0 {
info!("dead");
if game_data.health == 0 {
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 selected_constellations = sky.content.clone();
selected_constellations.shuffle(&mut rng);
let constellations = &selected_constellations[0..4];
let mut cons_names = game_data.content.clone();
cons_names.shuffle(&mut rng);
let selected_cons_names = &cons_names[0..4];
let target_index = rng.next_u32().rem_euclid(4) as usize;
let target_constellation = &constellations[target_index];
let target_constellation = sky.get_constellation(&selected_cons_names[target_index]);
let mut mean_pos = Vec3::ZERO;
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());
player.target_rotation = Some(constellation_center(target_constellation.clone()));
game_data.target_cons_name = Some(target_constellation.name.clone());
info!("Target constellation: {}", target_constellation.name);
for (i, mut text) in text_query.iter_mut().enumerate() {
text.sections[0].value = constellations[i].name.clone();
text.sections[0].value = selected_cons_names[i].clone();
}
for (mut bg_color, mut border_color) in &mut button_query {
@ -390,8 +407,20 @@ fn choose_constellation(
commands.entity(entity).despawn();
}
player.state = PlayerState::Playing;
} else {
info!("Not enough constellations in the sky (need 4)");
game_data.state = PlayerState::Playing;
}
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,14 +2,13 @@ use bevy::prelude::*;
use bevy::math::*;
use bevy::render::render_resource::PrimitiveTopology;
use bevy::render::render_asset::RenderAssetUsages;
use std::fs::File;
use std::io::Read;
use serde::{Deserialize, Serialize};
use std::f64::consts::PI;
mod end_state;
mod start_state;
mod game_state;
mod explo_state;
const NORMAL_BUTTON: Color = Color::srgb(0.15, 0.15, 0.15);
const WRONG_BUTTON: Color = Color::srgb(0.50, 0.15, 0.15);
@ -42,11 +41,30 @@ struct StarData {
name: Option<String>,
}
#[derive(Resource, Default)]
#[derive(Resource, Default, Clone)]
struct Sky {
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)]
struct Constellation {
#[serde(rename = "Name")]
@ -85,17 +103,36 @@ struct MainGame;
#[derive(Component)]
struct GameOver;
#[derive(Component)]
#[derive(Component, Default)]
struct Player {
target_rotation: Option<Quat>,
target_cons_name: Option<String>,
dragging_pos: Option<Vec2>,
}
#[derive(Resource)]
struct GameData {
content: Vec<String>,
score: usize,
health: usize,
state: PlayerState,
target_cons_name: Option<String>,
}
#[derive(PartialEq)]
impl Default for GameData {
fn default() -> Self {
GameData {
content: vec![],
score: 0,
health: 3,
state: PlayerState::Playing,
target_cons_name: None,
}
}
}
#[derive(Default, PartialEq)]
enum PlayerState {
#[default]
Playing,
Hinted,
Answered,
@ -113,6 +150,7 @@ fn main() {
App::new()
.add_plugins(DefaultPlugins)
.insert_resource(Sky::default())
.insert_resource(GameData::default())
.init_state::<GameState>()
.add_systems(Startup, star_setup)
.add_systems(Startup, cons_setup)
@ -122,6 +160,7 @@ fn main() {
.add_systems(OnExit(GameState::Start), despawn_screen::<StartMenu>)
.add_systems(OnEnter(GameState::Game), game_state::setup)
.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_labels.run_if(in_state(GameState::Game)))
.add_systems(OnExit(GameState::Game), despawn_screen::<MainGame>)
@ -138,9 +177,8 @@ fn spawn_cons_lines(
sky: Res<Sky>,
target_constellation_name: String,
) {
// Create a material for the line
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()
});
@ -160,7 +198,6 @@ fn spawn_cons_lines(
}
}
// Create the mesh and add the vertices
let mut mesh = Mesh::new(PrimitiveTopology::LineList, RenderAssetUsages::RENDER_WORLD);
mesh.insert_attribute(Mesh::ATTRIBUTE_POSITION, vertices);
@ -168,7 +205,7 @@ fn spawn_cons_lines(
PbrBundle {
mesh: meshes.add(mesh),
material: line_material.clone(),
transform: Transform::default(), // Position and scale for the line
transform: Transform::default(),
..default()
},
ConstellationLine,
@ -181,14 +218,12 @@ fn star_setup(
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
// plane
commands.insert_resource(ClearColor(Color::BLACK));
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 material = materials.add(Color::srgb(1.0, 1.0, 1.0));
let star_material = materials.add(StandardMaterial {
emissive: LinearRgba::rgb(1.0, 1.0, 1.0),
..default()
@ -215,12 +250,18 @@ fn star_setup(
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>> {
let mut file = File::open("data/stars.json")?;
let mut data = String::new();
file.read_to_string(&mut data)?;
let data = include_str!("../data/stars.json");
let stars: Vec<StarData> = serde_json::from_str(&data).unwrap();
@ -266,9 +307,7 @@ fn cons_setup(mut sky: ResMut<Sky>) {
}
fn get_cons() -> std::io::Result<Vec<Constellation>> {
let mut file = File::open("data/constellations.json")?;
let mut data = String::new();
file.read_to_string(&mut data)?;
let data = include_str!("../data/constellations.json");
let sky_data: Vec<Constellation> = serde_json::from_str(&data).unwrap();

View file

@ -1,101 +1,82 @@
use bevy::prelude::*;
use std::f64::consts::PI;
use crate::Player;
//use bevy::input::mouse::MouseMotion;
use crate::GameState;
use crate::GameOver;
use crate::StartMenu;
use crate::PlayerState;
use crate::Player;
#[derive(Component)]
struct AudioPlayer;
pub fn audio_setup(asset_server: Res<AssetServer>, mut commands: Commands) {
commands.spawn(AudioBundle {
commands.spawn((AudioBundle {
source: asset_server.load("Banjo.ogg"),
settings: PlaybackSettings::LOOP,
});
}, AudioPlayer));
info!("audio started");
}
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
pub fn setup(
mut commands: Commands,
) {
let container_node = NodeBundle {
style: Style {
width: Val::Percent(100.0), // Full width of the screen
height: Val::Percent(100.0), // Full height of the screen
flex_direction: FlexDirection::Column, // Arrange children in a column (vertical)
justify_content: JustifyContent::Center, // Center vertically
align_items: AlignItems::Center, // Center horizontally
width: Val::Percent(100.0),
height: Val::Percent(100.0),
flex_direction: FlexDirection::Column,
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
..default()
},
..default()
};
// Create the container for the text areas
let container = commands.spawn(container_node).id();
// TextStyle for the top text (larger font)
let top_text_style = TextStyle {
font_size: 50.0, // Larger font size
font_size: 50.0,
color: Color::WHITE,
// font: asset_server.load("fonts/FiraSans-Bold.ttf"), // Load font if needed
..default()
};
// TextStyle for the bottom text (smaller font)
let bottom_text_style = TextStyle {
font_size: 30.0, // Smaller font size
font_size: 30.0,
color: Color::WHITE,
// font: asset_server.load("fonts/FiraSans-Regular.ttf"), // Load font if needed
..default()
};
// TextBundle for the top text
let top_text_node = TextBundle::from_section(
"Astraea", // Text for the top section
"Astraea",
top_text_style,
);
// TextBundle for the bottom text
let bottom_text_node = TextBundle::from_section(
"Press Space to Begin", // Text for the bottom section
"Press Space to Begin",
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 bottom_text = commands.spawn((bottom_text_node, StartMenu)).id();
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(
keys: Res<ButtonInput<KeyCode>>,
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) {
info!("start space");
game_state.set(GameState::Game);
}
if let Ok((_player, mut transform)) = player_query.get_single_mut() {
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_x((-PI / 2000.0) as f32); // Rotate by -3 degrees
transform.rotation *= rotation; // Apply the rotation
rotation *= Quat::from_rotation_y((PI / 6000.0) as f32);
rotation *= Quat::from_rotation_x((-PI / 2000.0) as f32);
transform.rotation *= rotation;
}
}