Welcome, Guest. Please login or register.
Did you miss your activation email?

Login with username, password and session length

 
Advanced search

891513 Posts in 33545 Topics- by 24780 Members - Latest Member: Xander Davis

June 19, 2013, 09:57:31 PM
TIGSource ForumsDeveloperTechnical (Moderators: Glaiel-Gamer, ThemsAllTook)Post your game loop
Pages: 1 2 [3] 4
Print
Author Topic: Post your game loop  (Read 2298 times)
ChevyRay
Level 1
*



View Profile WWW Email
« Reply #30 on: June 12, 2012, 09:08:54 PM »

Hah, had this exact thread years ago. Glad a new one popped up, these are fun to look through.

Since I build game engines and then build my games from those, mine are quite generic (nothing cool like frog->update() or whatever) but I'll post anyways.

FlashPunk's update/render loop (AS3)

Code:
public function update():void
{
if (FP.tweener.active && FP.tweener._tween)
FP.tweener.updateTweens();

if (FP._world.active)
{
if (FP._world._tween)
FP._world.updateTweens();

FP._world.update();
}

FP._world.updateLists();
if (FP._goto)
checkWorld();
}

public function render():void
{
var t:Number = getTimer();

if (!_frameLast)
_frameLast = t;

FP.screen.swap();
Draw.resetTarget();
FP.screen.refresh();

if (FP._world.visible)
FP._world.render();

FP.screen.redraw();

t = getTimer();
_frameListSum += (_frameList[_frameList.length] = t - _frameLast);

if (_frameList.length > 10)
_frameListSum -= _frameList.shift();

FP.frameRate = 1000 / (_frameListSum / _frameList.length);
_frameLast = t;
}

And here's my C# engine's game loop:

Code:
protected override void Update(GameTime gameTime)
{
    Input.Update();

    if (Input.Pressed(Keys.Escape))
        Exit();

    if (currentScene != null && currentScene.Active)
        currentScene.Update();

    if (currentScene != targetScene)
    {
        if (currentScene != null)
            currentScene.End();
        currentScene = targetScene;
        if (currentScene != null)
            currentScene.Start(this);
    }

    base.Update(gameTime);
}

protected override void Draw(GameTime gameTime)
{

    if (currentScene != null && currentScene.Visible)
        currentScene.RenderToScreen();

    Screen.Render();

    base.Draw(gameTime);
}
Logged

Eigen
Level 8
***


Jebus backups.


View Profile WWW
« Reply #31 on: June 12, 2012, 09:49:23 PM »

Mine's a bit ugly and not as compact as it should be, but still better than my last game where I had everything in the main loop, including the whole game logic.

