You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
rulebot/src/main.rs

91 lines
2.1 KiB
Rust

2 years ago
use std::{fmt::Display, ops::Index};
2 years ago
use rand::Rng;
2 years ago
#[derive(Debug, Clone, Copy)]
struct State([bool; 8]);
impl Index<usize> for State {
type Output = bool;
fn index(&self, index: usize) -> &Self::Output {
&self.0[index]
}
}
2 years ago
fn map_state(rule: u8, state: &State) -> State {
let mut new_state: [bool; 8] = [false; 8];
for i in 0..8 {
let pattern = ((i != 0 && state[i - 1]) as u8 * 4)
| (state[i] as u8 * 2)
| ((i != 7 && state[i + 1]) as u8);
new_state[i] = (rule >> pattern & 1) == 1;
}
2 years ago
State(new_state)
2 years ago
}
2 years ago
impl Display for State {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
self.0.map(|c| if c { "⬛" } else { "⬜" }).concat()
)
}
2 years ago
}
2 years ago
impl Into<State> for u8 {
fn into(self) -> State {
let mut state = [false; 8];
2 years ago
2 years ago
for i in 0..8 {
state[i] = (self >> i & 1) == 1;
}
2 years ago
2 years ago
State(state)
}
2 years ago
}
fn main() {
let mut rng = rand::thread_rng();
let seed: u16 = rng.gen();
let rule: u8 = (seed & 0xff) as u8;
2 years ago
let init_state = ((seed >> 8 & 0xff) as u8).into();
2 years ago
let states: String = (0..8)
.scan(init_state, |state, _i| {
let old_state = *state;
*state = map_state(rule, state);
Some(old_state)
})
2 years ago
.map(|state| state.to_string())
2 years ago
.collect::<Vec<String>>()
.join("\n");
println!("Rule: {}\n{}", rule, states);
let client = reqwest::blocking::Client::new();
let res = client
.post("https://mastodon.raptorpond.com/api/v1/statuses")
.header(
"Authorization",
format!("Bearer {}", std::env::var("MASTODON_TOKEN").unwrap()),
)
.form(&[
("status", format!("Rule: {}\n{}", rule, states)),
("visibility", String::from("private")),
])
.send();
match res {
Ok(_) => std::process::exit(exitcode::OK),
Err(error) => {
println!("{:?}", error);
std::process::exit(exitcode::IOERR);
}
}
}