jrhenderson1988 / snake-rs

MIT License
29 stars 1 forks source link

[feature] [question] fast forwarding the snake #1

Open borowyalan opened 3 years ago

borowyalan commented 3 years ago

Hi! Thanks for the blog post.

I was wandering whether changing in the game.rs

Command::Turn(towards) => {
    if direction != towards && direction.opposite() != towards {
        self.snake.set_direction(towards);
    }
}

to:

Command::Turn(towards) => {
    if direction == towards {
        break;
    } else if direction.opposite() != towards {
        self.snake.set_direction(towards);
    }
}

is the proper way to do add a feature of fast forwarding the snake? Is there any other, maybe more idiomatic way to achieve this that you can think of? ^^

jrhenderson1988 commented 3 years ago

Hey! You are very welcome.

Your suggestion does indeed look like a good way to implement a fast-forward function, by pressing in the direction that the snake is facing.

By breaking from the inner loop we're effectively jumping to the next iteration of the outer loop and breaking from the timer that is used to regulate the time in between each snake move, so it does have the effect of pushing the snake onwards each time you press. One thing I did notice when trying locally is that holding the key down registers a lot of keypresses and results in the snake moving super quickly, so that is probably not intended.

It's been so long since I looked at the code for this that I couldn't suggest a better way off the top of my head. I think implementing a fast-forward feature so that it works a bit more reliably, would probably entail re-working the primary game loop in a way that accounts for repeated keypresses.

In all honesty, I'm not much of a Rust expert and building this game was an exercise in brushing up on the little knowledge I had as well as for a blog post to help others. I'm probably not qualified enough to talk about idiomatic Rust.

Thanks again for your feedback - it is much appreciated :)

teamrocket77 commented 2 years ago

Howdy, so I know it's been ages I implemented the FForwarding. I just did it by making two new keys up and down and using those to adjust the snake internal speed for example

KeyCode::Char('d') => Some(Command::Adjust(Speed::Down)),

// Many lines away...

Command::Adjust(towards) => {
    if Speed::Down == towards && self.speed != 0{
        self.speed -= 1;
    }