Code:
void Game::run()
{
  while (renderWindow->isOpen())
  {
      // Very generic
      sf::Time frameTime_ = Clock.getElapsedTime();
      frameTime = frameTime_.asMilliseconds() / 1000.f;
      Clock.restart();

      // In older versions of SFML I sometimes got a GainedFocus event
      // followed immediately by LostFocus event so it stayed unfocused
      // even though the window was actually focused. So I hacked around that
      // with a timer for those events. Not sure if needed in the current
      // version.
      if (windowFocusLost)
        lostFocusTimer += frameTime;

      // Process events
      sf::Event Event;

      // Gimme something!
      while (renderWindow->pollEvent(Event))
      {
        // Give other dingies a chance to handle events with which
        // the GUI had nothing to do.
        if (primaryEventReceiver->handleEvent(Event) == false)
        {
          // Secondary event receiver is either the game logic
          // or the main menu object, depending on the game state.
          secondaryEventReceiver->handleEvent(Event);
        }

        // Handle window focus
        if (Event.type == sf::Event::LostFocus &&
            !windowFocusLost)
        {
          windowFocusLost = true;
          lostFocusTimer = 0.0f;
        }
        else
        if (Event.type == sf::Event::GainedFocus &&
            windowFocusLost &&
            lostFocusTimer > 0.075f)
        {
          windowFocusLost = false;
        }
        // Close window .. exit the game
        else if (Event.type == sf::Event::Closed)
        {
          // This breaks the main loop so I can do closing stuff when closing
          renderWindow->close();
        }
      }

      // Clear the screen
      renderWindow->clear(spriteManager->getPalette(0)->colors[3]);

      // Super system (c)
      switch (state)
      {
        case STATE_IN_GAME:
        {
          if (!windowFocusLost)
          {
            // This is where the magic happens ...
            gameLogic->update();

            // ... not so much here
            viewport->update( frameTime );

            // Create/destroy/update particles
            particleManager->update( frameTime );

            // Register particle emitters to map drawing
            particleManager->registerEmittersToMap( mapObject );
          }

          // Render the map and all the visible objects
          mapObject->draw();

          // This does nothing yet, but I might need it later
          gameLogic->updateLate();

          break;
        }

        case STATE_MAIN_MENU:
        {
          // The draw and update methods do nothing yet, but I will need them
          // later when I do the whole main menu art and animation stuff. This
          // will all be in the background, so the GUI stuff will be drawn over it.
          if (!windowFocusLost)
          {
            mainMenu->update();
          }

          mainMenu->draw();

          break;
        }

        // Should not happen but Justin Case
        default:
          printf("Unknown state: %d\n", state);
          break;
      }

      // Updates and draws all of the GUI widgets. They've already received their
      // events so they now what to do.
      guiObject->updateAndDraw( state );

      // Display window contents on screen
      renderWindow->display();

      // Let the CPU catch some breath
      if (windowFocusLost) {
        sf::sleep(sf::milliseconds(30));
      }
  }

  std::string configFilePath = getPlatformSpecificResourcePath() + "data/conf.dat";
  configurationStorage->writeConfigFile( configFilePath.c_str() );
}
Logged

BlueSweatshirt
Level 10
*****


the void


View Profile WWW
« Reply #32 on: June 12, 2012, 09:49:45 PM »

@Chevy

Ooooh. Is there any out-standing reason you chose to have Esc be an engine level killswitch for the entire game? That seems like it could be rather problematic if pressed accidentally or whatnot.
Logged

richy486
Level 0
**



View Profile WWW
« Reply #33 on: June 12, 2012, 09:58:18 PM »

from my simple space invader clone http://github.com/richy486/InvaderR

Code:
void Game::Update()
{
double currTime, frameRateDelta;

currTime = DoublePrecisionSeconds();


// calculate frame rate (optional, added for fun)
gFrameCount++;
frameRateDelta = currTime - gLastFPSUpdate;
if (frameRateDelta > 0.5)
{
gFPS = gFrameCount / frameRateDelta;
gFrameCount = 0;
gLastFPSUpdate = currTime;
//Log(@"fps: %0.1f", gFPS);
#ifdef SHOW_FPS_ONSCREEN
m_fps->SetText("%0.1f", gFPS);
#endif
}

// update the game world at a constant tick rate
m_seconds = currTime - gPrevFrameTime;
gPrevFrameTime = currTime;

if (!m_pause)
{
// ----- update here ------
m_states.top()->Update(m_seconds);

if (m_states.top()->IsEnded())
{
State* popedState = m_states.top();
m_states.pop();
delete popedState;
}
}
else
{
if (Game::GetInstance()->GetLastInputState().m_pressed)
{
Pause(false);
}
}


// ------------------------

if (m_seconds < 0.01f)
{
Log(@" delta: %f", m_seconds);
}

// reset input at end of update
m_input.m_moveX = 0.0f;
m_input.m_pressed = false;
m_input.m_released = false;
}

and the StateGame update

Code:
void StateGame::Update(float seconds)
{
float moveX = Game::GetInstance()->GetLastInputState().m_moveX;
//Log(@"moveX: %f", moveX);
Player::getInstance()->update(seconds, moveX);

bool gameOver = false;
INVADERS_STATE::INVADERS_STATE invaderState = INVADERS_STATE::COUNT; // default
if (InvaderSet::getInstance()->getPlaying())
{
m_shooter->update(seconds);
Bomber::getInstance()->update(seconds);

invaderState = InvaderSet::getInstance()->Update(seconds);
if (invaderState == INVADERS_STATE::LOSE)
{
gameOver = true;
}
else if (invaderState == INVADERS_STATE::INTRO)
{
m_shooter->killAll();
Bomber::getInstance()->killAll();
}

}
else
{
// lose
gameOver = true;
}

// shooting, after invader update to get invaderState
if (Game::GetInstance()->GetLastInputState().m_pressed)
{
if (invaderState == INVADERS_STATE::PLAYING)
{
if (!g_PressedShoot)
{
g_PressedShoot = true;

Point2D pos = Player::getInstance()->getPos();
pos.x += (2.5f * IPS) - 1.5f;
pos.y += (5.0f * IPS);

m_shooter->fire(pos);
}
}
}
if (Game::GetInstance()->GetLastInputState().m_released)
{
g_PressedShoot = false;
}

Score::GetInstance()->Update(seconds);
int level = Game::GetInstance()->GetLevelCount();
m_scoreText->SetText([UTextConverter ConvertUText:[NSString stringWithFormat: @"%d | %d", level, Score::GetInstance()->GetVisualScore()]]);

if (gameOver)
{
BaseSet::getInstance()->makeBases();
InvaderSet::getInstance()->setPlaying(true);
InvaderSet::getInstance()->restart();
Player::getInstance()->start();

m_shooter->killAll();
Bomber::getInstance()->killAll();

StateLose* stateLose = new StateLose();
stateLose->Init();
Game::GetInstance()->PushState(stateLose);
}
}
Logged

Moczan
Level 5
*****



View Profile
« Reply #34 on: June 12, 2012, 10:44:08 PM »

@Chevy

Ooooh. Is there any out-standing reason you chose to have Esc be an engine level killswitch for the entire game? That seems like it could be rather problematic if pressed accidentally or whatnot.

I think it's a default behaviour in XNA (or it defaults to XBox gamepad's key), it's the same loop as mine, I guess nobody would ship a game with such functionality.
Logged
nospoon
Level 1
*


View Profile Email
« Reply #35 on: June 13, 2012, 12:35:15 AM »

Was still learning AS3 atm.
Code:
if (focus == 0) {
level.update(TIME_MODIFIER);
particleSystem.update(TIME_MODIFIER*ANOTHER_TIME_MODIFIER);
bulletManager.update(TIME_MODIFIER * ANOTHER_TIME_MODIFIER);
entityManager.update(TIME_MODIFIER*ANOTHER_TIME_MODIFIER);
playerController.update();
if (playerController.isPlayerDead())
{
//playerController.destroy();
FlashConnect.trace("Player died showing YouDiedScreen");
ANOTHER_TIME_MODIFIER = .1;
addChild(new YouDiedView(main,restartLevel,levelSelectView,mainMenu));
//restartLevel();
focus = 1;
}else if (entityManager.onlyTeam0Alive)
{
if (!level.spawnWave())
{
//level end

FlashConnect.atrace("WIN showing YouWonView");
ANOTHER_TIME_MODIFIER = .1;
addChild(new YouWonView(main,nextLevel,levelSelectView,mainMenu));
focus = 1;
}else
{
levelName = new LevelNameInfoScroller(this,level.getName());
}
}
} else return;

Logged
Xecutor
Level 1
*


View Profile Email
« Reply #36 on: June 13, 2012, 04:53:56 AM »

