Can read config files now

- Now reads config from `$XDG_CONFIG_HOME/.config/snake/snake.yaml`
- Added error enum from config and try to remove all usages of unwrap
- Bumped version to 0.2.3
This commit is contained in:
Uttarayan Mondal
2021-03-15 22:27:35 +05:30
parent 2a4c4889af
commit 6c178b6a81
6 changed files with 118 additions and 40 deletions
Generated
+87 -11
View File
@@ -1,5 +1,7 @@
# This file is automatically @generated by Cargo. # This file is automatically @generated by Cargo.
# It is not intended for manual editing. # It is not intended for manual editing.
version = 3
[[package]] [[package]]
name = "arrayref" name = "arrayref"
version = "0.3.6" version = "0.3.6"
@@ -35,6 +37,12 @@ dependencies = [
"constant_time_eq", "constant_time_eq",
] ]
[[package]]
name = "case"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e88b166b48e29667f5443df64df3c61dc07dc2b1a0b0d231800e07f09a33ecc1"
[[package]] [[package]]
name = "cc" name = "cc"
version = "1.0.66" version = "1.0.66"
@@ -64,6 +72,17 @@ dependencies = [
"lazy_static", "lazy_static",
] ]
[[package]]
name = "derive-error"
version = "0.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eb6238eafbc141db51c6d0d599dde74224b28437c7cf7c3a1755e3e3e5e00806"
dependencies = [
"case",
"quote 0.3.15",
"syn 0.11.11",
]
[[package]] [[package]]
name = "dirs" name = "dirs"
version = "3.0.1" version = "3.0.1"
@@ -84,6 +103,12 @@ dependencies = [
"winapi", "winapi",
] ]
[[package]]
name = "dtoa"
version = "0.4.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "88d7ed2934d741c6b37e33e3832298e8850b53fd2d2bea03873375596c7cea4e"
[[package]] [[package]]
name = "getrandom" name = "getrandom"
version = "0.1.16" version = "0.1.16"
@@ -118,6 +143,12 @@ version = "0.2.82"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "89203f3fba0a3795506acaad8ebce3c80c0af93f994d5a1d7a0b1eeb23271929" checksum = "89203f3fba0a3795506acaad8ebce3c80c0af93f994d5a1d7a0b1eeb23271929"
[[package]]
name = "linked-hash-map"
version = "0.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7fb9b38af92608140b86b693604b9ffcc5824240a484d1ecd4795bacb2fe88f3"
[[package]] [[package]]
name = "ncurses" name = "ncurses"
version = "5.100.0" version = "5.100.0"
@@ -147,9 +178,15 @@ version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e0704ee1a7e00d7bb417d0770ea303c1bccbabf0ef1667dae92b5967f5f8a71" checksum = "1e0704ee1a7e00d7bb417d0770ea303c1bccbabf0ef1667dae92b5967f5f8a71"
dependencies = [ dependencies = [
"unicode-xid", "unicode-xid 0.2.1",
] ]
[[package]]
name = "quote"
version = "0.3.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a6e920b65c65f10b2ae65c831a81a073a89edd28c7cce89475bff467ab4167a"
[[package]] [[package]]
name = "quote" name = "quote"
version = "1.0.8" version = "1.0.8"
@@ -244,19 +281,43 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f3fcab8778dc651bc65cfab2e4eb64996f3c912b74002fb379c94517e1f27c46" checksum = "f3fcab8778dc651bc65cfab2e4eb64996f3c912b74002fb379c94517e1f27c46"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote 1.0.8",
"syn", "syn 1.0.60",
]
[[package]]
name = "serde_yaml"
version = "0.8.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "15654ed4ab61726bf918a39cb8d98a2e2995b002387807fa6ba58fdf7f59bb23"
dependencies = [
"dtoa",
"linked-hash-map",
"serde",
"yaml-rust",
] ]
[[package]] [[package]]
name = "snake" name = "snake"
version = "0.2.1" version = "0.2.2"
dependencies = [ dependencies = [
"derive-error",
"dirs", "dirs",
"ncurses", "ncurses",
"rand", "rand",
"serde", "serde",
"toml", "serde_yaml",
]
[[package]]
name = "syn"
version = "0.11.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3b891b9015c88c576343b9b3e41c2c11a51c219ef067b264bd9c8aa9b441dad"
dependencies = [
"quote 0.3.15",
"synom",
"unicode-xid 0.0.4",
] ]
[[package]] [[package]]
@@ -266,19 +327,25 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c700597eca8a5a762beb35753ef6b94df201c81cca676604f547495a0d7f0081" checksum = "c700597eca8a5a762beb35753ef6b94df201c81cca676604f547495a0d7f0081"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote 1.0.8",
"unicode-xid", "unicode-xid 0.2.1",
] ]
[[package]] [[package]]
name = "toml" name = "synom"
version = "0.5.8" version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a31142970826733df8241ef35dc040ef98c679ab14d7c3e54d827099b3acecaa" checksum = "a393066ed9010ebaed60b9eafa373d4b1baac186dd7e008555b0f702b51945b6"
dependencies = [ dependencies = [
"serde", "unicode-xid 0.0.4",
] ]
[[package]]
name = "unicode-xid"
version = "0.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8c1f860d7d29cf02cb2f3f359fd35991af3d30bac52c57d265a3c461074cb4dc"
[[package]] [[package]]
name = "unicode-xid" name = "unicode-xid"
version = "0.2.1" version = "0.2.1"
@@ -318,3 +385,12 @@ name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0" version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
[[package]]
name = "yaml-rust"
version = "0.4.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56c1936c4cc7a1c9ab21a1ebb602eb942ba868cbd44a99cb7cdc5892335e1c85"
dependencies = [
"linked-hash-map",
]
+3 -4
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "snake" name = "snake"
version = "0.2.2" version = "0.2.3"
authors = ["Uttarayan Mondal <uttarayan21@gmail.com>"] authors = ["Uttarayan Mondal <uttarayan21@gmail.com>"]
edition = "2018" edition = "2018"
@@ -9,8 +9,7 @@ edition = "2018"
[dependencies] [dependencies]
ncurses = "5.100.0" ncurses = "5.100.0"
serde = { version = "1.0.121", features = ["derive"] } serde = { version = "1.0.121", features = ["derive"] }
# serde = "1.0.121" serde_yaml = "0.8.17"
# serde_derive = "1.0.121"
toml = "0.5.8"
rand = "0.8.0" rand = "0.8.0"
dirs = "3.0.1" dirs = "3.0.1"
derive-error = "0.0.5"
+9 -9
View File
@@ -8,10 +8,9 @@ use std::ops::Sub;
use std::thread::sleep; use std::thread::sleep;
use std::time::Duration; use std::time::Duration;
#[derive(Serialize, Deserialize, Clone, Copy)] #[derive(Debug, Serialize, Deserialize, Clone, Copy)]
#[serde(tag = "type", content = "value")]
pub enum Difficulty { pub enum Difficulty {
Linear(f32), Linear(u8),
Flat, Flat,
} }
@@ -162,9 +161,10 @@ impl Board {
} }
pub fn check_collision(&mut self, snake: &Snake) -> bool { pub fn check_collision(&mut self, snake: &Snake) -> bool {
let (snake_line, snake_col): (u32, u32) = snake.posyx(); let (snake_line, snake_col): (u32, u32) = snake.posyx();
if (snake_line >= self.maxlines - 1) || (snake_col >= self.maxcols - 1) if (snake_line >= self.maxlines - 1)
// || (snake_line <= 0) || (snake_col >= self.maxcols - 1)
// || (snake_col <= 0) || (snake_line == 0)
|| (snake_col == 0)
{ {
self.gamestate = GameState::Failed(FailState::Wall); self.gamestate = GameState::Failed(FailState::Wall);
return true; return true;
@@ -222,7 +222,7 @@ pub struct Snake {
direction: Direction, direction: Direction,
difficulty: Difficulty, difficulty: Difficulty,
grow: bool, grow: bool,
speed: u32, speed: f32,
last_tail: Option<Cell>, last_tail: Option<Cell>,
} }
impl Snake { impl Snake {
@@ -275,13 +275,13 @@ impl Snake {
// let time: std::time::Duration = // let time: std::time::Duration =
// std::time::Duration::from_millis((1000 / self.speed) as u64); // std::time::Duration::from_millis((1000 / self.speed) as u64);
// sleep(time); // sleep(time);
sleep(Duration::from_millis((1000 / self.speed) as u64)); sleep(Duration::from_millis(1000 / self.speed as u64));
self.smove(self.direction); self.smove(self.direction);
} }
pub fn scale_difficulty(&mut self) { pub fn scale_difficulty(&mut self) {
match self.difficulty { match self.difficulty {
Difficulty::Flat => (), Difficulty::Flat => (),
Difficulty::Linear(scale) => self.speed = (self.speed as f32 * scale) as u32, Difficulty::Linear(scale) => self.speed *= scale as f32 / 256_f32 + 1_f32,
} }
} }
pub fn grow(&mut self) { pub fn grow(&mut self) {
+1 -1
View File
@@ -28,7 +28,7 @@ pub fn start(config: &Config) {
loop { loop {
frontend::draw_snake(&snake, game_win); // always draw snake before board because the snake will clear the game win frontend::draw_snake(&snake, game_win); // always draw snake before board because the snake will clear the game win
frontend::draw_board(&board, game_win); frontend::draw_board(&board, game_win);
frontend::_log(&snake, &board); // frontend::_log(&snake, &board);
if board.check_collision(&snake) { if board.check_collision(&snake) {
// Add stuff here to show the score and // Add stuff here to show the score and
// how You lose screen // how You lose screen
+2 -2
View File
@@ -1,10 +1,11 @@
extern crate ncurses; extern crate ncurses;
#[macro_use]
extern crate derive_error;
mod game; mod game;
mod highscore; mod highscore;
mod menu; mod menu;
mod settings; mod settings;
// use game::{Cell, Snake}; // use game::{Cell, Snake};
// use ncurses::*;
use ncurses::{ use ncurses::{
curs_set, endwin, getmaxyx, initscr, keypad, noecho, raw, refresh, setlocale, stdscr, curs_set, endwin, getmaxyx, initscr, keypad, noecho, raw, refresh, setlocale, stdscr,
LcCategory, CURSOR_VISIBILITY, LcCategory, CURSOR_VISIBILITY,
@@ -36,5 +37,4 @@ fn main() {
} }
refresh(); refresh();
endwin(); endwin();
config.write();
} }
+16 -13
View File
@@ -1,7 +1,5 @@
extern crate dirs; extern crate dirs;
extern crate serde; extern crate serde;
// extern crate serde_derive;
extern crate toml;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
// use serde_derive::{Deserialize, Serialize}; // use serde_derive::{Deserialize, Serialize};
use crate::game::Difficulty; use crate::game::Difficulty;
@@ -10,21 +8,26 @@ use std::io::{Read, Write};
use std::path::PathBuf; use std::path::PathBuf;
use std::thread::sleep; use std::thread::sleep;
#[derive(Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
pub struct Config { pub struct Config {
pub difficulty: Difficulty, pub difficulty: Difficulty,
pub speed: u32, pub speed: f32,
}
#[derive(Debug, Error)]
pub enum ConfigError {
FileSystemError(std::io::Error),
ParsingError(serde_yaml::Error),
} }
impl Config { impl Config {
pub fn new() -> Result<Self, std::io::Error> { pub fn new() -> Result<Self, ConfigError> {
let config_path = Config::config_path().unwrap(); let config_path = Config::config_path().unwrap();
if config_path.exists() { if config_path.exists() {
let mut config_file = File::open(config_path).unwrap(); let mut config_file = File::open(config_path).unwrap();
let mut config_file_str: String = String::new(); let mut config_file_str: String = String::new();
config_file.read_to_string(&mut config_file_str).unwrap(); config_file.read_to_string(&mut config_file_str).unwrap();
// let config: Config = toml::from_str(&config_file_str).expect("Error in config file"); let config: Config = match serde_yaml::from_str(&config_file_str) {
let config: Config = match toml::from_str(&config_file_str) {
Ok(config) => config, Ok(config) => config,
Err(e) => { Err(e) => {
eprintln!( eprintln!(
@@ -33,7 +36,7 @@ impl Config {
e, e,
); );
eprintln!("Falling back to using the default values"); eprintln!("Falling back to using the default values");
sleep(std::time::Duration::from_millis(3000)); sleep(std::time::Duration::from_millis(1000));
Config::default() Config::default()
} }
}; };
@@ -46,11 +49,11 @@ impl Config {
fn default() -> Self { fn default() -> Self {
Self { Self {
difficulty: Difficulty::Flat, //Default set to ten blocks per second difficulty: Difficulty::Flat, //Default set to ten blocks per second
speed: 10, speed: 10_f32,
} }
} }
pub fn write(&self) { pub fn _write(&self) {
let config_file_str: String = toml::to_string(self).unwrap(); let config_file_str: String = serde_yaml::to_string(self).unwrap();
let config_path = Config::config_path().unwrap(); let config_path = Config::config_path().unwrap();
let mut config_file: File = let mut config_file: File =
File::create(config_path).expect("Couldn't open config file to write"); File::create(config_path).expect("Couldn't open config file to write");
@@ -62,13 +65,13 @@ impl Config {
let config_path: PathBuf = match dirs::config_dir() { let config_path: PathBuf = match dirs::config_dir() {
Some(mut path) => { Some(mut path) => {
path.push("snake"); path.push("snake");
path.push("snake.toml"); path.push("snake.yaml");
path path
} }
None => { None => {
return Err(std::io::Error::new( return Err(std::io::Error::new(
std::io::ErrorKind::NotFound, std::io::ErrorKind::NotFound,
"snake.toml not found", "snake.yaml not found",
)); ));
} }
}; };