• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
Nicholas Kong

Is there a way to break out of an if statement without "hacking the code"?

17 posts in this topic

I noticed I cannot use a break statement inside of an if statement. I'm using Java.

 

Compiler will complain to the following:

 

if(true)

{

  break; // invalid code

}

 

This lead me to have habits of hacking the code everything I cannot break out of the if statement.

 

I would usually set the boolean flag to false right after execution has been done once because I just want the code to execute once.

 

EDIT:

 

Example of hacky approach: The code written below is used for when a character has leveled up in-game. The current level gets incremented, the current and max hp gets updated. The current hp gets updated to the updated max level. Upon level up, the level up logo renders upward above the character and disappears once it has reached a certain final point(this will be dictated by some fixed height in the game code).

 

All the code will appear in the main character update method.

 

NOTE: levelUp = true triggers everything(all the hp data to be updated and level up Logo effect to happen.)

public void update()
{
        if(exp >= 15 && (level < maxLevel))
       {
              levelUp = true;
              exp = 0;
       }
 
       if(updateLevel && (level < maxLevel) )
       {
              level++;
              updateLevel = false;
       }
 
       // update current hp
       if(updateCurrenHpAfterLevelUp)
       {
               if(life < maxLife)
               {
 
                     life++;
 
               }
 
               if(life == maxLife)
               {
                     updateCurrenHpAfterLevelUp = false;
               }
 
       }
 
 
        // updates maxHp
        if(updateMaxHpAfterLevelUp)
        {
                  if(maxHpCounter < maxHpIncrease)
                  {
                          maxLife++;
                          maxHpCounter++;
 
                  }
 
 
 
                   if(maxHpCounter == maxHpIncrease)
                   {
                          maxHpCounter = 0;
                          updateCurrenHpAfterLevelUp = true;
 
                          updateMaxHpAfterLevelUp = false;
 
                   }
         }
 
                   if(levelUp)
                   {
 
 
                         levelUpLogo.update();
 
 
                         if(levelUpLogo.getHeightIncrease() == levelUpLogo.getMaxHeight())
                         {
                                   levelUp = false;
                                   updateMaxHpAfterLevelUp = true;
                                   updateLevel = true;
 
                                   levelUpLogo.setHeightIncrease(0);
                         }
                   }
 
 
}
Edited by warnexus
0

Share this post


Link to post
Share on other sites

 

I would usually set the boolean flag to false right after execution has been done once because I just want the code to execute once.

I do not see though why would execution return before the if again, is it in a cycle?

 

In case you do not wish the code to continue inside the if upon some condidtion, nested if is what I would do.

 

In case the if is in a cycle and you wish it to run only once- you should move it out of cycle primarily if you can.

 

In case the execution once wish to run it , once not, keep condition altering as you do.

 

Anyway, it is always a very particular problem, and one has always many ways to rethink what he is performing and how.

 

Without criticizing the very concrete code of yours, we cannot give you a definite advice on this.

0

Share this post


Link to post
Share on other sites

Honestly kind of hard to tell what it is you need though, you may have to expand on what you are trying to solve, but that said...

 

Some things to think about, if you are in a loop, you can use the continue keyword, though I know some people won't approve, as they prefer to have as simple of a control flow as possible (which you could get by rearranging your code)  As debugging anything that jumps around all over the place is a pain.

 

Or you might need to rejigger it to be a function that returns a boolean, then you can just return as soon as you've gotten far enough.

Edited by ferrous
0

Share this post


Link to post
Share on other sites
This is also quite hacky, but if you're interested in Dumb Programmer Tricks, here's one for you:

for (bool once = true; once; once = false) {
  // stuff that happens at most once

  if (early_exit)
    break; // 'continue' would also work

  // other stuff that happens at most once
}
I have blissfully never seen this kind of code in the wild, aside from some gnarly pre-C++11 macros for emulating range-based-for.

Decomposing your logic into separate functions is a _significantly_ better idea, of course.
0

Share this post


Link to post
Share on other sites
In the same line as SeanMiddleditch's hack:
#define breakable_if(X) for (bool breakable_if_var = X; breakable_if_var; breakable_if_var = false)
0

Share this post


Link to post
Share on other sites

Your approach seem a bit hackish if you want my opinion. Perhaps you should refactor and encapsulate more code into classes that would take care of the leveling up process and manage the player health ect? Your code is very  hard to read/understand atm to be honest. You might consider splitting those things up into functions.

Edited by Vortez
2

Share this post


Link to post
Share on other sites


Your approach seem a bit hackish if you want my opinion. Perhaps you should refactor and encapsulate more code into classes that would take care of the leveling up process and manage the player health ect? Your code is very  hard to read/understand atm to be honest. You might consider splitting those things up into functions.

 

