Skip to content

Instantly share code, notes, and snippets.

@chanmix51
Created February 13, 2023 12:31
Show Gist options
  • Save chanmix51/88dbb0885c88d51f2c57d6b36d256e28 to your computer and use it in GitHub Desktop.
Save chanmix51/88dbb0885c88d51f2c57d6b36d256e28 to your computer and use it in GitHub Desktop.
ChatGPT generated code for a simple Diplomacy like game
use std::collections::HashMap;
struct Square {
name: String,
pawn: Option<String>,
}
struct GameBoard {
squares: HashMap<String, Square>,
}
impl GameBoard {
fn new() -> Self {
let mut squares = HashMap::new();
// initialize squares with their names
squares.insert("A1".to_string(), Square { name: "A1".to_string(), pawn: None });
squares.insert("A2".to_string(), Square { name: "A2".to_string(), pawn: None });
squares.insert("B1".to_string(), Square { name: "B1".to_string(), pawn: None });
squares.insert("B2".to_string(), Square { name: "B2".to_string(), pawn: None });
GameBoard { squares }
}
fn move_pawn(&mut self, pawn: &str, target: &str) {
let current_square = self.squares.get_mut(pawn).unwrap();
let target_square = self.squares.get_mut(target).unwrap();
if target_square.pawn.is_none() {
target_square.pawn = current_square.pawn.take();
}
}
}
fn main() {
let mut game_board = GameBoard::new();
// place pawns on the board
game_board.squares.get_mut("A1").unwrap().pawn = Some("Pawn 1".to_string());
game_board.squares.get_mut("B2").unwrap().pawn = Some("Pawn 2".to_string());
// move Pawn 1 to B1
game_board.move_pawn("A1", "B1");
// move Pawn 2 to A2, but it fails because Pawn 1 is already on B1
game_board.move_pawn("B2", "A2");
println!("{:?}", game_board.squares);
}
@chanmix51
Copy link
Author

Problem was:

let's say I have a game boards with named squares. A pawn on one square can only move to the adjacent square. Two pawns cannot be on the same square. If two paws decide to go on the same square, they do not move.
Please write a piece of Rust code that handle that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment