Compare commits

..
10 Commits
4 changed files with 208 additions and 43 deletions

No files matched your search

-4
View File
@@ -1,7 +1,3 @@
To anyone will read this against all odds: Hello, I appreciate you being here.
---
So [Mankala](https://wikipedia.org/wiki/Mancala) (aka Mancala or Kalaha) is a simple fun game with marbles that I used So [Mankala](https://wikipedia.org/wiki/Mancala) (aka Mancala or Kalaha) is a simple fun game with marbles that I used
to play with a friend of mine now and again. In doing so, we theorized a lot about optimal strategies and eventually to play with a friend of mine now and again. In doing so, we theorized a lot about optimal strategies and eventually
thought about using [Reinforcement Learning](https://wikipedia.org/wiki/Reinforcement_learning) to aid us in that thought about using [Reinforcement Learning](https://wikipedia.org/wiki/Reinforcement_learning) to aid us in that
+128
View File
@@ -0,0 +1,128 @@
use std::{
error::Error,
fs,
io::{self, Stdin},
};
use mankalla_rl::{
mankalla::{MankallaGame, MankallaGameState, Player},
q_learning::{Deserialize, Environment, EpsilonGreedyPolicy, Policy, QLearning, Serialize},
};
fn main() -> Result<(), Box<dyn Error>> {
let mut policy = match fs::read_to_string("policy.csv") {
Ok(s) => EpsilonGreedyPolicy::<MankallaGame>::deserialize(s.as_str())?,
Err(_) => EpsilonGreedyPolicy::<MankallaGame>::new(0.2, 1., 1., 0.1, -0.01),
};
// QLearning::train(&mut policy, 1000, None);
game_loop(&mut policy);
fs::write("policy.csv", policy.serialize())?;
Ok(())
}
fn game_loop(policy: &mut impl Policy<MankallaGame>) {
let mut turn: usize = 1;
let mut state = MankallaGame::new();
let mut finished;
println!("{}", state);
let stdin = io::stdin();
let action;
match get_player_input(&stdin) {
PlayerRequest::Action(a) => {
action = a;
}
PlayerRequest::Quit => {
println!("Ok, goodbye");
return;
}
};
(state, finished) = player_turn(state, action, policy, &mut turn);
while !finished {
match state.get_player_to_move() {
Player::Player2 => {
(state, finished) = bot_turn(state, policy, &mut turn);
}
Player::Player1 => {
let action;
match get_player_input(&stdin) {
PlayerRequest::Action(a) => {
action = a;
}
PlayerRequest::Quit => {
println!("Ok, goodbye");
return;
}
};
(state, finished) = player_turn(state, action, policy, &mut turn);
}
}
}
}
enum PlayerRequest {
Action(u8),
Quit,
}
fn get_player_input(stdin: &Stdin) -> PlayerRequest {
println!("Choose your action: (0,1,2,3,4,5,q)");
let mut input = String::new();
loop {
stdin
.read_line(&mut input)
.expect("Something with stdin went wrong");
match input.as_str().strip_suffix("\n").unwrap_or("") {
digit @ ("0" | "1" | "2" | "3" | "4" | "5") => {
return PlayerRequest::Action(digit.parse().expect("Guaranteed to work"));
}
"q" => return PlayerRequest::Quit,
_ => continue,
}
}
}
fn player_turn(
state: MankallaGameState,
action: u8,
policy: &mut impl Policy<MankallaGame>,
turn: &mut usize,
) -> (MankallaGameState, bool) {
println!("Turn {turn}, you chose {action}");
let (next_state, reward, finished) = MankallaGame::step(&state, &action);
println!("{}", next_state);
policy.improve(state.into(), action, reward, next_state, finished);
*turn += 1;
(next_state, finished)
}
fn bot_turn(
state: MankallaGameState,
policy: &mut impl Policy<MankallaGame>,
turn: &mut usize,
) -> (MankallaGameState, bool) {
let action = policy.choose_action(state.into());
println!("Turn {turn}, bot chose {action}");
let (next_state, reward, finished) = MankallaGame::step(&state, &action);
println!("{}", next_state);
policy.improve(state.into(), action, reward, next_state, finished);
*turn += 1;
(next_state, finished)
}
+17 -8
View File
@@ -35,7 +35,7 @@ impl Environment for MankallaGame {
.collect() .collect()
} }
fn step(state: &Self::State, action: &Self::Action) -> (Option<Self::State>, f32) { fn step(state: &Self::State, action: &Self::Action) -> (Self::State, f32, bool) {
let mut state = state.clone(); let mut state = state.clone();
let p1_points = state.get_points(&Player::Player1); let p1_points = state.get_points(&Player::Player1);
@@ -70,13 +70,9 @@ impl Environment for MankallaGame {
reward *= -1f32; reward *= -1f32;
} }
if finished {
return (None, reward);
}
state.handle_switch_player(i); state.handle_switch_player(i);
return (Some(state), reward); return (state, reward, finished);
} }
} }
@@ -185,6 +181,10 @@ impl Default for MankallaGameState {
} }
impl MankallaGameState { impl MankallaGameState {
pub fn get_player_to_move(&self) -> Player {
self.player_to_move
}
fn get_points(&self, player: &Player) -> u8 { fn get_points(&self, player: &Player) -> u8 {
match player { match player {
Player::Player1 => self.fields[6], Player::Player1 => self.fields[6],
@@ -193,12 +193,21 @@ impl MankallaGameState {
} }
fn handle_steal(&mut self, i: usize) { fn handle_steal(&mut self, i: usize) {
if self.fields[i] == 1 && self.player_to_move == Player::Player1 && i < 6 { if self.fields[i] == 1
&& self.player_to_move == Player::Player1
&& i < 6
&& self.fields[12 - i] > 0
{
self.fields[6] += self.fields[i] + self.fields[12 - i]; self.fields[6] += self.fields[i] + self.fields[12 - i];
self.fields[i] = 0; self.fields[i] = 0;
self.fields[12 - i] = 0; self.fields[12 - i] = 0;
} }
if self.fields[i] == 1 && self.player_to_move == Player::Player2 && 6 < i && i < 13 { if self.fields[i] == 1
&& self.player_to_move == Player::Player2
&& 6 < i
&& i < 13
&& self.fields[12 - i] > 0
{
self.fields[13] += self.fields[i] + self.fields[12 - i]; self.fields[13] += self.fields[i] + self.fields[12 - i];
self.fields[i] = 0; self.fields[i] = 0;
self.fields[12 - i] = 0; self.fields[12 - i] = 0;
+63 -31
View File
@@ -1,4 +1,5 @@
use std::collections::HashMap; use std::collections::HashMap;
use std::error::Error;
use std::fmt::Display; use std::fmt::Display;
use std::hash::Hash; use std::hash::Hash;
@@ -9,7 +10,7 @@ pub trait Environment {
type ActionRelevantState: From<Self::State> + Copy + Eq + Hash + Serialize + Deserialize; type ActionRelevantState: From<Self::State> + Copy + Eq + Hash + Serialize + Deserialize;
type Action: Copy + Eq + Hash + Serialize + Deserialize; type Action: Copy + Eq + Hash + Serialize + Deserialize;
fn actions(state: &Self::ActionRelevantState) -> Vec<Self::Action>; fn actions(state: &Self::ActionRelevantState) -> Vec<Self::Action>;
fn step(state: &Self::State, action: &Self::Action) -> (Option<Self::State>, f32); fn step(state: &Self::State, action: &Self::Action) -> (Self::State, f32, bool);
fn new() -> Self::State; fn new() -> Self::State;
} }
@@ -17,10 +18,11 @@ pub trait Policy<E: Environment> {
fn choose_action(&self, state: E::ActionRelevantState) -> E::Action; fn choose_action(&self, state: E::ActionRelevantState) -> E::Action;
fn improve( fn improve(
&mut self, &mut self,
state: &E::ActionRelevantState, state: E::ActionRelevantState,
action: E::Action, action: E::Action,
reward: f32, reward: f32,
next_state: Option<&E::State>, next_state: E::State,
finished: bool,
); );
fn on_episode_increment(&mut self) {} fn on_episode_increment(&mut self) {}
} }
@@ -35,8 +37,11 @@ pub trait Deserialize {
Self: Sized; Self: Sized;
} }
#[derive(Debug)]
pub struct DeserializeError; pub struct DeserializeError;
impl Error for DeserializeError {}
impl Display for DeserializeError { impl Display for DeserializeError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Error deserializing input") write!(f, "Error deserializing input")
@@ -62,7 +67,8 @@ impl QLearning {
if let Some(m) = max_steps { if let Some(m) = max_steps {
for _ in 0..m { for _ in 0..m {
if let Some(next_state) = QLearning::choose_and_improve(policy, state) { let (next_state, finished) = QLearning::choose_and_improve(policy, state);
if !finished {
state = next_state; state = next_state;
} else { } else {
break; break;
@@ -70,7 +76,8 @@ impl QLearning {
} }
} else { } else {
loop { loop {
if let Some(next_state) = QLearning::choose_and_improve(policy, state) { let (next_state, finished) = QLearning::choose_and_improve(policy, state);
if !finished {
state = next_state; state = next_state;
} else { } else {
break; break;
@@ -82,12 +89,12 @@ impl QLearning {
fn choose_and_improve<E: Environment>( fn choose_and_improve<E: Environment>(
policy: &mut impl Policy<E>, policy: &mut impl Policy<E>,
state: E::State, state: E::State,
) -> Option<E::State> { ) -> (E::State, bool) {
let action = policy.choose_action(state.into()); let action = policy.choose_action(state.into());
let (next_state, reward) = E::step(&state, &action); let (next_state, reward, finished) = E::step(&state, &action);
policy.improve(&state.into(), action, reward, next_state.as_ref()); policy.improve(state.into(), action, reward, next_state, finished);
next_state (next_state, finished)
} }
} }
@@ -97,6 +104,16 @@ pub struct GreedyPolicy<E: Environment> {
gamma: f32, gamma: f32,
} }
impl<E: Environment> GreedyPolicy<E> {
pub fn new(learning_rate: f32, gamma: f32) -> Self {
GreedyPolicy {
qtable: HashMap::new(),
learning_rate,
gamma,
}
}
}
impl<E: Environment> Policy<E> for GreedyPolicy<E> { impl<E: Environment> Policy<E> for GreedyPolicy<E> {
fn choose_action(&self, state: E::ActionRelevantState) -> E::Action { fn choose_action(&self, state: E::ActionRelevantState) -> E::Action {
let actions = E::actions(&state); let actions = E::actions(&state);
@@ -113,28 +130,26 @@ impl<E: Environment> Policy<E> for GreedyPolicy<E> {
} }
fn improve( fn improve(
&mut self, &mut self,
state: &E::ActionRelevantState, state: E::ActionRelevantState,
action: E::Action, action: E::Action,
reward: f32, reward: f32,
next_state: Option<&E::State>, next_state: E::State,
finished: bool,
) { ) {
let former_value = *self.qtable.get(&(*state, action)).unwrap_or(&0f32); let former_value = *self.qtable.get(&(state, action)).unwrap_or(&0f32);
let target = match next_state { let target = reward
Some(next_state) => { + match finished {
reward false => {
+ self.gamma self.gamma
* self * self
.qtable .qtable
.get(&( .get(&(next_state.into(), self.choose_action(next_state.into())))
(*next_state).into(),
self.choose_action((*next_state).into()),
))
.unwrap_or(&0f32) .unwrap_or(&0f32)
} }
None => 0f32, true => 0f32,
}; };
self.qtable.insert( self.qtable.insert(
(*state, action), (state, action),
former_value + self.learning_rate * (target - former_value), former_value + self.learning_rate * (target - former_value),
); );
} }
@@ -142,14 +157,14 @@ impl<E: Environment> Policy<E> for GreedyPolicy<E> {
impl<E: Environment> Serialize for GreedyPolicy<E> { impl<E: Environment> Serialize for GreedyPolicy<E> {
fn serialize(&self) -> String { fn serialize(&self) -> String {
format!("{};{}", self.gamma, self.learning_rate) format!("{};{}\n", self.gamma, self.learning_rate)
+ self + self
.qtable .qtable
.iter() .iter()
.map(|((state, action), value)| { .map(|((state, action), value)| {
format!("{};{};{}", state.serialize(), action.serialize(), value) format!("{};{};{}\n", state.serialize(), action.serialize(), value)
}) })
.reduce(|a, b| a + b.as_str() + "\n") .reduce(|a, b| a + b.as_str())
.unwrap_or(String::new()) .unwrap_or(String::new())
.as_str() .as_str()
} }
@@ -218,6 +233,22 @@ pub struct EpsilonGreedyPolicy<E: Environment> {
} }
impl<E: Environment> EpsilonGreedyPolicy<E> { impl<E: Environment> EpsilonGreedyPolicy<E> {
pub fn new(
learning_rate: f32,
gamma: f32,
max_epsilon: f32,
min_epsilon: f32,
decay_rate: f32,
) -> Self {
EpsilonGreedyPolicy {
greedy_policy: GreedyPolicy::new(learning_rate, gamma),
min_epsilon,
max_epsilon,
decay_rate,
episode: 0,
}
}
fn epsilon(&self) -> f32 { fn epsilon(&self) -> f32 {
self.min_epsilon self.min_epsilon
+ (self.max_epsilon - self.min_epsilon) * (-self.decay_rate * self.episode as f32).exp() + (self.max_epsilon - self.min_epsilon) * (-self.decay_rate * self.episode as f32).exp()
@@ -240,13 +271,14 @@ impl<E: Environment> Policy<E> for EpsilonGreedyPolicy<E> {
fn improve( fn improve(
&mut self, &mut self,
state: &E::ActionRelevantState, state: E::ActionRelevantState,
action: E::Action, action: E::Action,
reward: f32, reward: f32,
next_state: Option<&E::State>, next_state: E::State,
finished: bool,
) { ) {
self.greedy_policy self.greedy_policy
.improve(state, action, reward, next_state); .improve(state, action, reward, next_state, finished);
} }
fn on_episode_increment(&mut self) { fn on_episode_increment(&mut self) {
@@ -257,7 +289,7 @@ impl<E: Environment> Policy<E> for EpsilonGreedyPolicy<E> {
impl<E: Environment> Serialize for EpsilonGreedyPolicy<E> { impl<E: Environment> Serialize for EpsilonGreedyPolicy<E> {
fn serialize(&self) -> String { fn serialize(&self) -> String {
format!( format!(
"{};{};{};{}", "{};{};{};{}\n",
self.min_epsilon, self.max_epsilon, self.decay_rate, self.episode self.min_epsilon, self.max_epsilon, self.decay_rate, self.episode
) + self.greedy_policy.serialize().as_str() ) + self.greedy_policy.serialize().as_str()
} }