Showing posts with label sqlite. Show all posts
Showing posts with label sqlite. Show all posts

Tuesday, 17 June 2014

iOS Sprite Kit Game (Luke's Paddle Tree Game)

Activities @ Lynda - 




Screen Recording in iPhone Simulator


iOS Game Dev with Sprite Kit with Simon Allardice 
    (thanks Lynda for an awesome course!!) DONE
Screenshots of My First Game (Adapted from Copyright Lynda.com Tutorial)
  • GitHub Link: Luke's Breaking Bricks iOS Sprite Kit Game
  • Instructions: 
    • Touch and hold the bottom Paddle to play and prevent it falling. 
    • Move left and right to stop the ball hitting the bottom. 
    • Pause feature activates if you let go of paddle! Touch again to Unpause.
    • Destroy upper bricks to cause Tree to fall down. 
    • Win if Tree touches bottom of screen (tough luck if you deflect it elsewhere haha)
    • Lose if bottom Paddle or Ball touches bottom of screen.
    • Note: The paddle rapidly impulses automatically, so the ball is propelled faster with each contact with the paddle (brace yourself!)
    • Note: Win screen Screenshot not shown (you have to Win to see it!!!), Audio for winning was prepared by yours truly :)
  • Wondering how I preparing the game? It took under 2 days to prepare this game. The purpose of preparing it was to learn iOS Sprite Kit fundamentals programming in Objective-C using Xcode. Most of the code used to prepare the game came from following the Lynda.com course video. I added the following extensions to the game of my own in order to test the framework, but I expended minimal effort in doing so:
    • Custom background (simply a few random coloured brush strokes in Photoshop)
    • Custom sounds (silly 'You Win' and 'You Lose' sounds recorded using Quicktime Player)
    • Custom particle effects (simply replaced the particle effect snow flakes with an image of my head and slightly modified the effect in Particle Effects Editor)
    • Pause feature that activates when use stops touching screen (adapted from this post on Stackoverflow.com). Pause deactivates when the user touches the screen again
    • Tree shaped and coloured object and an animation sequence associated with it. The animation sequence throws the tree it into the screen amongst the bricks at the start of each game. The animation helps it slowly wiggle out of them
    • 'You Win' screen which appears upon contact between the tree object and the bottom of screen (the user may need to destroy the bricks to make it fall)
    • Impulses are automatically applied to the paddle so when the user holds down on the paddle and moves it left and right, the paddle will rapidly spring up and down in this defensive approach, so that each time the ball bounces off the paddle the ball speed increases, which in turn rapidly increases the game difficulty so you can fail or win fast and often! Alternatively an offensive approach can be taken during gameplay if the user chooses to simply hold down on the paddle but does not move left or right, as this will cause the paddle to only rise upward toward the bricks (until the user moves their touch left or right again)
    • If you'd like to know more, please feel free to contact me! Please ensure that you appropriately credit me and the sources I used if you share.

