I want to implement a game loop (that is acting as a server) in Erlang, but I dont know how to deal with the lack of incrementing variables.
What I want to do, described in Java code:
class Game {
int posX, posY;
int wall = 10;
int roof = 20;
public void newPos(x,y) {
if(!collision(x,y)) {
posX = x;
posY = y;
}
}
public boolean collision(x,y) {
if(x == wall || y == roof) {
// The player hit the wall.
return true;
}
return false;
}
public sendStateToClient() {
// Send posX and posY back to client
}
public static void main(String[] args) {
// The game loop
while(true) {
// Send current state to the client
sendStateToClient();
// Some delay here...
}
}
}
If the client moves, then the newPos() function is called. This function changes some coordinate variables if a collision do not occur. The game loop is going on forever and is just sending the current state back to the client so that the client can paint it.
Now I want to implement this logic in Erlang but I dont know where to begin. I can't set the variables posX and posY in the same way as here... My only thaught is some kind of recursive loop where the coordinates is arguments, but I don't know if that is the right way to go either...
Your intuition is correct: a recursive loop with the state as a parameter is the standard Erlang approach.
This concept is often abstracted away by using one of the server behaviors in OTP.
Simple example, may contain errors:
game_loop(X, Y) ->
receive
{moveto, {NewX, NewY}} ->
notifyClient(NewX, NewY),
game_loop(NewX, NewY)
end.