Here is loop I used in allegro-based game.
Code:
class LoopBase{
public:
  LoopBase():needExit(false)
  {
  }
  virtual ~LoopBase()
  {
  }
  virtual void Draw(BITMAP* bmp)=0;
  virtual void ProcessKey(int key){}
  bool needExitLoop()
  {
    if(needExit)
    {
      needExit=false;
      return true;
    }
    return false;
  }
protected:
  bool needExit;
};
void Loop(LoopBase& lc)
{
  while(!needShutdown)
  {
    int frameStart=getmillis();
    clear_bitmap(backBuffer);
    lc.Draw(backBuffer);
    if(Tutorial::getInstance())
    {
      Tutorial::getInstance()->Draw(backBuffer);
    }
    if(keypressed())
    {
      int key=readkey()|(key_shifts<<16);
      if(Tutorial::getInstance())
      {
        Tutorial::getInstance()->ProcessKeyEx(key,lc);
      }else
      {
        lc.ProcessKey(key);
      }
    }
    frameCount++;
    blit(backBuffer,screen,0,0,0,0,backBuffer->w,backBuffer->h);//options.screenWidth,options.screenHeight);
    int frameTime=getmillis()-frameStart;
    if(frameTime<20)millisleep(20-frameTime);
    if(lc.needExitLoop())
    {
      break;
    }
  }
}
Logged
Klaim
Level 10
*****



View Profile WWW
« Reply #37 on: June 13, 2012, 08:30:03 AM »

Ok here is a more complex setup, from the previous version of my "big" game, that i am making very simpler right now but still have some parts interesting:


Code:
int Application::mainLoop()
try // this may be inefficient ? for instance, avoid premature optimization and keep that
{
System& system = System::instance();

// Just update the system!
// Note : the system update is voluntarily the fastest we can,
// but the real game state will not be updated that fast.
// In fact the real game is updated in another loop on another thread
// that will make it update at a fixed frame rate.
// So don't change this. Some reference : http://dewitters.koonsolo.com/gameloop.html
system.update();

// THIS IS FOR TEST ONLY - CHANGE THAT LATER :
KeyboardInput& keyboard = InputManager::instance().keyboard();
if(keyboard.getKeyState(KC_ESCAPE) == KEY_IS_DOWN)
end();


return 0;
}
catch (Exception& e)
{
//We have a "known" problem...
ErrorHandler error_handler( e, "An error occurred while NetRush was playing with the player!" );

NR_LOG <<   "!=======================================!" ;
error_handler.write_log( NR_LOG );

//
terminateSystem();

throw;
}
catch( std::exception& e)
{
ErrorHandler error_handler( e, "A strange error occurred while NetRush was playing with the player!" );

NR_LOG <<   "!=======================================!" ;
error_handler.write_log( NR_LOG );

//
terminateSystem();

throw;
}
catch(...)
{
ErrorHandler error_handler( "An unknown error occurred while NetRush was playing with the player!" );

NR_LOG <<   "!=======================================!" ;
error_handler.write_log( NR_LOG );

//
terminateSystem();

throw;
}


Then system.update() does this:
Code:
void System::update()
{
NR_ASSERT( isReady(), "Tried to update non-initialized system!" );

if( m_isFirstUpdate )
{
firstUpdate(); // we need to setup some informations at first update
return; // yes // do we need to skip this update?
}

m_taskManager.executeTasks();
}

I don't remember what the hell is that first update infos, but I will check this out while reorganising everything simpler.

The taskmanager have several tasks provided by different systems, each task begin just an object to call to update the system (several different updates can be called).
It is not parallel in this version but it is made in a way that allows it later. Also, it allows the graphic and audio rendering to be updated far more than the different other tasks: each task can be (or not) scheduled to be executed or just sit in the task main loop.

This makes the call stack a bit big but it makes finding problems and fixing them very good.

The try/catch thing is overkill here, I'll make that simpler soon too.
Logged

http://www.klaimsden.net | Game : NetRush | Digital Story-Telling Technologies : Art Of Sequence
ChevyRay
Level 1
*



View Profile WWW Email
« Reply #38 on: June 13, 2012, 08:44:33 AM »

@Chevy

Ooooh. Is there any out-standing reason you chose to have Esc be an engine level killswitch for the entire game? That seems like it could be rather problematic if pressed accidentally or whatnot.

It's just code I haven't removed yet, had to have it in there for easy escape while I was testing out full-screen/resolution functionality in case I botched something up. It'll be replaced with a toggle/variable soon.

Also, it's probably the button I most commonly press in games Cheesy so I wish more had an esc-killswitch. But I kid (sorta).
Logged

GCshepard
Level 0
**



View Profile Email
« Reply #39 on: June 13, 2012, 10:16:18 AM »

This looks fun.

Here's the Update loop for my last game.
Code:
protected override void Update(GameTime gameTime)
{
    if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || (keyState.IsKeyDown(Keys.Escape) && keyPrev.IsKeyDown(Keys.Escape)))
        this.Exit();
    keyPrev = keyState;
    keyState = Keyboard.GetState();
    padPrev = padState;
    padState = GamePad.GetState(padPlayer);

    if (setupTime > 0f)
    {
        setupTime -= (float)gameTime.ElapsedGameTime.TotalSeconds;
        if (keyState.IsKeyDown(Keys.Space) || keyState.IsKeyDown(Keys.Z) || keyState.IsKeyDown(Keys.X) || keyState.IsKeyDown(Keys.C))
            setupTime = 0f;
    }
    else
    {
        if (Player.alive)
        {
            Player.Update(gameTime, keyState, padState); //run this before (does collchecks)
        }
        else
        {
            if (keyState.IsKeyDown(Keys.Space) && keyPrev.IsKeyUp(Keys.Space))
            {
                EnemyManager.Initiate();
                Player.Initiate(Vector2.Zero);
                EffectManager.Initiate();
            }
        }
        EnemyManager.Update(gameTime); //run this after (clears enemies)
        EffectManager.Update(gameTime);
    }

    base.Update(gameTime);
}

And the Draw loop. Slightly sloppy. Bleh.
Code:
protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.Black);
    spriteBatch.Begin();

    if (setupTime > 0f)
    {
        spriteBatch.Draw(GJsetup, new Rectangle(0, 0, 640, 640), Color.White * Math.Min(setupTime*2f,1f));
    }
    else
    {
        EffectManager.Draw(spriteBatch);
        EnemyManager.Draw(spriteBatch);

        if (Player.alive)
        {
            Player.Draw(spriteBatch);
            Player.DrawHud(spriteBatch, gameTime);
            if (EnemyManager.win)
            {
                spriteBatch.DrawString(fontBig, "YOU WIN", new Vector2(320, 300), Color.Cyan, 0f, new Vector2(65, 0), 1f, SpriteEffects.None, 0f);
                spriteBatch.DrawString(font, "YOU MAY NOW RESUME YOUR LIFE o.O", new Vector2(320, 340), Color.Cyan, 0f, new Vector2(55, 0), 1f, SpriteEffects.None, 0f);
            }
            else
            {

                if (EnemyManager.waveDetected)
                {
                    float det = (2f - EnemyManager.waveTime) / 2f;
                    float rotate = (float)Math.Sign(det) * 50f * (float)Math.Pow(det, 4f);
                    for (int i = 0; i < 7; i++)
                    {
                        spriteBatch.DrawString(fontBig, "WAVE " + EnemyManager.wave.ToString(), new Vector2(320, 200), Color.DarkCyan, rotate * (1f + ((float)(3 - i) / 30f)), new Vector2(40, 20), 1f, SpriteEffects.None, 0f);
                    }
                    spriteBatch.DrawString(fontBig, "WAVE " + EnemyManager.wave.ToString(), new Vector2(320, 200), Color.Cyan, rotate, new Vector2(40, 20), 1f, SpriteEffects.None, 0f);
                }
            }
        }
        else
        {
            spriteBatch.DrawString(fontBig, "GAME OVER", new Vector2(320, 300), Color.Cyan, 0f, new Vector2(65, 0), 1f, SpriteEffects.None, 0f);
            spriteBatch.DrawString(font, "AT WAVE " + EnemyManager.wave.ToString(), new Vector2(320, 330), Color.Cyan, 0f, new Vector2(30, 0), 1f, SpriteEffects.None, 0f);
            spriteBatch.DrawString(font, "PRESS SPACE TO START", new Vector2(320, 340), Color.Cyan, 0f, new Vector2(40, 0), 1f, SpriteEffects.None, 0f);
        }
    }
           
    spriteBatch.End();
    base.Draw(gameTime);
}
Logged
paste
Level 6
*


