What minimal first test I should write to start in BDD? - tdd

I am learning BDD and trying to make very simple game. Player see some polygon shape and need to guess it's area by expanding circle spot. To guess player need to hold finger on screen (mobile game) for some time to expand circle to desired size. If circle's area is near shape area, thep player wins.
Now i want to create first minimal test to start developing, but I can't figure out this test.
This is the most simple test that I write (in bdd style):
public partial class GuessShapeSize_Feature
{
[Test]
public void RightGuess_Scenario()
{
Given_expanding_spot_expand_speed_is (5.0f);
Given_shape_has_area_of (15.0f);
When_player_holds_finger_for_seconds (3.0f);
Then_player_guess_result_is (GuessResult.Success);
}
}
The problem here is that it is complex test that required around 5 classes: Level (container for everything happens here and checks for result), Shape (to guess), PlayerInput (hold and release finger), CircleSpot (that expands over time), TimeManager (i need to fake 3 seconds elapsed).
I can't name this test really simple for the first test. But I can't imagine any simpler test. What should i do in this situtation?

You don't really need 5 classses for that first answer. All you need is an empty API or UI, and something which always returns GuessResult.Success.
The time manager will only be used from within the scenario (and is always set to 3 seconds for now).
If that behaviour isn't rich enough (well, of course it isn't!) then what scenario comes next? Can you think of an example where your game should return something other than GameResult.Success?
Start by making one scenario at a time pass in the simplest possible way. When it isn't enough, change it.
It's absolutely fine to have the classes of your design in mind, but make it simple, and refactor as you go to meet that design.
As you break out other classes, you'll be delegating parts of the system behaviour to those classes. Some things will be better expressed as behaviour of classes than full system stuff (probably the rules around area calculation, for example) so write an example of how the class behaves from the API / UI's point of view (TDD). This is the "outside-in" of BDD.
This will help you to keep a good Test Pyramid (lots of unit tests, few scenarios).
Don't forget to talk to someone about what it is you're doing, even if it's a rubber duck.

Think smaller, meaning: look at the "building blocks" that your overall experience requires:
You need an expanding spot. What about a test that simply tests that you have such an expanding thing?
Then: that expanding spot will at some point hit a hard limit. So, write a test to ensure the spot grows to that limit, but not beyond.
Next thing: user input. Write a test showing the growing shape and test the required user interactions (without deciding about winning or loosing)
And then when all these things work, then you can come back to the test you already have: the full user experience, maybe in different flavors to represent the winning and losing case.

Related

Avoiding nested for loops in 2D game engine

I am creating a 2D game.
There are many objects, each has a width, a height, and X and Y coordinates.
Each object is stored in an array of it's class:
the player
allies
enemies
obstacles
power ups
bullets shot by the enemies
bullets shot by the player & allies
To make the game work, I need to obviously detect if two elements occupy the same space (let's call it "collission") , so that
the player can collect power ups
nobody can pass through obstacles
the allies can shoot the enemies
the enemies can shoot the allies
friendly fire can be either enabled or disabled
this needs to be checked every frame, 60 times per second.
What I have been doing so far, is loop through each class, and then loop over each class that it can interact with.
For example:
foreach (ally_bullets)
{
foreach (enemies)
{
if ( collision detected between enemy and bullet )
{
remove the bullet and the enemy
}
}
}
It makes sense and it works, but it's very resource intensive as the game gets more complex. The more elements there are, the longer this nested for loop takes to render, ultimately reducing the frame rate. Even if I am trying to run as few loops as possible.
What's a better way of solving this then nested for loops?
A common solution is to use Polymorphism, in which you have a base class (in this case Object) which gets inherited by other classes (such as Player, Bullet, Enemy, etc). Instead of each of these having an individual array, you would have a single array (or typically more appropriate, a vector). Now you just loop through that one array having each Object do their updates, and have their updates checked against every Object in the array.
This 'vector-wise' updating is usually setup as a Messaging System. Now whenever an inherited Object receives a message (such as 'hit by bullet'), that object checks if it cares about that message. If so, accept the message, else ignore it.
This is (in my opinion) the better way to handle what you are trying to accomplish, which I believe is what you were asking.
If you are still using arrays for this, I am going to assume you are still fairly new to programming, and I am going to suggest sticking with what you have now. It will absolutely work (providing you know how to finish your project), and when you finish this and start to learn something more advanced you will see both the shortcomings of the way you are doing it, and the benefits of it).
If you do see some lag arise, it will likely be from your drawing methods long before this kind of interactivity checking becomes a bottleneck.
Either way you go, collision detection itself and rendering are going to be the main areas your cpu will be eaten up, providing your arrays stay within reasonable ranges.
Edit:
Another thing that will help you should you pursue the topics I mentioned is the Observer Pattern, also known as the Listener Pattern.

