Settings

Theme

Flappy Bird in Swift

github.com

309 points by pjvds 12 years ago · 125 comments

Reader

gokhan 12 years ago

As a C# developer, I can read and understand the code without any issues. That's a good thing for Apple. I'm sure Objective-C is great but it's too foreign for me and didn't want to toy with it for fun, not worth the effort. But I can write an app or two with this one.

  • matthewmacleod 12 years ago

    I get where you're coming from - but in my experience, the barrier is totally psychological. Objective C isn't that unusual a language - the syntax is a bit foreign, but nothing that takes more than a couple of days to wrap your head around.

    You'll spend far more time getting to grips with Cocoa/Cocoa Touch.

    • untog 12 years ago

      the barrier is totally psychological

      Of course it is. It's certainly not a physical barrier. But psychological or not, other languages don't have a similar barrier.

      • robterrell 12 years ago

        > other languages don't have a similar barrier

        Lisps have the RPN psychological barrier. Python has the significant whitespace psychological barrier. etc. Any language can present someone with some psychological barrier.

        I think the OP's strongest point was, Objective-C the language is pretty trivial to learn quickly (after all, it's just C with message passing). You'll spend far longer trying to learn the Cocoa APIs than you will spend learning Objective-C-the-language.

        For instance, I decided to try to learn swift and SpriteKit at the same time. I spent far longer looking up methods on SKSpriteNode than I did looking up language constructs. (i.e. I assumed "let" was the same as in ES6 and couldn't figure out why the compiler was mad.)

      • matthewmacleod 12 years ago

        Okay, I meant more that there's not a skills barrier in terms of actually learning to use the language. The syntax can be intimidating, but once you've spent a couple of hours with it, it's not an issue any more.

        It's far more difficult to get to grips with how the APIs work.

    • WorldWideWayne 12 years ago

      That's my problem. I can't even find the entry point for this application. Looking at AppDelegate.swift I see an unused var (window) and that's it.

      • matthewmacleod 12 years ago

        @UIApplicationMain is the key there, from what I can see. An Objective C iOS app typically includes a main.m entry point which calls UIApplicationMain and passes the AppDelegate. This seems to have been removed in favour of what Swift is calling a "declaration attribute", which presumably does the same thing.

        In this sense, the code is even less clear than the Objective C implementation.

pajju 12 years ago

I just started exploring the Book: The Swift Programming Language by Apple Inc.

Link: https://itunes.apple.com/us/book/the-swift-programming-langu...

Hope it helps.

kevinwang 12 years ago

I guess Flappy Bird is now a tier 2 "hello world" :)

jashmenn 12 years ago

Author here - I didn't expect to see this here this morning. I'd intended to write a longer post :)

In any case, here's a few things I learned about swift yesterday building this. Please note that I have about 4 hours swift experience, so feel free to correct anything I say that's wrong.

1. To make properties on a class you simply declare the variable on the class e.g.:

    class GameScene: SKScene { 
      var bird = SKSpriteNode()
      // ...
    }
2. The APIs generally have shorter names and it's really nice. E.g.

    SKTexture* birdTexture1 = [SKTexture textureWithImageNamed:@"Bird1"];

becomes

    var birdTexture1 = SKTexture(imageNamed: "Bird1")

If I understand it correctly, any overloading `inits` basically look like calling the constructor on the class, whereas any class functions will be called like this:

    var flap = SKAction.repeatActionForever(animation)

3. You can put inline blocks and it's great

    var spawn = SKAction.runBlock({() in self.spawnPipes()})

4. The typing is really strong - this takes some getting used to. For instance, `arc4random()` returns a 32 bit unsigned integer. This means before you can use any operators on it you have to make sure you're using compatible types. e.g.

    var quarter = UInt32( self.frame.size.height / 4 )
    var y = arc4random() % quarter + quarter;
If we didn't use `UInt32` to convert `quarter` we'd get an error. After you get the hang of this, it's actually really nice.

5. I use `var` everywhere and I'm pretty sure I should be using `let` a lot more. I haven't worked with Swift enough to have a strong intuition about when to use either.

I should also mention that my code is just converted from Matthias Gall's code [1].

I also want to put in a shameless plug that the point of making this was to advertise the "Making Games with Swift" class that auser and I are building. If you're interested, put in your email here: https://fullstackedu.com

I intend to redo this more fully with Playgrounds. I've been looking for a way to teach kids programming for a while now (if you recall, auser and I built Choc [2] a few months back). I think Playgrounds in Swift are finally the tool we've been waiting for.

[1] http://digitalbreed.com/2014/how-to-build-a-game-like-flappy...

[2] http://www.fullstack.io/choc/

EDIT: added choc

  • sergejsb 12 years ago

    I don't have XCode to try it out, but according to the book, you can replace

      var spawn = SKAction.runBlock({() in self.spawnPipes()})
    
    with

      var spawn = SKAction.runBlock({self.spawnPipes()})
    
    or even

      var spawn = SKAction.runBlock() {self.spawnPipes()}
    
    or

      var spawn = SKAction.runBlock {self.spawnPipes()}
    
    EDIT: formatting for code
    • jashmenn 12 years ago

      This is awesome and I didn't know this. Thanks for posting it - I don't have much swift experience so I assume there are several things in the code that will be shown to be non-standard.

      • jonhohle 12 years ago

        > I don't have much swift experience…

        Considering the language has only been public for <36 hours, I would imagine effectively no one outside of Apple (and its Alpha partners) does.

        • leftcoaster 12 years ago

          Which will not stop recruiters from seeking candidates with 5 years experience in Swift.

    • kinghajj 12 years ago

      What about this?

        var spawn = SKAction.runBlock self.spawnPipes
      • anon4 12 years ago

        Heh. Reminds me of when I correct people for

          if var == true {...}
        
        or (and I have actually seen this)

          if (<expression> == true) {
              return true;
          } else {
              return false;
          }
        
        I sometimes think that simply giving those 5 lines to a person and observing if they make a face like you've handed them a bucket full of day-old fish is a better test for programming aptitude than anything.
        • josephlord 12 years ago

            if var == true {...}
          
          In some languages var might be truthy but not equal to true. The falsy values may be more of a problem at times.

          However in the strongly typed swift I don't think it will be a problem as I suspect (but haven't read/tested enough yet to confirm) that only false and nil will be falsy and that comparison with true will throw errors if var isn't of bool type.

          • josephlord 12 years ago

            Just tried it. In Swift:

              3 == true    // Give an error (operator overload doesn't cover this)
              true == 3    // Returns false
              nil == false // Returns false
            
            You can't use nil or integers directly in an if statement without a function to return a logic value.
          • anon4 12 years ago

            Yes, such languages exist, and even in C++ if (x == true) is different from if (x), given that x is any number kind other than boolean, but my comment was only for the case when the two would be equivalent.

        • lfuller 12 years ago

          I'd argue the second is clearer in many cases. Readability trumps conciseness any day.

          • MaulingMonkey 12 years ago

            I agree that readability trumps shortness of code. I want not for APL nor code run through a javascript minifier.

            But the branch and explicit boolean comparison are additional structural complexity (not just "verbosity") and invariably harms readability to me. Care give a poster child example for where it helps readability? Unless it's unclear <expression> results in a boolean - a problem better solved through better naming - code like this forces me to perform the equivalent simplification in my head to understand and reason about the code, a process fraught with error and distraction from my actual task.

          • the_af 12 years ago

            Really? In which cases would the previous example be clearer than

                return expression;
            
            What readability does the verbosity add?
      • sergejsb 12 years ago

        Are you sure this should work? I checked the grammar once more and it seems that closure-expression should always be enclosed in { ... }

  • kevin818 12 years ago

    I think just the fact that you were able to build a game with just 4 hours of learning a new language speaks volumes about Swift's barrier to entry. Well done!

    • na85 12 years ago

      I think it speaks more to the author's prowess, not to the fantastic magic powers of Apple's latest walled garden.

    • CmonDev 12 years ago

      Any up-to-date C# developer already knows Swift.

    • wingerlang 12 years ago

      But the code was just a port/convert, seems relatively non-trivial to do that in 4 hours.

      • tylermac1 12 years ago

        I supposed "relatively" is the key word here. To me, that'd be a great feat. To others, not that special.

  • Someone 12 years ago

    "I use `var` everywhere and I'm pretty sure I should be using `let` a lot more. I haven't worked with Swift enough to have a strong intuition about when to use either."

    I think you should type let everywhere, except when you cannot get away with it.

    So, it is var when declaring a loop variable. Elsewhere you almost always can introduce a new name. So, instead of

       X += 1
    
    do

       let newX = x + 1
    
    Those rules are too strict, but not much so, and you will learn the difference faster if you overcompensate.

    If you find yourself creating a newerX, a newestX, etc. you may be better of with a var, but chances also are that you are better of writing your code differently (for example can you iterate over a constant array of values instead of doing x+=1 a few times? If your function needs to create 10+ Local variables, can you factor out a function?)

  • sergejsb 12 years ago

    A couple more interesting swift features that seemed a bit weird to me after skipping through the reference:

    1. Strings, arrays and dictionaries are value types (like structs in C# - stored on stack, not on the heap) with special copying rules for arrays.

    2. Custom operators - can be defined as a sequence of "/ = - + * % < > ! & | ^ . ~" characters and made prefix, infix or postfix. There is an example in the reference that defines a prefix operator "+++" for vectors

matthewmacleod 12 years ago

Good work. I'll have to do 2048 instead, I guess :)

I'm quite impressed so far. Having been an Objective C and Ruby engineer, so far Swift seems to offer the best of both.

That said, OpenGL support doesn't appear to be finished yet.

stigi 12 years ago

If you're new to functional programming styles this swift project might be more relevant: https://github.com/maxpow4h/swiftz

diminish 12 years ago

I got mixed feelings about the language at first sight. I guess my mammalian brain recognizes languages based on the particular combination of the following naming decisions.

* func, function, fun, defun fu, funct

* CamelCase vs snake_case

* whitespace, semicolon or comma usage

* var, int/integer/uint64/Integer/

* choice of (), {}, [] or better (){a[]}

* import/include/require, class/class, override, self vs this, new vs Class()

PS: next time you design a new language just make a random unique combination of the above.

  • fdej 12 years ago

    > PS: next time you design a new language just make a random unique combination of the above.

    That's my impression whenever I see a new programming language too. Why would someone switch to your language if the syntax is just the same boring old syntax they've been using in another language?

    • pjc50 12 years ago

      Why would someone switch language if the familiar concepts have been given different names for no good reason?

      Use different syntax and naming for the things that are genuinely different about your language.

    • jaxytee 12 years ago

      Because in this case, it's an alternative to a language (Objective C) with a not so boring esoteric syntax.

    • fdej 12 years ago

      Since I'm being downvoted... please excuse my poor attempt at sarcasm.

      What I'm saying is that I sometimes get the impression that language designers randomly change up syntax just to make their language look different, and thus superficially more appealing to users. Just like any other kind of product.

    • Illotus 12 years ago

      It would be pretty weird to base language switching decision on syntax similarity.

      • collyw 12 years ago

        Do you see the amount of people that complain about Pythons white space? Plenty of people avoid it for that reason alone.

  • fit2rule 12 years ago

    >>mammalian brain

    Woof woof! I got one too. My view of Swift is: not a good enough reason not to continue using Lua for the same problem.

kclay 12 years ago

Always had a problem with Objective C, could never read it (Android Dev) but this right here is pretty impressive. I like the mixture of language features. But my only question, are you still locked to using an mac to develop for iOS. I guess since the language is closed source it depends on some osx libs at compile time.

  • craigching 12 years ago

    Yes, you still need a Mac to develop for iOS. Come to the dark side! :)

  • Tokala 12 years ago

    What is so hard about reading Objective-C? I've seen this as a very common thread with people celebrating the arrival of Swift.

    I'm not trying to be flippant and I understand that the named parameter format may throw some people for a loop, but I'm curious why it appears to be such a limiting factor in trying Objective-C.

LukeB_UK 12 years ago

From the GIF in the readme, it looks like collision detection is broken.

  • jashmenn 12 years ago

    I'm terrible at flappy bird - I can /sometimes/ get through the first pipe. Rarely.

    I didn't build the collision detection yet just b/c I actually think it's more fun to play this way.

    That said, we'll add it before too long.

ajanuary 12 years ago

This being the only code sample of swift I've seen, my overriding takeaway is that for the basic stuff it's remarkably similar to Objective-C with a lick of paint.

If people really take to swift, it'll be interesting to see if that's because it creates a shift in programming style, or because people really are just afraid of small syntactical differences.

  • weaksauce 12 years ago

    After skimming through the code and knowing that it was a job that took only four hours, it's very likely that this is just objective-c code written in swift(as the saying goes, you can write java in any language). It will take a bit more time to learn the idiomatic swift style and implementation.

  • jashmenn 12 years ago

    Part of the reason it looks like that is because I don't really know swift all that well. One of the great things we have in Swift is more functional features like closures, named functions, etc. I expect we'll see a lot of higher-order functions being used and that would clean it up a lot.

  • andybak 12 years ago

    Readability matters - maybe the Objective-C verbiage melts away once you're up to speed, but it certainly puts you off wanting to get there.

    • jurre 12 years ago

      I find obj-c super readable, other people don't? I mean, take two hours to get used to the bracket syntax for message sending and it's super readable although a bit verbose?

      • ktran03 12 years ago

        Same here.

        All you have to do is get over named parameters, square bracket message passing, and overall verbosity, and you know enough to read/understand Objective-C code.

        If you can get past those three differences, Objective-C is remarkably similar to Java and other OOP languages.

        Personally, I love the verbosity. The code pretty much just explains itself.

        Swift is a welcomed change though. I'm very optimistic and excited about the future of iOS going forward.

        • andybak 12 years ago

          Please take this in good humour but I couldn't resist:

          > All you have to do is get over named parameters, square bracket message passing, and overall verbosity

          Translation: "All you have to do is get over it's poor readability and it's quite readable!"

          > Objective-C is remarkably similar to Java and other OOP languages.

          Translation: "Objective-C is as readable as several other unreadable languages".

          ;-)

          Readability isn't about familiarity as much as it's about clarity and a lack of boilerplate. Verbosity is in most cases the antithesis if readability. I think there can be exceptions (maybe some verbose DSLs that manage to map cleanly from your brain to the code on the page) but if the verbosity comes from boilerplate or visual clutter then verbosity is a strong point against.

    • ajanuary 12 years ago

      That's always been the intuition. If swift maintains a distinct Objective-C style but with more approachable syntax, then that suggests the intuition is true.

  • threeseed 12 years ago

    Swift is definitely more approachable than Objective-C for new developers.

    I would imagine that is very on the reasons for creating it.

    • ajanuary 12 years ago

      For new developers, or for developers coming from other languages?

      I think a lot of the trouble people have with starting to develop apps for Apple platforms actually comes from trying to figure out the APIs and style, while at the same time battling against unfamiliar syntax. From the little I've seen, Swift doesn't change the first part of that very much.

      • eddieroger 12 years ago

        I think both. I have a young cousin who is starting to show interest in programming, and when I think of showing her Objective-C, I grimace inside because it has taken me so long to become comfortable with it, and I'm coming from other languages and years of experience. But I think I can walk through Swift with her, and we can learn it at the same time - me bridging the gaps because I come from another language, and her learning how to program for the first time.

      • threeseed 12 years ago

        Both. The APIs and style sure are issues.

        But there are plenty of language constructs which exist only in Objective-C.

QuadDamaged 12 years ago

I am really intrigued by the obj-c interop capability of swift, namely interactions between blocks and closures / anonymous functions.

I can see my AFNetworking code becoming much, much more readable now, without the need to @weakify/@strongify self on both sides of the block, but just add a blanket '[unowned self] in' inside the closure.

barrystaes 12 years ago

Swift is a new programming language. Does this implementation also use Metal? What is the Scene Kit relation to Metal?

  • jemeshsu 12 years ago

    SpriteKit and SceneKit is targeting casual games. Metal is an API that is close to GPU and is meant to replace OpenGL for console level games.

  • M4v3R 12 years ago

    This only uses SpriteKit, for 2d graphics. SceneKit is for 3d stuff.

k-mcgrady 12 years ago

This may be a stupid question but is the language in some way tailored to game programming? Apple's examples at WWDC were game companies, their coding demo was a game, and this is the first project I've seen written in it - and it's a game.

  • ajanuary 12 years ago

    Games make easy examples because you can do a simple render loop and input. Most people understand the concept of sprites and basic animation.

    Apple's UI frameworks are all MVC based, which means multiple classes and apple specific UI terminology.

    • eddieroger 12 years ago

      Additionally, they're a quick route between code and something visual. If the demo yesterday had been "look how easy I can make a tableview", no one would have cared much, but the circus scene had motion, lights, and barely any code. People love spectacle.

      That reads a lot more sarcastic than it should have, but it's unfortunately true. Swift was announced in front of a room of people who needed to be convinced to start migrating from something they all know (ObjC) in favor of something new, so you have to win them over quick.

  • mitchty 12 years ago

    I think you're missing this is building off of other things that are meant for games like scene kit etc....

    The language isn't tailored to it, but there are things it makes easy that are. If that makes any sense.

  • wging 12 years ago

    There's also a new graphics API, 'Metal', though I don't know if that has anything to do with it.

ktg 12 years ago

Flappy Bird in Racket | https://github.com/soegaard/flappy-bird

  • dukerutledge 12 years ago

    Man, apparently dr racket format looks like a hot mess.

    • soegaard 12 years ago

      A normal Racket file is a straight forward text file.

      In Flappy Bird I used inline images, as in (define bird <the-bird-image-here> ) This makes it simple to distribute the source and images as a single file, but unfortunately the resulting file is not pretty.

      In short: to see the source open it in DrRacket.

kayoone 12 years ago

pretty neat! I am not an iOS developer but if i understand correctly this uses the new Sprite Kit stuff included in iOS8 for 2d rendering right ? Is this a threat to existing 2d/game engines ? Not sure where SpriteKit integrates into the existing stack for making a game.

  • babuskov 12 years ago

    Looks like a good way for Apple to lock the developers to their platform. In past glory days people used to make games for iOS first and consider porting to Android much later. These days developers think cross-platform from the start, esp. since it's much easier to test waters and iterate on Android. I guess that SpriteKit is an attempt to stop this trend. Smart move by Apple IMHO, but perhaps a little bit too late.

    • chillingeffect 12 years ago

      I see your polite, critical, level-headed opinion has been down voted into gray dust, despite my meager support. I entreat those who pass by here to drink in my own following opinion: I think you're operating from the democratic ideal that "all people will opine equally about all topics at all times."

      The departure from this ideal, I've discovered, is that there is a "Practical Crowd" who will swoop through when questions of practicality, such as cross-platform compatibility come up. Their opinions will be nearly absolute and they will be all but intolerant of the "weak" who claim that merely targeting Windows, Linux and OSX is "enough." They will justify with numerous cherry-picked examples from history, starkly, if not carefully, considered arguments toward the future, and with evidence of grit on their fingers from the present, in which the particular ideal is espoused. At that time, they will down vote anyone deviant enough to cheer for Swift.

      Yet, currently my friend, the Apple Crowd has the floor. Any practical concerns are scheduled after the celebration. Think of this when you read the next cross-platform thread and see the Apple fans trying to get a point in edgewise amongst The Practical. There is very little global reality, mainly local basins of morality.

  • austinz 12 years ago

    SpriteKit was released last year with iOS 7. It's a pretty much self-contained 2D game engine like Cocos2D, including stuff like physics simulation. iOS 8 is going to ship with SceneKit, which is similar but for simple 3D games.

alexcroox 12 years ago

Well that didn't take long...

Zelphyr 12 years ago

If Swift has namespaces why are classes still prefixed? "SKScene" for example.

brador 12 years ago

Does this need IOS8 to run?

Is there a way to get that without being a signed up dev with Apple?

  • martingordon 12 years ago

    Apple has stated that Swift apps can target iOS 7/8 and Mavericks/Yosemite. You do need access to the dev program in order to get access to the Xcode 6 beta.

  • alexbilbie 12 years ago

    It shouldn't need iOS 8 to run because it compiles down to the same native code that Objective-C apps and Rubymotion apps do.

  • craigching 12 years ago

    > Is there a way to get that without being a signed up dev with Apple?

    You need to be in the iOS developer program to get iOS 8 beta.

seanhandley 12 years ago

Someone needs to add Swift to the linguist gem

martinvol 12 years ago

OK, that was fast!

joeyspn 12 years ago

2k+ Github stars in less than 24h? OMG

hellbreakslose 12 years ago

Swift looks fine, the only thing I don't like its that is for Apple only products... that kinda defeats the purpose of having a programming language.

  • craigching 12 years ago

    > Swift looks fine, the only thing I don't like its that is for Apple only products... that kinda defeats the purpose of having a programming language.

    Tell that to Microsoft ;)

  • chipotle_coyote 12 years ago

    There are many programming languages that in practice tend to be locked to one platform or another. C# isn't only on Windows and Objective-C isn't only on iOS, but very few people learn either of those languages with the expectation of "write once, run anywhere." (I've found that generally people who use C# on other platforms do so because they already know C# and don't want to learn something else.)

    On principle I'd like to see Apple put Swift under a free software license of some kind and ideally make a cross-platform reference implementation, but realistically, even if they do that it's unlikely to ever get wide use anywhere but Apple products.

  • unfamiliar 12 years ago

    You can write code for non-apple products, its just that the libraries are lacking. I don't see how this defeats "the purpose of a programming language".

  • hellbreakslose 12 years ago

    apple fanboys keep downvoting!

  • mnem 12 years ago

    Good luck compiling Objective-C on Windows :)

    • mdellabitta 12 years ago

      Pretty sure you can compile Objective-C on Windows, since gcc supports it, and OpenStep worked on Windows.

      It's Apple's libraries you don't get on Windows.

    • matthewmacleod 12 years ago
      • mnem 12 years ago

        Ye-es, except:

          "Apple has recently added new functionality to their runtime, including built-in exception handling, etc. Hopefully these will be ported to the GNU runtime in the future."
        
        My general point is that programming languages don't have to be cross platform to be useful. Certainly handy from a developer's point of view, but just a convenience.
napolux 12 years ago

FAST AS HELL! :P Thanks a lot!

supergeek133 12 years ago

Why.

nakovet 12 years ago

I was curious when I saw a tests folders, but it was just auto-generated files with no actual tests. =(

nicolime 12 years ago

Share the latest about Swift here! Be part of the biggest page for the language. Looking for admins. https://www.facebook.com/swiftofficial

Keyboard Shortcuts

j
Next item
k
Previous item
o / Enter
Open selected item
?
Show this help
Esc
Close modal / clear selection