implement error handling for game

This commit is contained in:
Max Bradbury 2020-04-18 17:48:29 +01:00
parent c47c4205aa
commit 434e98cc60
1 changed files with 30 additions and 22 deletions

View File

@ -2,6 +2,7 @@ use crate::{
optional_data_line, Avatar, Dialogue, Ending, Font, Item, Palette, Room, Sprite, TextDirection, optional_data_line, Avatar, Dialogue, Ending, Font, Item, Palette, Room, Sprite, TextDirection,
Tile, ToBase36, Variable, Tile, ToBase36, Variable,
}; };
use std::error::Error;
#[derive(Debug, Eq, PartialEq)] #[derive(Debug, Eq, PartialEq)]
pub struct Version { pub struct Version {
@ -39,8 +40,8 @@ pub struct Game {
pub variables: Vec<Variable>, pub variables: Vec<Variable>,
} }
impl From<String> for Game { impl Game {
fn from(string: String) -> Game { fn from(string: String) -> Result<Game, &'static dyn Error> {
let mut string = format!("{}\n\n", string.trim_matches('\n')); let mut string = format!("{}\n\n", string.trim_matches('\n'));
if string.starts_with("# BITSY VERSION") { if string.starts_with("# BITSY VERSION") {
@ -142,6 +143,7 @@ impl From<String> for Game {
assert!(avatar.is_some()); assert!(avatar.is_some());
let avatar = avatar.unwrap(); let avatar = avatar.unwrap();
Ok (
Game { Game {
name, name,
version, version,
@ -159,6 +161,7 @@ impl From<String> for Game {
endings, endings,
variables, variables,
} }
)
} }
} }
@ -301,7 +304,9 @@ impl Game {
#[test] #[test]
fn test_game_from_string() { fn test_game_from_string() {
let output = Game::from(include_str!["test-resources/default.bitsy"].to_string()); let output = Game::from(
include_str!["test-resources/default.bitsy"].to_string()
).unwrap();
let expected = crate::mock::game_default(); let expected = crate::mock::game_default();
@ -412,7 +417,7 @@ fn test_bitsy_omnibus() {
println!("Testing: {}...", path.display()); println!("Testing: {}...", path.display());
let game_data = std::fs::read_to_string(path).unwrap(); let game_data = std::fs::read_to_string(path).unwrap();
let game = Game::from(game_data.clone()); let game = Game::from(game_data.clone()).unwrap();
assert_eq!( assert_eq!(
game.to_string().trim_matches('\n'), game.to_string().trim_matches('\n'),
game_data.trim_matches('\n') game_data.trim_matches('\n')
@ -424,7 +429,10 @@ fn test_bitsy_omnibus() {
#[test] #[test]
fn test_arabic() { fn test_arabic() {
let game = Game::from(include_str!("test-resources/arabic.bitsy").to_string()); let game = Game::from(
include_str!("test-resources/arabic.bitsy").to_string()
).unwrap();
assert_eq!(game.font, Font::Arabic); assert_eq!(game.font, Font::Arabic);
assert_eq!(game.text_direction, TextDirection::RightToLeft); assert_eq!(game.text_direction, TextDirection::RightToLeft);
} }