Game Elements 
Scenes (Architecture)
  • Node Types (Sprite, Label, Video, Shape, Emitter, Crop, Effect, etc) 
  • Node Use (manipulable independent Visual Elements Creation and Artwork, Property Configuration, Scene Inclusion, Manipulation, Drawing Order), FPS 
  • Node Association and Inheritance
  • Node Positioning and Coordinate System
    • Anchor Points of Scene and Nodes (Default to Parent Scene)
    • CGPoint (Core Graphics framework) (Explicit and Inline Creation)
  • Physics World (connect and configure different Scene {gravity, zero gravity} and Node Physics Body Properties) 
    • Physics Bodies (Volume-based (Default is Dynamic Volume or use Static) {simple Draw Path and Play-Testing for complex shapes to minimise Performance impact} , Edge-based). Each one has Bitmask Properties
      • categoryBitMask (Turned On by Default, each Physics Body can belong to multiple Categories and belong to all by Default)
      • collisionBitMask (Turned On by Default, cross-references all Categories where Physics Body should Register a Collision and provide notification of an event)
      • contactBitMask (Turned Off by Default, cross-references all Categories where Physics Body should Register a Contact and provide notification of an event)
    • Physics Body Properties (Mass, Density, Friction {object resistance at collision}, Linear Damping {object resistance moving across space}, Restitution {object bounciness at collision 0 to 1.0f}, Angular Damping, Velocity, etc)
    • Vectors (Magnitude {Force, Impulse}, Direction)
    • Touch Events 
    • Flexibility (Rotation Orientation Compatibility)
    • Collisions (causes them to bounce on impact, and prevents intersection of objects)
    • Contact (apply manually with custom code to be informed when touch detected between objects and apply logic to event)
      • didBeginContact and didEndContact  (reacts to contact using SKPhysicsContactDelegate Protocol)
    • Categories (meaningful Groupings of objects Defined for association with different Physics Body Objects, where Bitmasks are used to describe the actions upon touch between objects of different Categories {inform us, allow or disallow cross-over, bounce, nothing}, 32 Categories allowed to be toggled)
      • Bitwise Operators for defining Multiple Constants for each Categories
    • Landscape Orientation
      • CMD + Right Arrow (in Simulator)
    • Rendering/Game Loop 
      • update method (called at beginning of every frame)
      • didEvaluationActions method (check modifications after Sprite Kit evaluates actions and before any nodes changed are rendered to frame)
      • didSimulatePhysics methods (check mods of Physics Simulation but before affected nodes rendered to screen)
    • Texture Atlases (Manage Artwork Assets for Higher Performance by Grouping images)
      • Animation by Iterating Multiple Images
  • Game Play
    • Scene Transitions (Transition to Second Scene, Win and Lose Scene, Restart First Scene)
    • Sound Effects (SKAction in CAF format)
    • Convert to CAF Format (i.e. M4A from QuickTime Player to CAF Format File)
    • Apple Audio File Convert Tool use by type at Command-Line: 
                /usr/bin/afconvert -f caff -d LEI16 {INPUT} {OUTPUT}
    • Particle Systems (use Small Image and repeat Multiple times)
    • Particle Emitter controls effects under defined Particle Effect Rules using transitioning and Particle Emitter Inheritance to link gradually between nodes
    • Particle Emitter Editor (alternative to creating and setting properties of emitter node object with SKEmitterNode in code, instead simply define properties and save to SKS File for use to create Emitter Nodes)
    • iOS > New File > Resources > Sprite Kit Particle File
    • Actions (SKAction Class)
      • Methods with Reversible Actions
      • Combinations of Sequencing, Grouping, and Repeating Actions
      • Wait Action
  • Refactor 
    • Select Code Snippet > Right Click > Refactor > Extract 
Purchases:
Challenges:
  • Overcoming error "The model used to open the store is incompatible with the one used to create the store”?". 
    • Solution: Delete the SQL file in the apps documents directory
  • Display SQL syntax in Xcode Debugging Area
    • Solution: 
Menu > Product > Scheme > Edit Scheme > Arguments  "-com.apple.CoreData.SQLDebug 1"
  • Discovered how to overcome app always crashing (lost so much time trying to work this out) when attempting to save enum data to core data persistent store. I simply followed this Stackoverflow post from Paras Joshi to reset session and cache data in iPhone Simulator. Absolute lifesaver, this is now my favourite Xcode feature (how sad)!
         Menu > iOS Simulator > Reset Content and Settings

Sunday, 27 April 2014

Post WDI - iPhone App Sandbox, Data Management Persistence Mechanisms (Object Archiving, Core Data to SQLite)