Multiplayer shooter: should projectiles carry the information about damage, or should the damaged entity?

This is a conceptual question, so no code is included.
When making a multiplayer shooter, be it 2D or 3D, where there are projectile-based weapons, should each projectile contain information as to who fired it, and how much damage it should do? Or, should the entity, upon being struck by the projectile, interpret the projectile and deal damage to itself accordingly?
Basically, the question is "where should the information/code about the damage being dealt exist."
Thoughts?
Personally, I think that giving the projectile this damage provides better modularity and makes more sense logically.
Modularity
I used to do M.U.G.E.N, a fighting game engine where individual creators and teams of creators can release either full games or pieces of games. Full games are actually comparatively rare next to individual characters, stages and etc that you could copy into your own folder and have added to your roster. So if any game engine absolutely had to be designed for modularity, this was it.
How did M.U.G.E.N handle the situation? Except in specific circumstances where a particular creator wanted to do something creative or unconventional, damage amount (and a gazillion more pieces of information, like hit sound, how long to stun, what state to enter as a result) are carried by the character that delivers the attack (In a shooter, this would be equivalent to the bullet holding this information). Why?
Well, simply put, there's no way that one character could be defined so that it could tell who hit it and what attack they used when said character and attack hadn't even been made yet. Keep in mind, characters from 1999 and characters from 2016 are able to fight each other without issue. And almost as dauntingly (and more relevant for you), even if a character's creator could somehow precognitively know every character and every attack that would be added, it would take a long time and a lot of code to add a case for all of them.
So let's get back to the idea of a shooter. Consider that you have two kinds of bullets. One is big and deals a lot of damage (we'll call this BigBullet), while the other is small and deals a little damage (We'll call this SmallBullet). Consider also that you have two kinds of targets that these bullets can damage (We'll call them Soldier and Tank). If you store damage information in the target classes (Soldier and Tank), you have to define this information for each type of bullet for each type of target.
That is, Soldier class will have to have logic to determine which type of bullet it is and how much damage it should deal. Tank class will also have to have logic to determine which type of bullet it is and how much damage it should deal. You can reduce the redundancy of this code if you inherit both classes from a common base class, true.
But compare with the alternative. BigBullet and SmallBullet have a public damage field. The Soldier and Tank don't have to care what type of bullet it got hit by; only ask how much damage it should do. So you can remove that code altogether.
And more importantly, this allows the design to be easily expandable. If you later decide you want a new HugeBullet class that deals even more damage, all you need to do is make a new HugeBullet class. You don't have to worry about updating your target entities at all.
Logic
This is more opinional, but let me describe the way I look at it.
Consider the human skull. It is a work of art. It's got joints in it that allow jaw movement. It has holes in all the right places to allow sensory information to enter, and a hole for food. It's designed for durability and observation.
But it's not specifically designed for every single thing that can happen to it. It doesn't have a bullet-deflection property or an axe-survival property. It has properties that contribute to these defenses, but only in the vaguest and most general of terms. Maybe they have a general resistance to piercing, but they don't have a particular resistance to piercing by each individual type of bullet.
Ultimately the driving force behind how much damage it takes lies with the design of the weapon that strikes it. A bullet is designed to cut through flesh and bone. So organizing your code so that the bullet objects carry damage data is a more accurate simulation of reality.
IMHO
Depends entirely on what you consider damage:
Damage potential from the projectile... definitely store in each projectile.
Damage realized upon the target... a counter to add all the damage inflicted on it by the different projectiles.
Information stored on the projectile regarding firing entity is only relevant if the firing entity is to be awarded points for sucessful hits on targets.

Developing a Checkers (Draughts) engine, how to begin?

