Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement various methods. #38

Merged
merged 28 commits into from
Sep 20, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
d8f45c6
Implement various methods.
ASalvail Sep 10, 2018
a76d1ac
Market complex methods
ASalvail Sep 15, 2018
4664e3e
Flaggy Flag!
ASalvail Sep 16, 2018
3069b27
Mineral + ResourceType conversion to string
ASalvail Sep 16, 2018
34964e2
Nukes to ruin your day
ASalvail Sep 16, 2018
79ca6a7
Add some methods to Room
ASalvail Sep 16, 2018
f4d650f
Add a method for RoomPosition
ASalvail Sep 16, 2018
7d284b5
Add a CanStoreEnergy trait
ASalvail Sep 16, 2018
b3d642e
Add a HasCooldown trait
ASalvail Sep 16, 2018
b32bfa9
Add method to KeeperLair in mod.rs
ASalvail Sep 16, 2018
bfb79c6
Add StructureLab module and conversion from string to Resource type
ASalvail Sep 16, 2018
4308afa
Add structure_link module and implement method
ASalvail Sep 16, 2018
2d0735d
Add structure_nuker mod + implement methods
ASalvail Sep 16, 2018
3869700
Add structure_observer mod
ASalvail Sep 16, 2018
fc74433
Add trait CanDecay
ASalvail Sep 16, 2018
5661dbc
Add PowerBank accessor to mod.rs
ASalvail Sep 16, 2018
c8e84ed
Add structure_power_spawn module
ASalvail Sep 16, 2018
f350548
Add structure_portal module
ASalvail Sep 16, 2018
8c36aa6
Add structure_rampart module
ASalvail Sep 16, 2018
756a96f
Add structure_terminal module
ASalvail Sep 16, 2018
ca8a521
Add structure_tower module
ASalvail Sep 16, 2018
0dde821
Import all changes into impls module
ASalvail Sep 16, 2018
d7514e2
Add new trait to prelude
ASalvail Sep 16, 2018
82f81a2
Moved hits and hitsMax to the Attackable trait
ASalvail Sep 16, 2018
75418e3
Addressed small changes from @daboross review.
ASalvail Sep 18, 2018
4420339
Transfers string conversion to JS side for ResourceType
ASalvail Sep 20, 2018
402c5fd
Converts OrderType to a number repr for quick transfer
ASalvail Sep 20, 2018
d5c1a05
Removed Attackable trait from StructureController
ASalvail Sep 20, 2018
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions screeps-game-api/javascript/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -212,3 +212,19 @@ function _hasActiveBodypart(body, type) {
}
return false;
}

function __order_type_str_to_num(str) {
switch (str) {
case ORDER_SELL: return 0;
case ORDER_BUY: return 1;
default: throw new Error("unknown order type " + str);
}
}

function __order_type_num_to_str(num) {
switch (num) {
case 0: return ORDER_SELL;
case 1: return ORDER_BUY;
default: throw new Error("unknown order type " + num);
}
}
70 changes: 58 additions & 12 deletions screeps-game-api/src/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,16 @@ impl TryFrom<Value> for ReturnCode {
}
}

impl TryFrom<i32> for ReturnCode {
type Error = i32;
fn try_from(v: i32) -> Result<Self, Self::Error> {
use num_traits::FromPrimitive;
Self::from_i32(v).ok_or(v)
}
}

pub unsafe trait FindConstant {
type Item: TryFrom<Value, Error = <Reference as TryFrom<Value>>::Error> + AsRef<Reference>;
type Item: TryFrom<Value, Error = ConversionError> + AsRef<Reference>;

fn find_code(&self) -> i32;
}
Expand Down Expand Up @@ -182,7 +190,7 @@ enum_from_primitive! {
}

impl TryFrom<Value> for Direction {
type Error = <u32 as TryFrom<Value>>::Error;
type Error = ConversionError;

fn try_from(v: Value) -> Result<Self, Self::Error> {
use num_traits::FromPrimitive;
Expand Down Expand Up @@ -212,6 +220,26 @@ enum_from_primitive! {
}
}

impl From<Color> for i32 {
fn from(c: Color) -> i32 {
c as i32
}
}

impl TryFrom<Value> for Color {
type Error = ConversionError;

fn try_from(v: Value) -> Result<Self, Self::Error> {
use num_traits::FromPrimitive;

let as_num = i32::try_from(v)?;

Ok(Self::from_i32(as_num).unwrap_or_else(|| {
panic!("encountered a color code we don't know: {}", as_num);
}))
}
}

#[repr(u32)]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum Terrain {
Expand All @@ -221,7 +249,7 @@ pub enum Terrain {
}

impl TryFrom<Value> for Terrain {
type Error = <u32 as TryFrom<Value>>::Error;
type Error = ConversionError;

fn try_from(v: Value) -> Result<Self, Self::Error> {
let v = match v {
Expand Down Expand Up @@ -356,7 +384,7 @@ impl TryFrom<u32> for Part {
}

impl TryFrom<Value> for Part {
type Error = <Value as TryInto<u32>>::Error;
type Error = ConversionError;
fn try_from(v: Value) -> Result<Self, Self::Error> {
let x: u32 = v.try_into()?;
Ok(Self::try_from(x)
Expand Down Expand Up @@ -516,7 +544,7 @@ impl StructureType {
}

impl TryFrom<Value> for StructureType {
type Error = <i32 as TryFrom<Value>>::Error;
type Error = ConversionError;

fn try_from(v: Value) -> Result<Self, Self::Error> {
let x: i32 = v.try_into()?;
Expand Down Expand Up @@ -612,10 +640,30 @@ pub const MINERAL_REGEN_TIME: u32 = 50_000;

// TODO: MINERAL_* constants

pub const DENSITY_LOW: i32 = 1;
pub const DENSITY_MODERATE: i32 = 2;
pub const DENSITY_HIGH: i32 = 3;
pub const DENSITY_ULTRA: i32 = 4;
enum_from_primitive! {
#[repr(i32)]
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum Density {
DensityLow = 1,
DensityModerate = 2,
DensityHigh = 3,
DensityUltra = 4,
}
}

impl TryFrom<Value> for Density {
type Error = ConversionError;

fn try_from(v: Value) -> Result<Self, Self::Error> {
use num_traits::FromPrimitive;

let as_num = i32::try_from(v)?;

Ok(Self::from_i32(as_num).unwrap_or_else(|| {
panic!("encountered a color code we don't know: {}", as_num);
}))
}
}

pub const TERMINAL_CAPACITY: i32 = 300000;
pub const TERMINAL_HITS: i32 = 3000;
Expand Down Expand Up @@ -663,14 +711,12 @@ pub enum ResourceType {
Catalyst = 9,
/// `"G"`
Ghodium = 10,

/// `"OH"`
Hydroxide = 11,
/// `"ZK"`
ZynthiumKeanite = 12,
/// `"UL"`
UtriumLemergite = 13,

/// `"UH"`
UtriumHydride = 14,
/// `"UO"`
Expand Down Expand Up @@ -778,7 +824,7 @@ impl ResourceType {
}

impl TryFrom<Value> for ResourceType {
type Error = <i32 as TryFrom<Value>>::Error;
type Error = ConversionError;

fn try_from(v: Value) -> Result<Self, Self::Error> {
let x: i32 = v.try_into()?;
Expand Down
182 changes: 181 additions & 1 deletion screeps-game-api/src/game.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,8 +122,10 @@ pub mod gcl {
/// [http://docs.screeps.com/api/#Game.map]: http://docs.screeps.com/api/#Game.map
pub mod map {
use std::collections;
use stdweb::unstable::{TryInto, TryFrom};

use {Direction, RoomPosition, Terrain};
use {Direction, RoomPosition, Terrain, Room};
use constants::{ReturnCode, find::Exit};

/// See [http://docs.screeps.com/api/#Game.map.describeExits]
///
Expand Down Expand Up @@ -174,8 +176,182 @@ pub mod map {
pub fn is_room_available(room_name: &str) -> bool {
js_unwrap!(Game.map.isRoomAvailable(@{room_name}))
}

/// Implements `Game.map.findExit`.
///
/// Does not yet support callbacks.
pub fn find_exit(from_room: Room, to_room: Room) -> Result<Exit, ReturnCode> {
let code: i32 = js_unwrap!{Game.map.findExit(@{from_room.name()}, @{to_room.name()})};
Exit::try_from(code).map_err(|v| v.try_into().expect("find_exit: Error code not recognized."))
}

// pub fn find_route(from_room: Room, to_room: Room, route_callback: Option<impl Fn(&str, &str) -> u32>) -> !{
// unimplemented!()
// }
}

pub mod market {
use std::collections::HashMap;

use stdweb::unstable::TryInto;

use {Room};
use constants::{ReturnCode, ResourceType};

#[repr(u32)]
#[derive(Clone, Debug)]
pub enum OrderType {
Sell = 0,
Buy = 1
}

// impl OrderType {
// fn as_string(&self) -> String {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you do want to keep this method in, I don't think it would hurt.

If we want to add in a typed OrderType to the transactions, the serde translation code would have to use strings anyways since stdweb turns it into JSON before loading it in.

// match self {
// OrderType::Sell => String::from("sell"),
// OrderType::Buy => String::from("buy")
// }
// }
// }

#[derive(Deserialize, Debug)]
pub struct Player {
username: String,
}
js_deserializable!(Player);

#[derive(Deserialize, Debug)]
pub struct TransactionOrder {
id: String,
#[serde(rename="type")]
order_type: String,
price: f64
}
js_deserializable!(TransactionOrder);

#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Transaction {
transaction_id: String,
time: u32,
sender: Player,
recipient: Player,
resource_type : String,
amount: u32,
from: String,
to: String,
description: String,
order: Option<TransactionOrder>,
}
js_deserializable!(Transaction);

#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Order {
id: String,
created: u32,
#[serde(rename = "type")]
order_type: String,
resource_type: String,
room_name: String,
amount: u32,
remaining_amount: u32,
price: f64
}
js_deserializable!(Order);

#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct MyOrder {
id: String,
created: u32,
active: bool,
#[serde(rename = "type")]
order_type: String,
resource_type: String,
room_name: String,
amount: u32,
remaining_amount: u32,
total_amount: u32,
price: f64
}
js_deserializable!(MyOrder);

pub fn credits() -> u32 {
js_unwrap!(Game.market.credits)
}

pub fn incoming_transactions() -> Vec<Transaction>{
let arr_transaction_value = js!{
return Game.market.incomingTransactions;
};
arr_transaction_value.try_into().unwrap()
}

pub fn outgoing_transactions() -> Vec<Transaction>{
let arr_transaction_value = js!{
return Game.market.outgoingTransactions;
};
arr_transaction_value.try_into().unwrap()
}

pub fn orders() -> HashMap<String, MyOrder> {
let order_book_value = js! {
return Game.market.orders;
};
order_book_value.try_into().unwrap()
}

pub fn calc_transaction_cost(amount: u32, room1: &Room, room2: &Room) -> u32 {
js_unwrap!(Game.market.calcTransactionCost(@{amount}, @{room1.name()}, @{room2.name()}))
}

pub fn cancel_order(order_id: &str) -> ReturnCode {
js_unwrap!(Game.market.cancelOrder(@{order_id}))
}

pub fn change_order_price(order_id: &str, new_price: u32) -> ReturnCode {
js_unwrap!(Game.market.changeOrderPrice(@{order_id}, @{new_price}))
}

pub fn create_order(order_type: OrderType, resource_type: ResourceType,
price: f64, total_amount: u32, room: &Room) -> ReturnCode {
js_unwrap!{
Game.market.createOrder(__order_type_num_to_str(@{order_type as u32}),
__resource_type_num_to_str(@{resource_type as u32}),
@{price},
@{total_amount},
@{room.name()})
}
}

pub fn deal(order_id: &str, amount: u32, target_room: &Room) -> ReturnCode {
js_unwrap!{Game.market.deal(@{order_id}, @{amount}, @{target_room.name()})}
}

pub fn extend_order(order_id: &str, add_amount: u32) -> ReturnCode {
js_unwrap!{Game.market.extendOrder(@{order_id}, @{add_amount})}
}

/// Get all orders from the market
///
/// Contrary to the JS version, filtering should be done afterwards.
pub fn get_all_orders() -> Vec<Order> {
let all_order = js! {
return Game.market.getAllOrders();
};
all_order.try_into().unwrap()
}

pub fn get_order(id: &str) -> Option<Order> {
let order = js! {
return Game.marget.getOrder(@{id});
};
order.try_into().ok()
}
}


/// See [http://docs.screeps.com/api/#Game.shard]
///
/// [http://docs.screeps.com/api/#Game.shard]: http://docs.screeps.com/api/#Game.shard
Expand Down Expand Up @@ -245,3 +421,7 @@ pub fn time() -> u32 {
pub fn get_object(id: &str) -> Option<::objects::RoomObject> {
js_unwrap!(Game.getObjectById(@{id}))
}

pub fn notify(message: &str, group_interval: Option<u32>) {
js!{Game.notify(@{message}, @{group_interval.unwrap_or(0)})};
}
9 changes: 8 additions & 1 deletion screeps-game-api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,13 @@ pub(crate) use stdweb::private::ConversionError;
/// structures in order to minimize namespace polution.
pub mod prelude {
pub use objects::{
HasPosition, HasStore, OwnedStructureProperties, RoomObjectProperties, StructureProperties,
HasPosition,
HasStore,
CanStoreEnergy,
HasCooldown,
CanDecay,
OwnedStructureProperties,
RoomObjectProperties,
StructureProperties,
};
}
2 changes: 1 addition & 1 deletion screeps-game-api/src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@
/// (If unavailable: https://docs.rs/stdweb/0.4.8/stdweb/unstable/trait.TryFrom.html )
macro_rules! js_unwrap {
($($code:tt)*) => (
::stdweb::unstable::TryInto::try_into(js! { return $($code)* })
::stdweb::unstable::TryInto::try_into(js! { return $($code)*; })
.expect(concat!("js_unwrap at ", line!(), " in ", file!()))
)
}
Expand Down
Loading