-
Notifications
You must be signed in to change notification settings - Fork 1
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
Allow snake to eat #26
Comments
@klappradla @LuisaAPF @ggpasqualino Hey 👋 Do you remember that we removed the
Then the snake eats the food, therefore it needs to grow by 1 unit. The defp move_snake(%{snake: snake} = state) do
%{body: body, size: size, direction: direction} = snake
# new head
[head | _] = body
new_head = move(state, head, direction)
# truncate body
new_body = Enum.take([new_head | body], size) # Compute snake body
state
|> put_in([:objects, :snake, :body], new_body) # First, update the state
|> maybe_eat_pellet(new_head) # Then, check if the snake ate the food
end
def maybe_eat_pellet(state = %{pellet: pellet}, snake_head) when pellet == snake_head do
state
|> grow_snake()
end
def grow_snake(state = %{snake: %{size: size}}) do
put_in(state, [:snake, :size], size + 1)
end 👆 the new_body = Enum.take([new_head | body], size) Basically, the size info is needed only to allow the snake to grow when it eats the food and it is evaluated always the following state update. OK.
What do you think? Do you have any idea? Let's also keep in mind this info:
|
Good catch @nickgnd! I like your suggestion to have a state defp move_snake(%{snake: snake} = state) do
%{body: body, direction: direction} = snake
# new head's position
[head | _] = body
new_head = move(state, head, direction)
# place a new head on the tile that we want to move to
# and remove the last tile from the snake tail if it has not eaten any pallet
new_body = [new_head | body]
new_body = if snake.has_eaten, do: new_body, else: List.delete_at(new_body, -1)
state
|> put_in([:snake, :body], new_body)
end |
@nickgnd I also like your suggestion of adding a |
Perfect! Thanks for the feedback 🤗 |
Wow, definitely a good catch 👍 I also like @ggpasqualino's approach - a bit more explicit than using the |
I think it depends whether we update the snake's size immediately or in the next tick, if we do it in the same tick then we don't need to store the state. |
Yep, talked about it today with @nickgnd. With the current approach it's probably most "natural" to have the snake "grow" on the second tick - so storing in the state is perfect 👌 |
Draft out chapter 6: Allow snake to eat 🐛 🍎
The text was updated successfully, but these errors were encountered: