Context switching

Basically you have one interface/abstract class (let’s call it Context) that has an update method and a render method (plus maybe some other methods).
Then you subclass this interface into different contexts depending on what they are supposed to do (like one context for the main menu, one for the actual in-game and so on).
In your gameloop you hold a reference to the current context (thus you will only run that context’s code).

Is this a good strategy for games? I mean it does make the code a lot cleaner and possibly easier to understand (since if you have a class called MainMenuContext then you’ll know it will be the main menu).

Yes, usually those Contexts are called screens. And you can also have subscreens if you want to render overlays and such. At least that’s how i do and and how i’ve seen a lot of other people do it.

Ah, I knew I was onto something. Thanks :slight_smile:

They are also known as ‘Worlds’ in Greenfoot.

I have been doing it this way for a couple years now, my interface looks like this.


import java.awt.Graphics2D;
import java.awt.event.KeyListener;
import javax.swing.event.MouseInputListener;


public interface GameState extends MouseInputListener, KeyListener {
	public void draw(Graphics2D g);
	public void update(long time);
	public GameState nextState();
}

I have the nextState function so state changes are controlled by the current state with a line in your main game class’s update function like:


currentState = currentState.nextState();

You can use a real state machine with the Fettle API as I do.

You are creating a linked-list of GameStates? Why?

I have a class called GameWorld that acts much like a JPanel.
I add objects of a type that extends GameComponent, which is an abstract class with a draw and update method.
So you have almost the same setup :smiley:

By the way, what is the

long time

parameter in your update method for?

it’s not a linked list . Probably this method is called each tick (from the “Main Context Holder”), and when it returns anything different than null, it’s time to switch the current context to the one that was returned from the method .

delta time, I suppose .

It’s amazing how it looks like my own context switching, which I thought it was very original :stuck_out_tongue:

Whoa alright. I’m quite confused by what you mean by Context Switching here. Could you explain?