TGC Codebase Backup



Basic GameState Template by Marl

13th Jun 2012 20:52
Summary

A template demonstrating the use of a game state global variable in a structured way, keeping the main loop small and allowing the project to easily be broken down into a series of



Description

Using a game state global variable within a single loop, this code demonstrates accessing UDT fields by function to keep code tidy.

The main loop contains a select structure which uses different code blocks depending on the game state variable. Normally, each case would contain a call to routines held in include files, keeping the main loop to a minimum and creating a base for a modular project.



Code
                                    ` This code was downloaded from The Game Creators
                                    ` It is reproduced here with full permission
                                    ` http://www.thegamecreators.com
                                    
                                    // Generic Game State Template

// Constants - Game State

#constant STATE_INIT	0
#constant STATE_MENU	1
#constant STATE_GAME	2
#constant STATE_EXIT	999

// Constants - Key Codes

#constant RAWKEY_ESC	27

// One Time Initialisation
Main_Init()

// Main Loop
do
	Main_LoopStart()
	select GameState()
		case STATE_INIT
			// Startup and Initialisation Code Goes here
			
			// Sample Basic Screen Setup 
			setVirtualResolution(getDeviceWidth(),getDeviceHeight())
			setPrintSize( getDeviceHeight() / 20.0 )

			// Change game state to menu
			SetGameState( STATE_MENU )
		endcase
		case STATE_MENU
			// Menu Code Goes here

		endcase
		case STATE_GAME
			// Main Game Code Goes Here

		endcase
		case STATE_EXIT
			// Cleanup and Exit Code Goes here

			exit
		endcase
	endselect
	Main_LoopEnd()
loop
end

// UDT Definitions

type GameType
	state
endtype

// Functions

function Main_LoopStart()
	// Code to run at start of every loop

	// Check for Escape (back) key indicating exit
	if GetRawKeyState( RAWKEY_ESC ) = 1 then SetGameState( STATE_EXIT )
endfunction

function Main_LoopEnd()
	// Code to run at end of every loop

	// Update Screen
	sync()
endfunction

function Main_Init()
	// Initialise Game Global
	global Game as GameType
	SetGameState( STATE_INIT )
endfunction

// UDT Access Functions

function GameState()
endfunction game.state
function SetGameState( thisInt )
	game.state = thisInt
endfunction