Fair enough. Thanks for the feedback.

1

Share this post


Link to post
Share on other sites
Even taking a quick peek at the code I'd say you can probably significantly streamline the branching just by following the advice about breaking some of the code into more functions. Leveling up for example could quite easily be a function in itself.
0

Share this post


Link to post
Share on other sites
Have to agree; what you really want here is a state machine, or at least several functions.
 
Part of your problem is that you're trying to handle event-based stuff in a polling update loop. You can do it that way, but it will make your life much easier if you break things like incrementing XP into their own function. That way, instead of checking every time it goes through the input loop, it'll only get called when the character actually needs to check for leveling up.
 
[source lang="java"]
public void levelUp() {
   if(level >= maxLevel) {
      return;
   }
   int hp_per_level; // defining this so it's not a magic number
   maxHp = min(maxHp + hp_per_level, maxHpIncrease);
   life = min(life + hp_per_level, maxHp);
   levelUpLogo.play();
}
 
// Call this whenever your character adds XP
public void addXP(int exp_to_add) {
   // check for leveling
   int xp_per_level = 15; // defining this so it's not a magic number
   exp += exp_to_add;
 
   if (exp > xp_per_level) {
      levelUp(); // level up
      exp = 0; // this resets exp to 0 after every level, you may want to have it instead be: exp -= xp_per_level;
   }
}
[/source]
Edited by ikarth
0

Share this post


Link to post
Share on other sites
Obviously the correct way to fix this is to refactor your code. You shouldn't need to exit an if without it completing but if you really wanted to do it the hacky way in Java you can use a labeled break which is effectively a goto.

The only place I've seen labeled breaks actually used in production code was when doing J2ME ports of megadrive games where we had the original ASM code in comments and then the Java was a line by line reimplementation including jumps and inclined data.
1

Share this post


Link to post
Share on other sites

Have to agree; what you really want here is a state machine, or at least several functions.
 
Part of your problem is that you're trying to handle event-based stuff in a polling update loop. You can do it that way, but it will make your life much easier if you break things like incrementing XP into their own function. That way, instead of checking every time it goes through the input loop, it'll only get called when the character actually needs to check for leveling up.
 
[source lang="java"]
public void levelUp() {
   if(level >= maxLevel) {
      return;
   }
   int hp_per_level; // defining this so it's not a magic number
   maxHp = min(maxHp + hp_per_level, maxHpIncrease);
   life = min(life + hp_per_level, maxHp);
   levelUpLogo.play();
}
 
// Call this whenever your character adds XP
public void addXP(int exp_to_add) {
   // check for leveling
   int xp_per_level = 15; // defining this so it's not a magic number
   exp += exp_to_add;
 
   if (exp > xp_per_level) {
      levelUp(); // level up
      exp = 0; // this resets exp to 0 after every level, you may want to have it instead be: exp -= xp_per_level;
   }
}
[/source]


Interesting, I notice a return statement that returns no value in the if statement. What or where will the code be when the code reaches return.
0

Share this post


Link to post
Share on other sites

Interesting, I notice a return statement that returns no value in the if statement. What or where will the code be when the code reaches return.


That's a very confused question. `return' quits the function, whether it returns with a value or without it. The execution will continue wherever the function was called.
0

Share this post


Link to post
Share on other sites

 

Interesting, I notice a return statement that returns no value in the if statement. What or where will the code be when the code reaches return.


That's a very confused question. `return' quits the function, whether it returns with a value or without it. The execution will continue wherever the function was called.

 

Specifically, addXP will be called [em]first[/em]. If exp is greater than 15, it will call levelUp(). The levelUp() function will check to see if maxLevel has been reached. If it has, it will return from there with no return value because these are void functions. The return takes it back to the addXp() function at the point it was called, and the next line is executed, in this case setting exp to 0.

 

Step through your running code in a debugger, it will give you a much better idea of what is going on under the hood.

0

Share this post


Link to post
Share on other sites

 

Interesting, I notice a return statement that returns no value in the if statement. What or where will the code be when the code reaches return.


That's a very confused question. `return' quits the function, whether it returns with a value or without it. The execution will continue wherever the function was called.

 

Oh Okay. That was the answer I was looking for. Apologies for rewording the question incorrectly.

0

Share this post


Link to post
Share on other sites

Oh Okay. That was the answer I was looking for. Apologies for rewording the question incorrectly.


Just think of it like returning a value, at any point in your code a function might return a bool or something, you've probably seen or used code like this before.
 
if (somecondition)
{
    dosomestuff;
}
else
{
    otherstuff;
    if (someothercondition)
    {
        return true;
    }
}

return false;
In a void function you can just return without a value, so for all intents and purposes it basically works like a break statement out of the function. Edited by Satharis
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0