please critique my code :)

For learning rust I decided to hack on a simple roguelike. I'm coming from a mainly Java/C++ and it's my first attempt at doing something in Rust - I feel the code might not be as "rust"-y as it should be.

https://github.com/devilbuddy/rrl

I'd be happy if someone more experienced than me took a look at the code and gave me some feedback on what could be improved :)

Posted Dec 29, 2014, 8:15 PM UTC

36
TopHattedCoder•

Also you do matches on Optionss a lot where you don't do anything if the value is None. Recently a new syntax for this was introduced, you can use it like so:

instead of:

match message {
    Some(message) => {
        world.add_message(message.as_slice());
    },
    None => {}
}

you can use if let syntax:

if let Some(message) = message {
    world.add_message(message.as_slice());
}

this is much shorter and does the same thing

6
TopHattedCoder•

I think the Actions in actor should be combined using an enum and a struct, like so:

pub enum ActionKind {
    Move,
    Bump
}

pub struct Action {
    kind: ActionKind,
    position: Point
}

This uses less code for the same thing

1
TopHattedCoder•

Or, if you're planning on having some actions without points:

pub enum Action {
    Move(Point),
    Bump(Point)
}
1
devilbuddyOP•

Thanks!

My idea was that actions could contain other things than Point. For instance an attack action could contain the weapon used for attacking.

The new let syntax was nice, I was kind of wondering if there was a more compact way to write that.

What I'm wondering myself is if storing the actors as:

Rc<RefCell<Actor>>

is the way to go. I'm exposing this "internal" detail of world to the actor code where I'm doing things like:

let mut position = Point::new(0,0);
{
    let player = actor_ref.borrow();
    position.x = player.get_position().x;
    position.y = player.get_position().y;
}

Also.. those extra curly braces just to let the borrow() go out of scope feels not so clean.

1
aepsil0n•

I also feel like Rc<RefCell<T>> is not really the way to go (I used to do this similarly in some projects but then found a way to get around it by becoming friends with the borrow checker ;) ). I guess it's mostly a C++/Java habit that people carry over, but there ought to be cleaner ways of structuring code.

However, this may be a bit of up-front work to get into. I have no definite answer yet, but am looking for one. I've got some tentative pointers though: If you consider these smart pointers effectively as a message passing mechanism, it may make sense to look at the stdlib's multi-producer, single-consumer communication primitives as an alternative.

Eventually some form of functional reactive programming could help to tackle such issues in the long term. But this is a much more complex issue altogether.

2
devilbuddyOP•

Ok, so I "finished" it :)

screenshot 1

screenshot 2

Not sure if it will receive any updates from now on. It was fun and I learned quite a bit doing it.

1