Slippy Flippy and the Time Warp.

icon2_120It’s hard being in two periods of time at the same time, or is it?

One problem with the Slippy Flippy Dare was I didn’t blog while I was doing it. I’m now going back and reblogging all my steps, though somewhat cleaned up. However with SlippyFlippyPenguin now in the App Store, I need to start version 1.1 of SlippyFlippyPenguin. I already identified a few things I’d like to add.

  • Need high scores for both the easy and hard versions of the game
  • Need a way of displaying both
  • Add instructions to the game
  • Change the back part of the frame to not have  collision detection — Slippy should not bounce off the back wall.
  • At some point (after 25-50 points and I havent decided yet) add a new obstacle which will make it harder for Slippy — baby penguins. This will also become part of my second game that on the drawing board.
  • change the ice walls to a better flat design graphic.
  • I already know that many people like the icon of the penguin facing forward. I’d like to add an animated graphic of that to the start/ Game over scene.

That’s the shopping list at the moment. I’m sure as people play the game more, other things will show up.

So the problem is I’d like to write about where I am right now and continue writing about building the game — which is development I did a month ago.

The best answer I have is to do both. Starting Monday, I’ll be writing about the improvements to the game in the App Store. I’ll also continue to build the game from the roots up as I have done for a week.

Hopefully  that will get all the information  about game programming out.

Enjoy your journey with me.



The Slippy Flippy Dare: How to Use Basic Physics in Sprite Kit

In the last installment of this series I showed two kinds of animation: SKAction and using the update: method from frame animation. The third major type of animation is using the physics engine.

A physics engine takes the mathematical laws of physics and adds them to the scene. It removes the developer from the math involved. It also adds collision detection, and the physics of collisions. In short, your sprite can work in the scene the same way real objects work in the real word.

To start let’s make sure everyone is in the same place.  If you have not done so, open a Sprite kit template in Xcode. If you have followed along, open your code.

Modify your code  so it should look like this:

-(id)initWithSize:(CGSize)size {
if (self = [super initWithSize:size]) {
/* Setup your scene here */

self.backgroundColor = [SKColor colorWithRed:0.15 green:0.15 blue:0.3 alpha:1.0];

/* Make a penguin */

//Initialize a sprite with a texture from a file.
SKSpriteNode *penguin = [SKSpriteNode spriteNodeWithImageNamed:@"gray penguin";];
penguin.position = CGPointMake(0, 0); = @"penguin";
SKAction *movePenguin = [SKAction moveTo:CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame)) duration:2.0];
[penguin runAction:movePenguin];

[self addChild:penguin];

return self;

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
/* Called when a touch begins */

for (UITouch *touch in touches) {
/* commented out code */


-(void)update:(CFTimeInterval)currentTime {
/* Called before each frame is rendered */
CGPoint position = [[self childNodeWithName:@"penguin"] position];
if (++position.y <= CGRectGetMidY(self.frame)){
[[self childNodeWithName:@"penguin";] setPosition:CGPointMake(++position.x, ++position.y) ];


gray penguinIf you are starting with new code, download the penguin graphic to your computer, name it gray penguin.png and drag it into the file list in Xcode. This includes cleaning out most of the original template code. There will be a warning in the touchesBegan: method. We will come back to that very shortly.

Physics turns on and off for individual sprites. Add the following code just below the assignment:

penguin.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:penguin.frame.size];
penguin.physicsBody.affectedByGravity = NO;

Line 1 turns on the physics engine. All sprites have a property which holds a SKPhysicsBody object. We initialize that object with a class method bodyWithRectangleOfSize: and give the size of the penguin.

By default, gravity is on. To start we turn off gravity, so the penguin’s SKAction can execute in peace. Build and run the code and the penguin should move to the middle of the screen. Change the affectedByGravity to YES and run again. You see Slippy fighting gravity to get to the middle and then falling off the screen. Set affectedByGravity back to NO.
in touchesBegan:, change the for loop with the code:

for (UITouch *touch in touches) {
        [[[self childNodeWithName:@"penguin";] physicsBody] setAffectedByGravity:YES];

Build and run. The penguin moves to the center. When the player touches the screen anywhere, we will turn the gravity on. Slippy then falls off the screen. However, we really don’t want Slippy falling off and out of sight. To solve this,  give the visible scene a physics body. In initWithSize: add the following under the self.background assignment:

//a physics body to prevent the penguin from going off the screen.
        self.physicsBody = [SKPhysicsBody bodyWithEdgeLoopFromRect:self.frame];

Here we used a different type of physics body, an edge loop. This builds a collision body that is only a line instead of a solid body, so the penguin is now trapped inside the frame. Edge loops, unlike bodies, are not affected by gravity by default. Try building and running with this change. Slippy now falls to the bottom of the screen, and bounces into the left corner.

The default gravity is earth normal. Add this code just above the comment for the code you just entered.

self.physicsWorld.gravity = CGVectorMake(0.0, -9.8); //-9.8 Earth normal gravity

On the scene we set up a physicsWorld which gives some environmental properties to physics. If you run this, you will see no change. The -9.8 is earth normal gravity, a value known in physics as g.  Over at The Physics Classroom,  they discuss the value of g.  Included there is a table for g for different planets. If Slippy was on Mars, g becomes 3.75.  We set gravity to pull down by putting a negative sign in front of it. Change the -9.8 or earth normal to -3.75. Now Slippy falls as if he is on Mars. In the real game, the penguin is on a tilting ice sheet and we are looking at the sheet from above. Gravity is much less than 9.8, and I ended up deciding on -7.0 for my gravity. Note if I put 7.0 for gravity, slippy would fall up. In the real game, I multiply the gravity by -1 to change the sign periodically, flipping gravity for a bit more of a challenge.

We don’t want Slippy to fall so we need some way of making him move up. What we need to do is give our penguin a push. The  applyImpulse: method does this by pushing the penguin with a specified force in the x and y directions. Change the code in touchesBegan: to the following:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    /* Called when a touch begins */
    if ([touches count]>0) {
        SKNode *penguin =[self childNodeWithName:@"penguin";];
        if (penguin.physicsBody.affectedByGravity){
            //[penguin.physicsBody applyImpulse:CGVectorMake(0, 0)];
            [penguin.physicsBody applyImpulse:CGVectorMake(0, 7)];
        } else{
            penguin.physicsBody.affectedByGravity = YES;

Figuring the position of our touch on the screen is necessary for many games , and the template has code to handle that case . For our game touching anywhere is good. We only need to know if there are any touches. We changed from the fast enumenration for loop of the template whihc list touches to an if...else statement that looks for any touch.

To reference the penguin easier, we created a SKNode and assigned a pointer to the object. We then check if gravity is on. If it is, we are in game mode. If not, we are in game over/start mode. In game mode we use a method applyImpulse and applied an impulse of 7 in the upward direction. Run this and you find no real change. Change 7 to 30 and see what happens. If you tap very quickly you can move the penguin up a little bit.

We are trying to play volleyball with a dumbell.  Slippy is too heavy or too dense. We need to change his mass or density. I’ll change his density to 0.1. In touchesBegan: change the else block to:

} else{
            penguin.physicsBody.affectedByGravity = YES;
            penguin.physicsBody.density = 0.1;

Now run and tap the screen. Pretty much this is  Flappy Bird’s animation behavior. One more line makes the graphics just a bit better. Remove the comment from the second applyImpulse. This stops motion before applying then new impulse.

That is some the basics of physics engines.  We will explore more of physics engines and collisions, but first we need an obstacle to crash into. That will be our next installment.

From Apple to Raspberry Pie: Python For Loops

appleberryPython for loops is, loopy.

C, Objective-C, Java and most other languages use a for loop that is numerical.

for (int i=0; i<5;i++){
     NSLog(@"The index is: %i", i);

This code will count the numbers, and when the numbers are greater than 5, will stop. Python is different. The for loop is more like fast enumeration in Objective-C than a counting loop.  Python lists individual elements in sequene from some collection such as an array or list.  A closer objective-C example might be:

NSArray *array = [NSArray arrayWithObjects:@"foo", @"bar", nil]; for(NSString *myString in array) { NSLog(myString); }

and Python codes as:

array = ["foo", "bar"]
for my_string in array {

Now look at this  same example, except I’ve added a real number and an integer

array = [&quot;foo&quot;, &quot;bar&quot;, 3.1415926, 1]
for my_string in array {

While it might make Xcode cringe in warnings and errors, this actually runs in Python without a hitch. Dynamic typing at its best. The for loop doesn’t care about the type.

Often we don’t want the element in the array. We want a number, which is easy with C-style for loops. Python has a solution to this: the range() function. The range() function sets a range of integers to enumerate through. there are one , two and three parameter varieties.

range(5)   # range of 0 through 4
range(1,5) #range of 1 through 4
range (1,20,2) #range of 1 through 19  stepping by 2

We replace the array or list with range in the for loop, and we get something similar to our C-style loop

# for (int i=0; i<5; i++){}
for i in range(5):
    print ('Simple for ', i)

# for (int i=1; i<5; i++){NSLog(@"Simple for from 1 %i",i);}
for i in range(1,5):
    print ('Simple for from 1 ', i)

# for (int i=1; i<20; i+=2){NSLog(@"Simple for from 1 %i",i);}
for i in range(1,20,2):
    print ('For from 1 by 2 ', i)

Note in each of these examples our test expression in the C-style loop is i< 5 not i<= 5. You count to a number less than the number in the second parameter.

Once you understand the range() function in for loops, they become easy. One last example. What if you wanted both an index and the value of its index?


for i in range(len(a)):
    print (i, a[i])
    a[i] = a[i] + '!!!'

From Apple to Raspberry Pi: While Loops

In Xcode, both in Objective-C and C, we have the while loop.

int number = 5;
while (number > 0){
    NSLog(@"The number is %i",number--);

The python equivalent is also while Since we already understand the block, know sometimes as a suite in Python, while loops in  Python are very simple to use.

number = 5
while number > 0:
    number = number -1
    print ('The number is ', number)

We can use break in a loop to break execution. This is a valid loop if we need to test at the end of the loop

number = 5
while True:
    number = number -1
    print ('The number is ', number)
    if number < 0:

The Slippy Flippy Challenge: How to Move a Sprite

iOS Simulator Screen shot Mar 26, 2014, 8.32.35 AM
The game when animation is working

Back in February,  I bragged once that I could put together  Flappy Bird in a week. Someone called my bluff, and I was challenged to do so.  I did put together a game like Flappy Bird, and now I’ll show you how I did it.

Last time we put a sprite  of a penguin on the screen . That might be cool, but if the penguin doesn’t move, it’s sort of meaningless.

There are several ways to move a sprite: SKActions, positing in update: and physics.

SKAction for animation

One is with an SKAction. In your code in initWithsize:, change your code to this:

//Initialize a sprite with a texture from a file.
SKSpriteNode *penguin = [SKSpriteNode spriteNodeWithImageNamed:@"gray penguin"];
penguin.position = CGPointMake(0, 0); = @"penguin"; //not required but VERY useful

SKAction *movePenguin = [SKAction moveTo:CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame)) duration:2.0];
[penguin runAction:movePenguin];
[self addChild:penguin];

We added a SKAction object. This will move the penguin from the left corner to the middle of the screen. SKAction objects are instructions on how to animate the sprite. They can be given once then let the sprite to without any more control needed.

This however puts the penguin right over the label. we can animate the label as well to move it 50 points up and out of the way of the sprite. Place this line just after the label.position assignment:

[myLabel runAction:[SKAction moveToY:myLabel.position.y + 50 duration:2.0]];

You can see another use of a SKAction in the code for the spaceship(s).

SKSpriteNode *sprite = [SKSpriteNode spriteNodeWithImageNamed:@"Spaceship"];
sprite.position = location;
SKAction *action = [SKAction rotateByAngle:M_PI duration:1];
[sprite runAction:[SKAction repeatActionForever:action]];
[self addChild:sprite];

Instead of a move, the spaceship uses  a rotation, another thing you can do with SKAction. Refer to the SKAction Class Reference for everything you can do with actions.

Frame by Frame Animation in update:

A second way is to control the sprite frame by frame. Remove the code for the space ship so it no longer is a distraction.

Comment out the following two lines in initWithSize:

//SKAction *movePenguin = [SKAction moveTo:CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame)) duration:2.0];
//[penguin runAction:movePenguin];

Now add the following in update:

CGPoint position = [[self childNodeWithName:@"penguin"] position];
    if (++position.y <= CGRectGetMidY(self.frame)){
        [[self childNodeWithName:@"penguin"] setPosition:CGPointMake(++position.x, ++position.y) ];

Now build and run. While with SKAction, the system figured out how to move the sprite, here we are moving the sprite frame by frame. Before the app renders every frame of animation, it checks with update: to know what it needs to render. At it’s fastest that will be 60 frames a second. Much of the brute force animation and logic happens here in update:

Before rendering every frame, we check the position of the sprite, and see if is halfway up the screen. if it is not we adjust the position one point up and to the right.

Tommorrow, we will look at the third type of animation: Physics.

Apple to Raspberry Pi: Python’s If

appleberryIn Objective-C, we would write an if statement like this:

if(number1 == number2){

in Python it is this:

if number1==number2 :

There is no parentheses required around the logical expression. Instead of the {} to show the block to run, a colon (:)  and indentations  find the code to run. Note that if you feel comfy putting parentheses around your logical expression, go ahead. Python will not complain.

A simple else statement is not more than that:

if (number1 == number2):
    print('not equal')

Python gets a little different when there is more than one else. Python uses the elif operator , which stands for else if.  Instead of this in XCode:

if (number1 == number2) {
else if(number1 > number2){
else if( number1 < number2){

We have in Python:

if number1 == number2:
elif number1 > number2:
elif number1 < number2:

Note the use of else here. Else is actually not required for chains of elif, but its use would be the same as default in a switch…case…default statement.

case 1:
case 2:
    //more stuff
case 3:{
    //even more stuff
    //none of that stuff, most likely an error.

The Slippy Flippy Challenge: How to Program a Basic Sprite in Sprite Kit.

The Slippy Flippy challenge was a success. The app was written in one week, debugged in another, and submitted it to the iTunes store in the third. Now a week of waiting to see what Apple thinks of it.

But how did I do it? Let’s make a version of Slippy Flippy. I’ll assume you have Xcode 5 at least, you are programming in iOS7 at least,  have loaded it on a compatible Mac and know how to do some basic things, like getting a template. For this app tutorial, you can use the free developer license, but I would strongly suggest spending the $99 and get a paid a developer’s license. Only with the paid license will you be able to test your apps on your devices and the simulator has a lot of problems with running sprite kit games.

Start by Loading the sprite kit template:

  • Start Xcode and you will get the intro window
  • Select Create a new Xcode project
  • Making sure the left column has iOS application selected, select the SpriteKitGame template. Click Next.
  • On the next window, fill in your information. we’ll call the game PenguinDemo. For the organization name put your name, and for the company identifier use a reverse name for your website. My website is so my identifier is com.shlomosdrash. For the Class prefix put SF. We will make the game for the iPhone this time, so the devices will be iPhone. click next. You will be asked where to save the files. I keep a folder called developer on my hard drive, so you might want to save it in a similar folder. Then Finish.
  • In the center of the window you will find the deployment info. Make it match the setting below to keep us in portrait. We’ll cover dealing with landscape in another blog piece.
  • Click the triangle run icon on the upper left corner of the window. The game will now run.
  • Tap the screen, and a spinning spaceship will show up
  • Stop the game by pressing the square stop button in Xcode.

Now we have set up and tested an environment for the sprite. Let’s add a sprite.

  •  Select the one SFMyScene.m file.
  •   In the initWithSize: method,  Under the line [self addChild:MyLabel]; Add the following code:
/* Make a penguin */
 //Declarations prior to making the sprite
CGFloat penguinWidth = 64.0;
CGSize penguinSize = CGSizeMake(penguinWidth, penguinWidth);
SKColor *penguinColor = [SKColor whiteColor];
//initialize the sprite node
SKSpriteNode *penguin = [SKSpriteNode spriteNodeWithColor:penguinColor 
//set properties
penguin.position = CGPointMake(100, 100); = @“penguin”;
//add to the scene tree
[self addChild:penguin];

Now run the app.  A white square representing your penguin appears at position 100,100.  This is how to make a sprite of a solid color.The first three lines of code are just declaring variables to use in our initialization of the sprite. We set two properties, position and name for the sprite. The position property  assignment makes our sprite show on the viewable area. Note the position is based on the center of the sprite, not a corner. Change the position from 100,100 to 0,0 and see what happens. Change it to another position afterwards. The name is not required, and there there are time it will not be needed, but it does allow for key searches for the sprite in the node tree, so it can be very useful.

However, most sprites, like the spaceship, are what are known as textures, and look a lot better than a white square. to add a texture easily, you need a .png graphic in the bundle.

  • gray penguinDownload the penguin at right to your desktop and save as gray penguin.png, or make your own 64×64 pixel image saved as a .png.
  • Drag the file for the image into the file list for the game.  Xcode will ask you if you want to import. Be sure to check the box to copy into the destination’s group folder.
  • Change the code to the following, commenting out all of our previous code:

        /* Make a penguin */
/* =============Removed for use of a SKTexture
         //Declarations prior to making the sprite;
         CGFloat penguinWidth = 64.0;
         CGSize penguinSize = CGSizeMake(penguinWidth, penguinWidth);
         SKColor *penguinColor = [SKColor whiteColor];
         //initialize the sprite node
         SKSpriteNode *penguin = [SKSpriteNode spriteNodeWithColor:penguinColor
         //set properties
        penguin.position = CGPointMake(100, 100); = @"penguin";
        //add to the scene tree
        [self addChild:penguin];
//Initialize a sprite with a texture from a file.
SKSpriteNode *penguin = [SKSpriteNode spriteNodeWithImageNamed:@"gray penguin"];
penguin.position = CGPointMake(100, 100); = @"penguin"; //not required but VERY useful
[self addChild:penguin];

We removed the required properties for the color sprite, and replaced them all with an image. The image sets the dimensions. Run this and you get a penguin on your game. iOS Simulator Screen shot Mar 25, 2014, 7.15.13 AM

Next post we will move the penguin.



The Slippy Flippy Penguin Challenge: A Tutorial on Sprite Kit

I stuck my foot in my mouth.

I’m now chewing vigorously and that is why you are reading this.
Photo Mar 19, 9 52 47 AMFor those who never heard of Flappy Bird, it was the game sensation nobody expected. It was a game that was very simple: a little bird moves up if you tap the screen, and falls due to gravity if you don’t. The game play is also simple: fly between two pipes without touching them and get a point. If you touch the pies or the ground, the game ends. While that seems easy, game play is very difficult.
The programming world was outraged when this jumped into #1 slot in iTunes and the developer began making $50,000 a day, far more than much slicker games with intensely realistic graphics. Then suddenly, the author pulled it from the stores. There was controversy. Not only was it simple, the graphics used  went out of style before the Gameboy. How did such a cheap game added to the store almost a year ago suddenly have such a meteoric rise? Apple’s App Store and Google Play hunkered down for an invasion of clones to the now defunct Flappy Bird, (which since I first wrote this is being resurrected ) and the author now says he pulled it because it was so addictive.
I was explaining the Flappy Bird controversy to a Friend. I claimed I could, actually anyone could, write Flappy Bird in a week. My friend dared me to try, and so I had ended up with a week-long challenge — write a Flappy Bird clone in a week then get it into the App store, with a variation or two.
Thus Slippy Flippy Penguin was born. If it gets into the App Store is another thing.
I didn’t want to write a clone – I prefer originality, like the game I’ve been working months to finish and is still under development. Besides Apple throwing it into a garbage heap in a second with the rest of the cheap knockoffs of the originall, I want to teach how to write games and how to program. I’m an educator at heart. Apple also last year made game programming a lot easier by introducing Sprite Kit to Xcode, the suite of programs used to write apps for iPhone and iPad. So a bigger challenge looms — can anyone write not just a clone but any game similar within a week’s time? If you have a Mac and can load Xcode, you are certainly welcome to follow along and write your own game. If you don’t, you may learn something too about a lot of what goes on behind the touchscreen of your iPhone.
The game itself is simple, which is what makes it such a great educational tool, and I’m not the only one doing this.

So Let’s see how to do this one part at a time.

From Apple to Raspberry Pi: Look ma! No Braces!!

I recently found a Post on Google Plus from that only a programmer would love:

Of course this is an endless debate of where to put the braces of a block of code.  C, C++, Java, JavaScript, Objective-C and even CSS uses those lovely curly braces.

Python does something totally mind tripping to me: it doesn’t use them. Here’s the same if statement in Python:

if condition:
    #a comment ...

In Python there is no braces:only white space. By convention there are four spaces. When there is no more indent, no more block.

Of course I do a lot of indentation in Xcode. But that is just documentation. In Python it’s syntax — and you can nest them too!

Another thing for me to swallow.

From Apple to Raspberry Pi: Variables and Types

RaspiI’m trying to learn Python for my new Raspberry Pi — though with all the app development I do that is not so easy. I need to wrap my head around some very different concepts.

The first concept that is obvious is the dynamic typing of Python. If you’ve used Objective-C or C, those are static typed languages. At compile time We set the variable  for life of the variable that type.   I’m used to writing in Objective C:

float number = firstNumber + secondNumber;
BOOL isThisTrue = 5 > 6;
NSInteger count = 0;

In Python that same declaration would be:

number = first_number + 1.23
is_this_true = 5>6
count = 0

It doesn’t matter if you want a integer, float, boolean or even string, that works. Also notice the lack of semicolon. There are no termination characters in Python like C, C++, or Objective C. Finally, the variable convention is underscores instead of capitalization.

While just missing a declaration is no big deal, in Python this is acceptable code:

number = first_number + 1.23
number = 5>6
number = 0
number = 'My number is 0'

The variable number  is successively a float, bool, integer and a string. For new programmers, this is probably is nothing to care about. For someone used to typing everything, it’s really annoying and took me a minute to get used to the difference.

In particular,  while coding I have to be very careful with the type I assign a variable.  Unlike Xcode giving us warnings about type there are no warning because everything is valid. This can lead to some unexpected bugs.

Fortunately, to prevent some of these there is casting. The functions int(x),float(x),bool(x) among others will cast to a type. There is also type checking. the type(x), and isInstance(object,classInfo) will also check classes and types.

Some people like dynamic typing, some don’t. When using Python, it is something that one will have to think about.