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 {
    print(my_string)
}

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 {
    print(my_string)
}

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?

a=['Mary','had','a','little','lamb']

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

From Apple to Raspberry Pi: While Loops

appleberry
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:
        break

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.name = @"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){
    NSLog(@"equal");
}

in Python it is this:

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

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('equal')
else:
    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) {
   NSLog(@"equal");
}
else if(number1 > number2){
    NSLog(@"greater");
}
else if( number1 < number2){
    NSLog(@"less");
else{
    NSLog(@"error");
}

We have in Python:

if number1 == number2:
    print('equal')
elif number1 > number2:
    print('greater')
elif number1 < number2:
    print('less')
else:
    print('error')

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.

switch(number2){
case 1:
    //stuff
    break;
case 2:
    //more stuff
    break;
case 3:{
    //even more stuff
    break;
default:
    //none of that stuff, most likely an error.
    break;
}

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 shlomosdrash.com 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 
                                      size:penguinSize];
//set properties
penguin.position = CGPointMake(100, 100);
penguin.name = @“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
         size:penguinSize];
         
         //set properties
        penguin.position = CGPointMake(100, 100);
        penguin.name = @"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.name = @"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 Codelect.net 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:
    Statements
    #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.

Adventures in Swift and iOS App Development