BARF!

HeyIAintEddie
View Profile WWW
« Reply #40 on: June 13, 2012, 11:18:47 AM »

BOOM!
Code:

void GameLoop()
{
Update();
Draw();
}

That's it. Seriously. I like my code clean

Code:
void Update()
{
// Change states, if necessary
SwitchStates();

// Update clock variables
elapsedTime = clock.getElapsedTime();
clock.restart();

// Relent control to the current GameState and retrieve the next GameState to move to.
nextStateName = currentState->Update(mainWindow, elapsedTime);
}

void Draw()
{
if(IsExiting())
return;
mainWindow.clear(sf::Color(155,110,50));

currentState->Draw(mainWindow);

mainWindow.display();
}
Logged

Revk
Level 0
**



View Profile WWW Email
« Reply #41 on: June 13, 2012, 12:29:05 PM »

Cool stuff here. Shows game loops can go from ridiculously long mess to some two-liners.

Here is mine, using an homebrewed C99 engine.
Not much AI/gameplay done yet. Concentrating on the world/map-system for now. That's why there isn't much stuff in the AI/Gameplay loop  :

Code:
void Game_run() {
    // clock & time record variables
    f32 start_t = 0.f, frame_t = 0.f;

    // gameplay/IA update variables
    const f32 phy_dt = 0.01f;
    f32 phy_update = 0.f, one_sec = 0.f;


    // MAIN LOOP
    while( true ) {
        // sample frame start time
        start_t = Clock_getElapsedTime( &game->clock );

        // check for game termination
        if( IsKeyUp( K_Escape ) || !Context_isWindowOpen() )
            break;

       
        // update events and inputs
        EventManager_update();

        // GAMEPLAY
            phy_update += frame_t;
            one_sec += frame_t;

            // custom frame callback. return false immediatly if frame_func said it
            if( game->frame_func && !game->frame_func( frame_t ) )
                break;

            // AI/GAMEPLAY LOOP (fixed at 1/phy_dt FPS)
            while( phy_update >= phy_dt ) {
                Scene_update( game->scene, phy_dt, game->mode );
                /* TODO : WORLD UPDATE ! */
                phy_update -= phy_dt;
            }

            // EACH 1 SECOND STUFF, (temp stuff)
            if( one_sec >= 1.f ) {
                str32 fps_str;
                snprintf( fps_str, 32, "FPS : %4.0f", (1.f/frame_t) );
                Scene_modifyText( game->scene, game->fps_text, TA_String, fps_str );
                one_sec = 0.f;
            }

        // RENDERING
            Renderer_beginFrame();
            Scene_render( game->scene );
            Context_swap();
   

        // calculate frame time
        frame_t = Clock_getElapsedTime( &game->clock ) - start_t;
    }

    // End game and free RAM/VRAM resources
    Game_destroy();
}
Logged
cliffski
Level 0
***



View Profile WWW
« Reply #42 on: June 14, 2012, 09:05:35 AM »

This is the loop from Gratuitous Tank Battles (www.gratuitoustankbattles.com)

Code:

