Skip to content

Commit

Permalink
save game statistics
Browse files Browse the repository at this point in the history
this is a work in progress

ok this is progress. the game saves all attempts now
```
{"games":[{"attempts":[12,28],"secret_number":28,"guesses":[12,28]},{"attempts":[1,17,18],"secret_number":18,"guesses":[1,17,18]},{"attempts":[3,33,32,31,30,29],"secret_number":29,"guesses":[3,33,32,31,30,29]}]}
```

however, looks like I only display the latest game?

:/Users/kushal/RustroverProjects/helloworld/target/debug/helloworld.exe
Guess the number!
Remember, you can update your consent by running this application with the --update-consent flag.
Please input your guess.
3
You guessed: 3
Too small!
The sum of your guess and the secret number is: 32
The product of your guess and the secret number is: 87
The greatest common divisor of your guess and the secret number is: 1
Please input your guess.
33
You guessed: 33
Too big!
The sum of your guess and the secret number is: 62
The product of your guess and the secret number is: 957
The greatest common divisor of your guess and the secret number is: 1
Please input your guess.
32
You guessed: 32
Too big!
The sum of your guess and the secret number is: 61
The product of your guess and the secret number is: 928
The greatest common divisor of your guess and the secret number is: 1
Please input your guess.
31
You guessed: 31
Too big!
The sum of your guess and the secret number is: 60
The product of your guess and the secret number is: 899
The greatest common divisor of your guess and the secret number is: 1
Please input your guess.
30
You guessed: 30
Too big!
The sum of your guess and the secret number is: 59
The product of your guess and the secret number is: 870
The greatest common divisor of your guess and the secret number is: 1
Please input your guess.
29
You guessed: 29
You win!
Game Statistics:
Attempts: [3, 33, 32, 31, 30, 29]
Secret Number: 29
Guesses: [3, 33, 32, 31, 30, 29]
Press Enter to exit...

context
mod my_math;
mod shadowing;
mod my_data_types;
mod greatest_common_divisor;
mod game_stats;
mod game_error;
mod game_history;

use rand::Rng;
use std::cmp::Ordering;
use std::env;
use std::fs;
use std::io;
use reqwest::blocking::Client;
use etcetera::{choose_app_strategy, AppStrategyArgs, AppStrategy};
use serde::{Deserialize, Serialize};
use game_stats::GameStats;
use game_error::GameError;
use game_history::GameHistory;

#[derive(Serialize, Deserialize)]
struct Config {
    analytics_consent: bool,
}

fn main() -> Result<(), GameError> {
    let strategy = choose_app_strategy(AppStrategyArgs {
        top_level_domain: "org".to_string(),
        author: "Kushal Hada".to_string(),
        app_name: "KusGuessingGame".to_string(),
    }).unwrap();

    let config_path = strategy.config_dir().join("config.json");
    let mut config = if config_path.exists() {
        let config_data = fs::read_to_string(&config_path).expect("Unable to read config file");
        serde_json::from_str(&config_data).expect("Unable to parse config file")
    } else {
        Config { analytics_consent: false }
    };

    let args: Vec<String> = env::args().collect();
    if args.len() > 1 && args[1] == "--update-consent" {
        println!("Do you consent to analytics? (yes/no)");
        let mut consent = String::new();
        io::stdin().read_line(&mut consent).expect("Failed to read line");
        config.analytics_consent = matches!(consent.trim().to_lowercase().as_str(), "yes" | "y");
        let config_data = serde_json::to_string(&config).expect("Unable to serialize config");
        fs::create_dir_all(strategy.config_dir()).expect("Unable to create config directory");
        fs::write(&config_path, config_data).expect("Unable to write config file");
        println!("Consent updated successfully.");
        return Ok(());
    }

    play_guessing_game(config.analytics_consent)?;
    Ok(())
}

fn play_guessing_game(analytics_consent: bool) -> Result<(), GameError> {
    println!("Guess the number!");
    println!("Remember, you can update your consent by running this application with the --update-consent flag.");

    let secret_number = rand::thread_rng().gen_range(1..=100);
    let mut attempts = Vec::new(); // Initialize attempts as a vector
    let mut guesses = Vec::new(); // Initialize guesses as a mutable vector

    loop {
        println!("Please input your guess.");

        let mut guess = String::new();

        io::stdin()
            .read_line(&mut guess)
            .expect("Failed to read line");

        let guess: u32 = match guess.trim().parse() {
            Ok(num) => num,
            Err(_) => continue,
        };

        attempts.push(guess); // Add each guess to attempts
        guesses.push(guess); // Add each guess to guesses

        println!("You guessed: {guess}");

        match guess.cmp(&secret_number) {
            Ordering::Less => println!("Too small!"),
            Ordering::Greater => println!("Too big!"),
            Ordering::Equal => {
                println!("You win!");
                if analytics_consent {
                    fetch_hello_world()?;
                }
                println!("Game Statistics:");
                println!("Attempts: {:?}", attempts);
                println!("Secret Number: {}", secret_number);
                println!("Guesses: {:?}", guesses);

                let game_stats = GameStats {
                    attempts,
                    secret_number,
                    guesses,
                };

                save_game_stats(&game_stats)?;

                println!("Press Enter to exit...");
                let mut exit = String::new();
                io::stdin().read_line(&mut exit).expect("Failed to read line");
                break;
            }
        }

        let sum = my_math::add(guess, secret_number);
        println!("The sum of your guess and the secret number is: {sum}");
        let product = my_math::multiply(guess, secret_number);
        println!("The product of your guess and the secret number is: {product}");

        let gcd = greatest_common_divisor::gcd(guess, secret_number);
        println!("The greatest common divisor of your guess and the secret number is: {gcd}");
    }

    Ok(())
}