I'm a relatively inexperienced programmer, and recently I've been getting interested in making a Checkers game app for a school project. I'm not sure where I can start (or if I should even attempt) at creating this. The project I have in mind probably wouldn't involve much more than a simple AI & a multiplayer player mode.
Can anyone give some hints / guidance for me to start learning?
To some extent I agree with some of the comments on the question that suggest 'try something simpler first', but checkers is simple enough that you may be able to get a working program - and you will certainly learn useful things as you go.
My suggestion would be to divide the problem into sections and solve each one in turn. For example:
1) Board representation - perhaps use an 8x8 array to represent the board. You need to be able to fill a square with empty, white piece, black piece, white king, black king. A more efficient solution might be to have a look at 'bit-boards' in which the occupancy of the board is described by a set of 64-bit integers. You probably want to end up with functions that can load or save a board state, print or display the board, and determine what (if anything ) is at some position.
2) Move representation - find a way to calculate legal moves. Which pieces can move and where they can move to. You will need to take into account - moving off the edges of the board, blocked moves, jumps, multiple jumps, kings moving 'backwards' etc. You probably want to end up with functions that can calculate all legal moves for a piece, determine if a suggested move is legal, record a game as a series of moves, maybe interface with the end user so by mousing or entering text commands you can 'play' a game on your board. So even if you only get that far then you have a 'product' you can demonstrate and people can interact with.
3) Computer play - this is the harder part - You will need to learn about minimax, alpha-beta pruning, iterative deepening and all the associated guff that goes into computer game AI - some of it sounds harder than it actually is. You also need to develop a position evaluation algorithm that measures the value of a position so the computer can decide which is the 'best' move to make. This can be as simple as the naive assumption that taking an opponents piece is always better than not taking one, that making a king is better than not making one, or that a move that leaves you with more future moves is better than one that leaves you with less choices for your next move. In practice, even a very simple 'greedy' board evaluation can work quite well if you can look 2-3 moves ahead.
All in all though, it may be simpler to look at something a little less ambitious than checkers - Othello is possibly a good choice and it is not hard to write an Othello player that can thrash a human who hasn't played a lot of the game. 3D tic-tac-toe, or a small dots-and-boxes game might be suitable too. Games like these are simpler as there are no kings or boundaries to complicate things, all (well most) moves are legal and they are sufficiently 'fun' to play to be a worthwhile software demonstration.
First let me state, the task you are talking about is a lot larger then you think it is.
How you should do it is break it down into very small manageable pieces.
The reasons are
Smaller steps are easier to understand
Getting fast feed back will help inspire you to continue and will help you fix things as they go wrong.
As you start think of the smallest step possible of something to do. Here are some ideas of parts to start:
Make a simple title screen- Just the title and to hit a key for it to
go away.
make the UI for an empty checkerboard grid.
I know those sound like not much but those will probably take much ore time than you think.
then add thing like adding the checkers, keeping the the gameboard data etc.,
Don't even think about AI until you have a game that two players can play with no UI.
What you should do is think about: what is the smallest increment I can do and add that, add that and then think about what the next small piece is.
Trust me this is the best way about going about it. If you try to write everything at once it will never happen.

How should platformer game's solid objects be implemented efficiently?

I have been trying to write a platformer engine for a few times now. The thing is I am not quite satisfied with my implementation details on solid objects. (wall, floor, ceiling) I have several scenario I would like to discuss.
For a simple platformer game like the first Mario, everything is pretty much blocks. A good implementation should only check for necessary collision, for instance, if Mario is running and at the end of the way, there is a cliff, how should we check for collision efficiently? Should we always check on every step Mario is taking to see whether his hitbox is still on the ground? Or is there some other programming way that allows us to not handle this every frame?
But blocks are boring, let's put in some slopes. Implementation details-wise, how should slopes be handled? Some games such as Sonic, have this loop structure that the character can go "woohoo" in the loop and proceed.
Another scenario is "solid" objects (floor, ceiling, wall) handling. In Megaman, we can see that the player can make himself go through the ceiling by using a tool to go into the solid "wall". Possibly, the programming here is to force the player to go out of the wall so that the player is not stuck, by moving the player quickly to the right. This is an old "workaround" method to avoid player stucking in wall. In newer games these days, the handle is more complex. Take, for instance, Super Smash Brawl, where players can enlarge the characters (along with their hitbox) The program allows the player to move around "in" the ceiling, but once the character is out of the "solid" area, they cannot move back in. Moreover, sometimes, a character is gigantic that they go through 3 solid floors of a scene and they can still move inside fine. Anybody knows implementation details along these lines?
So here, I know that there are many implementation possible, but I just wanna ask here that are there some advanced technical details for platformer game that I should be aware of? I am currently asking for 3 things:
How should solid collision of platformer game be handled efficiently? Can we take lesser time to check whether a character has ran and completely fell off a platform?
Slope programming. At first, I was thinking of physics engine, but I think it might be overkill. But in here, I see that slopes are pretty much another types of floor that "push" or "pull" the character to different elevation. Or should it be programmed differently?
Solid objects handling for special cases. There might be a time where the player can slip into the solid objects either via legal game rules or glitches, but all in all, it is always a bad idea to push the player to some random direction if he is in a wall.
For a small number of objects, doing an all-pairs collision detection check at each time step is fine. Once you get more than a couple hundred objects, you may want to start considering a more efficient method. One way is to use a binary space partitioning (BSP) to only check against nearby objects. Collision detection is a very well researched topics and there are a plethora of resources describing various optimizations.
Indeed, a physics engine is likely overkill for this task. Generally speaking, you can associate with each moving character a "ground" on which he is standing. Then whenever he moves, you simply make him move along the axis of the ground.
Slipping into objects is almost always a bad idea. Try to avoid it if possible.