void Game::GameProc()
{
HRESULT result = GetD3DEngine()->GetDevice()->TestCooperativeLevel();
if(FAILED(result))
{
if (result == D3DERR_DEVICELOST )
{
Sleep( 50 );
return;
}
else if(result == D3DERR_DEVICENOTRESET)
{
if (!GetD3DEngine()->Restore())
{
// Device is lost still
Sleep( 50 );
return;

}
GetDebug()->DebugOut("Rebuilding directx resources");

if(GUI_BS_Deployment::PTheWindow)
{
SAFEDELETE(GUI_BS_Deployment::PTheWindow);
CLoadedTexture::RemoveByName("rt_depicons");
}
//it worked, rebuild stuff
CreateRenderTargets();
GUI_Get_BS_InfantryCompositor()->ClearTextures();
CLoadedTexture::RebuildAll();
GUI_GetShaderManager()->Release();
GUI_GetShaderManager()->Restore();
InitText();
GVertexBuffer::GlobalVB.Initialise(5000,true);

GUI_GetBattleScreen()->SetRecoverAltTab(true);
}
else
{
Sleep( 50 );
return;
}
}

GTimer looptimer;
looptimer.StartTimer();

GetSteam()->Process();

GetInput()->Process();
GUI_GetCursor()->SetCursorStyle(GUI_Cursor::DEFAULT); //reset each frame...
if(BActive)
{

GUI_GetSounds()->Process();

PCurrentMode->ProcessInput();

GetD3DEngine()->BeginRender();
PCurrentMode->Draw();

DrawDebugOverlay();

GetD3DEngine()->EndRender();
GetD3DEngine()->Flip();

looptimer.Update();
if(looptimer.GetElapsed() < 16.0f)
{
SIM_GetIdleManager()->DoIdleWork();
looptimer.Update();
if(looptimer.GetElapsed() < 16.0f)
{
Sleep(0);
}
}
}
else
{
ReleaseResources();
}
}

Logged

www.positech.co.uk Maker of Democracy Kudos and Gratuitous Space Battles for the PC. owner of showmethegames.com.
Klaim
Level 10
*****



View Profile WWW
« Reply #43 on: June 14, 2012, 09:34:31 PM »

cliffski> Cool!

Are the D3D* names specific to windows or is it an abstraction layer over everything graphic?
As Gratious Space Battle is running on several platform, I assume the latest?
Logged

http://www.klaimsden.net | Game : NetRush | Digital Story-Telling Technologies : Art Of Sequence
Randomasta
Level 1
*

wait what


View Profile
« Reply #44 on: June 14, 2012, 11:59:40 PM »

So once I had to make a game in J2ME in a few days time. Having never touched Java before, this is what I come up with:
Code:
public void run() {
    while(running) {
        long timeBeginFrame = System.currentTimeMillis();
        CC.getScene().update();
        CC.getScene().render(graphics);
        long processTime = System.currentTimeMillis() - timeBeginFrame;
        if(processTime < CC.getTimePerFrame()) {
            CC.setElapsedTime(CC.getTimePerFrame());
            try {
                Thread.sleep(CC.getTimePerFrame() - processTime);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        } else {
            CC.setElapsedTime(processTime);
        }
        flushGraphics();
    }
}

public void update() {
    ComponentListNode node = components.head;
    if(node.component != null) {
        while(node != null) {
            node.component.update();
            node = node.next;
        }
    }
    if(!startTester) {
        startTester = true;
    }
}

public void render(Graphics graphics) {
    if(startTester) {
        graphics.setColor(bgColor);
        graphics.fillRect(0, 0, CC.width, CC.height);
        ComponentListNode node = components.head;
        if(node.component != null) {
            while(node != null) {
                node.component.render(graphics);
                node = node.next;
            }
        }
    }
}
Logged
Pages: 1 2 [3] 4
Print
Jump to:  

Theme orange-lt created by panic