fn save_game_stats(game_stats: &GameStats) -> Result<(), GameError> {
    let strategy = choose_app_strategy(AppStrategyArgs {
        top_level_domain: "org".to_string(),
        author: "Kushal Hada".to_string(),
        app_name: "KusGuessingGame".to_string(),
    }).unwrap();

    let stats_path = strategy.data_dir().join("game_stats.json");

    let mut game_history = if stats_path.exists() {
        let stats_data = fs::read_to_string(&stats_path)?;
        serde_json::from_str(&stats_data).unwrap_or(GameHistory { games: Vec::new() })
    } else {
        GameHistory { games: Vec::new() }
    };

    game_history.games.push(game_stats.clone());

    let stats_data = serde_json::to_string(&game_history).expect("Unable to serialize game stats");
    fs::create_dir_all(strategy.data_dir()).expect("Unable to create data directory");
    fs::write(stats_path, stats_data)?;

    Ok(())
}

fn fetch_hello_world() -> Result<(), GameError> {
    let client = Client::new();
    match client.get("https://nice.runasp.net/Analytics/HelloWorld").send() {
        Ok(response) => {
            let text = response.text()?;
            println!("Response from server: {text}");
        }
        Err(e) => {
            println!("Failed to fetch response: {e}");
        }
    }
    Ok(())
}
  • Loading branch information
9034725985 committed Aug 8, 2024
1 parent 4205515 commit 9ee7abc
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 33 deletions.
7 changes: 7 additions & 0 deletions src/game_history.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
use serde::{Deserialize, Serialize};
use crate::game_stats::GameStats;

#[derive(Serialize, Deserialize)]
pub struct GameHistory {
pub games: Vec<GameStats>,
}
2 changes: 1 addition & 1 deletion src/game_stats.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// src/game_stats.rs
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]
#[derive(Serialize, Deserialize, Clone)]
pub struct GameStats {
pub attempts: Vec<u32>,
pub secret_number: u32,
Expand Down
59 changes: 27 additions & 32 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ mod my_data_types;
mod greatest_common_divisor;
mod game_stats;
mod game_error;
mod game_history;

use rand::Rng;
use std::cmp::Ordering;
Expand All @@ -15,6 +16,7 @@ use etcetera::{choose_app_strategy, AppStrategyArgs, AppStrategy};
use serde::{Deserialize, Serialize};
use game_stats::GameStats;
use game_error::GameError;
use game_history::GameHistory;

#[derive(Serialize, Deserialize)]
struct Config {
Expand Down Expand Up @@ -49,15 +51,6 @@ fn main() -> Result<(), GameError> {
return Ok(());
}

if args.len() > 1 && args[1] == "--show-stats" {
let game_stats = read_game_stats()?;
println!("Game Statistics:");
println!("Attempts: {:?}", game_stats.attempts);
println!("Secret Number: {}", game_stats.secret_number);
println!("Guesses: {:?}", game_stats.guesses);
return Ok(());
}

play_guessing_game(config.analytics_consent)?;
Ok(())
}
Expand Down Expand Up @@ -97,6 +90,19 @@ fn play_guessing_game(analytics_consent: bool) -> Result<(), GameError> {
if analytics_consent {
fetch_hello_world()?;
}
println!("Game Statistics:");
println!("Attempts: {:?}", attempts);
println!("Secret Number: {}", secret_number);
println!("Guesses: {:?}", guesses);

let game_stats = GameStats {
attempts,
secret_number,
guesses,
};

save_game_stats(&game_stats)?;

println!("Press Enter to exit...");
let mut exit = String::new();
io::stdin().read_line(&mut exit).expect("Failed to read line");
Expand All @@ -113,14 +119,6 @@ fn play_guessing_game(analytics_consent: bool) -> Result<(), GameError> {
println!("The greatest common divisor of your guess and the secret number is: {gcd}");
}

let game_stats = GameStats {
attempts,
secret_number,
guesses,
};

save_game_stats(&game_stats)?;

Ok(())
}

Expand All @@ -132,13 +130,24 @@ fn save_game_stats(game_stats: &GameStats) -> Result<(), GameError> {
}).unwrap();

let stats_path = strategy.data_dir().join("game_stats.json");
let stats_data = serde_json::to_string(&game_stats).expect("Unable to serialize game stats");

let mut game_history = if stats_path.exists() {
let stats_data = fs::read_to_string(&stats_path)?;
serde_json::from_str(&stats_data).unwrap_or(GameHistory { games: Vec::new() })
} else {
GameHistory { games: Vec::new() }
};

game_history.games.push(game_stats.clone());

let stats_data = serde_json::to_string(&game_history).expect("Unable to serialize game stats");
fs::create_dir_all(strategy.data_dir()).expect("Unable to create data directory");
fs::write(stats_path, stats_data)?;

Ok(())
}


fn fetch_hello_world() -> Result<(), GameError> {
let client = Client::new();
match client.get("https://nice.runasp.net/Analytics/HelloWorld").send() {
Expand All @@ -152,17 +161,3 @@ fn fetch_hello_world() -> Result<(), GameError> {
}
Ok(())
}

fn read_game_stats() -> Result<GameStats, GameError> {
let strategy = choose_app_strategy(AppStrategyArgs {
top_level_domain: "org".to_string(),
author: "Kushal Hada".to_string(),
app_name: "KusGuessingGame".to_string(),
}).unwrap();

let stats_path = strategy.data_dir().join("game_stats.json");
let stats_data = fs::read_to_string(&stats_path)?;
let game_stats: GameStats = serde_json::from_str(&stats_data)?;

Ok(game_stats)
}

0 comments on commit 9ee7abc

Please sign in to comment.