Giter Club home page Giter Club logo

yare-rust's Introduction

Yare-Rust

A library for making bots for yare with Rust.

How it works

You make a Rust library and compile to wasm. Then you use the wasm2yareio script to generate a JavaScript yare bot. The result can be copied into the game.

Setup

You will need Rust, and some additional tools.

rustup toolchain add nightly
rustup target add wasm32-unknown-unknown
rustup component add llvm-tools-preview
rustup update

Create a new Rust library.

cargo new --lib my-yare-bot

Put this in your Cargo.toml.

[lib]
crate-type = ["cdylib"]

[dependencies]
yareio = "0.1"

[profile.release]
opt-level = "s"
lto = true

Then copy wasm2yareio.js from the linked submodule into your project and install a dependency. Make sure your Node is up-to-date.

npm i minify

Example

This is an example bot. You need to define an external function called tick that has one parameter. This will be called every tick.

#[no_mangle]
pub extern "C" fn tick(_tick: u32) {
    unsafe {
        let me = player::me();
        let Position {x, y} = base::position(0);
        for index in 0..spirit::count() {
            if spirit::player_id(index) == me && spirit::hp(index) > 0 {
                spirit::goto(index, x, y);
            }
        }
    }
}

You should make safe wrappers for these function so that you don't have to have unsafe blocks in your bot code. For example, you could do something like this:

use std::ffi::CString;
use yareio::spirit;
use yareio::player;

/// Your own Spirit struct with all the information you want.
struct Spirit {
    index: usize,
    alive: bool,
    friendly: bool,
}

impl Spirit {
    /// Safe wrapper for moving a spirit.
    fn goto(&self, x: f32, y: f32) {
        unsafe { spirit::goto(self.index, x, y) }
    }

    /// Safe wrapper for using shout.
    fn shout(&self, string: &str) {
        let c_string = CString::new(string).unwrap();
        unsafe { spirit::shout(self.index, c_string.as_ptr()) }
    }
}

/// Parse all spirits into your own Spirit structs.
fn get_spirits() -> Vec<Spirit> {
    unsafe {
        let me = player::me();
        let count = spirit::count();
        let mut spirits = Vec::with_capacity(count);
        for index in 0..count {
            spirits.push(Spirit {
                index,
                alive: spirit::hp(index) > 0,
                friendly: spirit::player_id(index) == me,
            });
        }
        spirits
    }
}

// No unsafe block needed here!
#[no_mangle]
pub extern "C" fn tick(_tick: u32) {
    let all_spirits = get_spirits();
    for spirit in all_spirits {
        if spirit.friendly && spirit.alive {
            spirit.goto(123., 456.);
            spirit.shout("Hello, world!");
        }
    }
}

Check out this template for an example of how you can structure your code!

Building

To build your yare bot, you first need to compile to wasm. Use this:

cargo rustc --target wasm32-unknown-unknown --release -- -C target-feature=+multivalue

Then you want to pass it through wasm2yareio.

node wasm2yareio target/wasm32-unknown-unknown/release/my-yare-bot.wasm

It is also recommended that you install the tampermonkey script to automatically upload your code to yare.io: Click to install.

Headless

This library comes with a headless implementation of the game by dbenson24. It is not complete, but it is useful for regression tests or possibly machine learning.

To use it, you will need to enable the "headless" feature. You will most likely run want to do this when testing. The command might look like this:

cargo test --features yareio/headless --release

The test should look something like this:

#[cfg(test)]
mod tests {
    use std::rc::Rc;
    use yareio::yare_impl::{Headless, Outcome, SimulationResult, Shape};

    #[test]
    fn win_against_rush() {
        let bots: &[Rc<dyn Fn(u32)>] = &[Rc::new(my_bot_func), Rc::new(rush)];
        let shapes = &[Shape::Circle, Shape::Square];
        let headless = Headless::init(bots, shapes, None);
        let SimulationResult(_tick, outcome) = headless.simulate();
        assert!(matches!(outcome, Outcome::Victory(0)));
    }
}

Make sure your bots are thread-safe if you run multiple tests. If you play against yourself, make sure you do not write to the same mutable statics.

Furthermore, there are undocumented ffi bindings to run the headless simulation from other languages.

yare-rust's People

Contributors

dbenson24 avatar lholten avatar viliamvadocz avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.