iPhone Development (Xcode 5) (Cont'd)

iPhone App Sandbox and Data Management  DONE
  • Application Sandbox { restrictions (policy and technical) introduced by Apple to protect users from malicious apps harming their devices, and where all apps exist in a sandbox. violation cause for app rejection from App Store }
  • Object Archiving 
    • Object Graph { all references between interlinked web of objects in memory. used for Cocoa's Object Archiving (serialisation mechanism) where the object graph is stored to the file system and unarchived and read it back into memory to restore a session at the same point. Object Archiving Components include NSCoder object and NSCoding Protocol }
      • NSCoder { encode and decode archiving any object to NSCoding Protocol using "keyed encoding" where a key is provided for each instance var }
      • NSCoding Protocol 
      • Methods: 
        • initWithCoder { Decoding where key is provided and decoded instance var returned } 
        • encodeWithCoder { Encode all instance vars (using encodeObject:forKey, encodeInt:forKey, encodeBool:forKey, encodeDouble:forKey, encodeBytes:forKey) of object to store during archival. implemented with decision on instance vars of scalar type to encode or not encode (transient) } 
    • Archiving to File
      • archiveRootObject:toFile of NSKeyedArchiver (on applicationWillTerminate event)
    • Unarchiving from File
      • unarchiveObjectWithFile method from NSKeyedUnarchiver(on viewDidLoad event)
    • Data Storage Options
      • Library/Preferences Directory { access indirectly with NSUserDefaults API }
      • Library/Caches Directory { direct file manipulation, cache retrieved data, persists between launches, improves performance }
      • Documents Directory { direct file manipulation, main location to store, backed up when synced }
      • tmp Directory { direct file manipulation outside devices limited volatile memory without persisting between launches of app }
    • File Paths 
      • NSSearchPathForDirectoriesInDomains { Core Foundation function returns multiple directories in NSArray with NSStrings extracted with objectAtIndex }
      • stringByAppendingPathComponent { joins path fragments }
    • Interface Elements
      • Flexible Space Bar Button
  • Core Data 
    • Dfn: Object-Relational Mapping (ORM) framework (handles conversion of data to and from objects in the app and relational data in a database) providing management and persistence of in-memory object graphs comprising multi-level undo management, data validation, data consistency across independent data accessors, efficient filtering with indexing, sorting, and searching object graphs, and persistence between invocations to various data repositories 
    • Uses: wraps the SQLite database and relational database (alternative to using SQL and SQLite API directly) to perform querying and data management functions of CRUD (create, read, update, delete)
    • Alternatives to SQLite Repository 
      • Uses: Core Data features (undo support, object schema versioning) without need for relational databases
      • Binary File Format { same limits on large data sets as Object Archiving }
      • In-Memory Implementation { no persistence between app invocations }
    • Concepts of Core Data
      • Managed Object Context { subset of persistent objects used by app at a point in time and containing the object graph. Core Data notices changes to the objects and persists changes to the database when save is called }
      • Managed Object { object managed by Core Data that can be added or removed from object graph resulting in Core Data performing inserts and deletes w database. changes to attributes and relationships of managed objects results in Core Data performing update operations to database }
      • Managed Object Model { object-relational schema, description of Entities persisted via Core Data. it's a mapping between an object in Objective-C and an Entity as it will be stored as rows in a database table in SQLite }
        • Xcode Data Modelling Tool { for .xcdatamodel files }
      • Entity 
        • Dfn: model of managed object containing only parts of object that Core Data will be persisting
        • Model Types:
          • Object Attributes { for persisting }
          • Relationships and Other Entities { stored to form a persistent object graph }
      • Persistent Stack { parts of Core Data that interact with a data repository like SQLite }
    • Core Data Application Template 
      • Dfn: boilerplate code that contains additional properties and actions to allow the Core Data application to interact with the managed object context through its application delegate 
      • Features:
        • @dynamic construct { tells compiler missing property getters and setters in implementation file will be provided by superclass NSManagedObject at runtime } 
        • managedObjectContext property { Core Data managed object context for passing to controllers subview in the app window upon applicationDidFinishLaunching }
      • CRUD (Create, Read, Update, Delete)
        • insertNewObjectForEntityForName:inManagedObjectContext method of NSEntityDescription { Create. arguments include name of Entity NSString from managed object model, and reference to managed object context }
        • NSFetchRequest instance in viewDidLoad method { Fetch. with NSEntityDescription to specify type of Entity to fetch, returns NSMutableArray of managed objects
        • hasChanges used by managed object context to report any changes to managed objects that were tracked and save in the applicationWillTerminate method 
        • deleteObject method of NSManagedObjectContext is passed managed object to delete
        • Note: NSUInteger vs NSNumber (scalar integer vs actual object)
Curiosity:



Links: