Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it okay to put game logic in a draw function?

I am making a game, and I have finally finished the gameplay aspect of it, but now it's time for me to create a menu and a high scores screen. I'm not entirely sure how to do it, the game will be in a different state (MENU_STATE, GAMEPLAY_STATE, SCORESCREEN_STATE) and in each state I want to draw different things to the screen, is it okay for me to do something like this then?

draw function()
{
    if MENU_STATE
        draw menu
    if GAMEPLAY_STATE
        draw game
    if SCORESCREEN_STATE
        draw scores
}

I've been following a strictly no logic in the draw function and it's been good so far, but I really can't figure out a different way to do this.

like image 710
Joe Avatar asked Dec 29 '22 02:12

Joe


1 Answers

You could use separate classes for the three states, implementing a common interface, and rather than setting a constant for state, set an instance of one of the classes:

interface IState {
    void draw();
}

class Menu implements IState {
    void draw() {
        // Draw menu
    }
}

class Game implements IState {
    void draw() {
        // Draw game
    }
}

void draw() {
    state.draw();
}

This still isn't ideal (you don't really want drawing code in your state, you want something a bit more separate), but the abstraction is a common one and could be relevant (and it's hard to advise further without knowing more of your architecture).

like image 125
Andrew Aylett Avatar answered Mar 03 '23 16:03

Andrew Aylett