TDD Spider Solitaire

Another question about TDD from me. I have read some articles and book chapters about TDD and I understand why you should TDD and I understand the simple examples but it seems when I am trying this out in the real world I get stuck very easy.
Could you give me some simple TDD examples if you were to program the well known Spider Solitaire that comes with Windows Vista? Which tests would you start with?
Solitaire games involve cards.
So, you think of a Card class. You write some tests for individual Card objects. You write your Card class to pass the tests.
You need a deck that shuffles and deals into the layout. You think of the Deck class and the shuffle algorithm and how it maintains state for dealing. You write some tests for a Deck that shuffles and deals. You write your Deck class to pass the tests. [Note, this requires a mock random number generator that isn't actually random.]
Solitaire games involve a layout with empty spaces and cards. Some empty spaces of rules (Kings only or Aces only). Solitaire games sometimes involve a stock, more-or-less the remains of the Deck.
So you think of a Layout class with spaces for cards. You write some tests for the Layout and put in various Cards. You write your Layout class to pass the tests.
Then there's rules on what cards can be moved from the layout. Whole stacks, sub-stacks, top cards, whatever. You have an AllowedMove or GameState or some such class. Same drill. Define roughly what it does, write tests, finish the class.
You have user interface and display stuff. The drill is the same.
Rough out the class.
Define the tests.
Finish the class.
etc.
I cover this in detail in a book on OO Design.
Well, when you're asking about TDD for spider solitaire, you're basically asking about how to design such a game. The tests will be the consequence of design decisions. Solitaire is a simple game, but designing such a game from scratch isn't trivial (there's more than one way to go about it).
You might want to start with something much simpler to design, like a number guessing game (where the system generates a random number and you try to guess it in as few tries as possible).
Some features of such a simple game would be:
Feature to generate the secret number randomly between 1 and 10. Generating a new number starts a new game.
Feature to compare whether a player's input is higher or lower than that number, or if the guess is right on
Feature to count the number of guesses
From that you might try these tests (just as crude examples, but easily coded):
Run your generator 1000 times. Make sure secret_number >= 1 && secret_number <= 10 every time.
For a sample set of numbers (randomly generated), does your comparison function return "HIGH" when number > secret_number, "LOW" when number < secret_number, and "WIN" when number == secret_number?
Repeat the previous test, but track the number of items you test. When "WIN" is returned, make sure your counter feature matches your test's number of items.
This is just a very rough outline, and by no means complete. But you can see from the english descriptions that code examples would be even more verbose. I think if you want more specific answers, you have to ask a more specific question.
First you should separate out the GUI from the engine. TDDing the GUI is the hardest part, so you shall keep your GUI layer as thin as you can. Google for "the humble dialog box" and read the tddui list on Yahoo! groups.
The engine layer will implement the game rules. I'm not sure how the Spider solitaire differs from the ancient solitaire (i.e. from Windows 3.1) on which I based the following:
Here is the initial test list I will start from:
you can always move a card to an empty stack
a card has a value, and one can compare to cards
you can only move a card to a non-empty stack when the card on the top is lower than the moved card
you can always move several cards to an empty stack
you can only move several cards to a non-empty stack when the card on the top is lower than the moved card
when you move all the turned cards from a stack, the top card can be returned (or shall be automatically returned ?)
you can take a the first card from the dock and put in an any stack (?)
I'me getting unsure about the rules, but I think this is enough to get the idea.
Last, start with the simplest test, add tests to the list when you have a new test idea, or when you find yourself questioning: what happen if ... .
list the features of spider solitaire [i don't play card games]
describe how you would test each feature
do it

Resources