如何在Erlang中实现"游戏循环"?

the*_*eva 2 erlang game-loop

我想在Erlang中实现一个游戏循环(它充当服务器),但我不知道如何处理缺少增量变量.

我想做什么,在Java代码中描述:

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...
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果客户端移动,则调用newPos()函数.如果不发生碰撞,此函数会更改某些坐标变量.游戏循环正在进行中,只是将当前状态发送回客户端,以便客户端可以绘制它.

现在我想在Erlang中实现这个逻辑,但我不知道从哪里开始.我不能以与此处相同的方式设置变量posX和posY ...我唯一可能的是某种递归循环,其中坐标是参数,但我不知道这是否是正确的方法. ..

mac*_*tux 5

你的直觉是正确的:以状态作为参数的递归循环是标准的Erlang方法.

通常使用OTP中的一个服务器行为来抽象出这个概念.

简单的例子,可能包含错误:

game_loop(X, Y) ->
    receive
        {moveto, {NewX, NewY}} ->
            notifyClient(NewX, NewY),
            game_loop(NewX, NewY)
    end.
Run Code Online (Sandbox Code Playgroud)