Need a unique gift idea?
A Pastebin account makes a great Christmas gift
SHARE
TWEET

Untitled

a guest Nov 17th, 2018 127 Never
Upgrade to PRO!
ENDING IN00days00hours00mins00secs
 
  1. import SpriteKit
  2.  
  3. func +(left: CGPoint, right: CGPoint) -> CGPoint {
  4.     return CGPoint(x: left.x + right.x, y: left.y + right.y)
  5. }
  6.  
  7. func -(left: CGPoint, right: CGPoint) -> CGPoint {
  8.     return CGPoint(x: left.x - right.x, y: left.y - right.y)
  9. }
  10.  
  11. func *(point: CGPoint, scalar: CGFloat) -> CGPoint {
  12.     return CGPoint(x: point.x * scalar, y: point.y * scalar)
  13. }
  14.  
  15. func /(point: CGPoint, scalar: CGFloat) -> CGPoint {
  16.     return CGPoint(x: point.x / scalar, y: point.y / scalar)
  17. }
  18.  
  19. #if !(arch(x86_64) || arch(arm64))
  20. func sqrt(a: CGFloat) -> CGFloat {
  21.     return CGFloat(sqrtf(Float(a)))
  22. }
  23. #endif
  24.  
  25. extension CGPoint {
  26.     func length() -> CGFloat {
  27.         return sqrt(x*x + y*y)
  28.     }
  29.  
  30.     func normalized() -> CGPoint {
  31.         return self / length()
  32.     }
  33. }
  34.  
  35. class GameScene: SKScene {
  36.  
  37.     struct PhysicsCategory {
  38.         static let none      : UInt32 = 0
  39.         static let all       : UInt32 = UInt32.max
  40.         static let fly   : UInt32 = 0b1
  41.         static let net: UInt32 = 0b10
  42.     }
  43.  
  44.     let net = SKSpriteNode(imageNamed: "net")
  45.     var fliesAdded = 0
  46.     var fliesCaught = 0
  47.     let maxFlies = 10
  48.     var level = CGFloat(1.0)
  49.     var gameKey: String?
  50.     var lives = 3
  51.     var levelCounter = 0
  52.  
  53.     override func didMove(to view: SKView) {
  54.  
  55.  
  56.  
  57.         backgroundColor = SKColor.white
  58.  
  59.         // Set up the properties of the net
  60.         net.scale(to: CGSize.init(width: net.size.width/10, height: net.size.height/10))
  61.         net.physicsBody = SKPhysicsBody(rectangleOf: net.size)
  62.         net.physicsBody?.isDynamic = false
  63.         net.physicsBody?.categoryBitMask = PhysicsCategory.net
  64.         net.physicsBody?.contactTestBitMask = PhysicsCategory.fly
  65.         net.physicsBody?.collisionBitMask = PhysicsCategory.none
  66.         net.position = CGPoint(x: size.width * 0.5, y: size.height * 0.1)
  67.         // 4
  68.         addChild(net)
  69.  
  70.         physicsWorld.gravity = .zero
  71.         physicsWorld.contactDelegate = self
  72.  
  73.         self.isPaused = false
  74.         run(SKAction.run(addFly))
  75.  
  76.         let backgroundMusic = SKAudioNode(fileNamed: "background-music-aac.caf")
  77.         backgroundMusic.autoplayLooped = true
  78.         addChild(backgroundMusic)
  79.  
  80.         // Add a label for the score
  81.         let scoreLabel = SKLabelNode()
  82.         scoreLabel.fontColor = UIColor.black
  83.         scoreLabel.fontSize = 65
  84.         scoreLabel.name = "scoreLabel"
  85.         scoreLabel.position = CGPoint(x: size.width/2, y: size.height/2);
  86.         scoreLabel.text = "0";
  87.         self.addChild(scoreLabel)
  88.  
  89.         // Add a label for the level
  90.         let levelLabel = SKLabelNode()
  91.         levelLabel.fontColor = UIColor.black
  92.         levelLabel.fontSize = 32.5
  93.         levelLabel.name = "levelLabel"
  94.         levelLabel.text = "level (Int(level))"
  95.         levelLabel.horizontalAlignmentMode = .left
  96.         levelLabel.verticalAlignmentMode = .top
  97.         levelLabel.position = CGPoint(x: 0, y: self.size.height)
  98.         self.addChild(levelLabel)
  99.  
  100.         // Add a label for the lives
  101.         let livesLabel = SKLabelNode()
  102.         livesLabel.fontColor = UIColor.black
  103.         livesLabel.fontSize = 32.5
  104.         livesLabel.name = "livesLabel"
  105.         livesLabel.text = "3/3 lives"
  106.         livesLabel.horizontalAlignmentMode = .right
  107.         livesLabel.verticalAlignmentMode = .top
  108.         livesLabel.position = CGPoint(x:self.size.width, y:self.size.height)
  109.         self.addChild(livesLabel)
  110.  
  111.         // Get the starting level
  112.         let urlComp = NSURLComponents(string: "---")!
  113.         let params = [URLQueryItem(name: "UserName", value: (UIApplication.shared.delegate as! AppDelegate).userName)]
  114.         urlComp.queryItems = params
  115.         var request = URLRequest(url: urlComp.url!)
  116.         request.httpMethod = "GET"
  117.  
  118.  
  119.         let task = URLSession.shared.dataTask(with: request) { data, response, error in
  120.             do {
  121.                 let result = try JSONDecoder().decode(LevelResponseObject.self, from: data!)
  122.                 let userHighestLevel = Int(result.level) ?? 1
  123.                 if userHighestLevel > 5 {
  124.                     self.level = CGFloat(userHighestLevel) - 5.0
  125.                 }
  126.                 else {
  127.                     self.level = CGFloat(userHighestLevel)
  128.                 }
  129.                 if let levelLabel = self.childNode(withName: "levelLabel") as? SKLabelNode {
  130.                     levelLabel.text = "level (Int(self.level))"
  131.                 }
  132.             } catch {
  133.                 print(error)
  134.             }
  135.  
  136.         }
  137.  
  138.         task.resume()
  139.  
  140.     }
  141.  
  142.  
  143.  
  144.     func touchDown(atPoint pos : CGPoint) {
  145.         //net.position = CGPoint(x: pos.x, y: size.height * 0.1)
  146.     }
  147.  
  148.     func touchMoved(toPoint pos : CGPoint) {
  149.  
  150.         //net.position = CGPoint(x: pos.x, y: size.height * 0.1)
  151.  
  152.     }
  153.  
  154.     func touchUp(atPoint pos : CGPoint) {
  155.  
  156.     }
  157.  
  158.     override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
  159.  
  160.     }
  161.  
  162.     override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
  163.         for touch: AnyObject in touches {
  164.             let touchLocation = touch.location(in: self)
  165.  
  166.             net.position = CGPoint(x: touchLocation.x, y: size.height * 0.1)
  167.  
  168.         }
  169.     }
  170.  
  171.     override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
  172.  
  173.     }
  174.  
  175.     override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
  176.  
  177.     }
  178.  
  179.     override func update(_ currentTime: TimeInterval) {
  180.         // Called before each frame is rendered
  181.     }
  182.  
  183.     // MARK: Private functions
  184.  
  185.     func addFly() {
  186.  
  187.  
  188.             let origin = (UIApplication.shared.delegate as! AppDelegate).dataOrigin
  189.  
  190.             let urlComp = NSURLComponents(string: "---")!
  191.             let params = [URLQueryItem(name: "Origin", value: origin)]
  192.             urlComp.queryItems = params
  193.             var request = URLRequest(url: urlComp.url!)
  194.             request.httpMethod = "GET"
  195.  
  196.  
  197.             let task = URLSession.shared.dataTask(with: request) { data, response, error in
  198.                 do {
  199.                     let result = try JSONDecoder().decode(ResponseObject.self, from: data!)
  200.                     let rows = result.items[0].Data.components(separatedBy: ";")
  201.                     let firstPoint = Double(rows[0]) ?? 0.0
  202.                     //let xCoords = rows.map{ CGFloat(NSString(string: $0).doubleValue - firstPoint)*self.size.width/157.4*2 + self.size.width/2 }
  203.                     let xCoords = rows.map{ self.size.width/(1+exp(-(CGFloat(NSString(string: $0).doubleValue - firstPoint)/10)))} // increasing the denominator in the exponential will make the relationship more linear, decreasing it will exaggerate moves near to the center
  204.                     self.gameKey = result.items[0].Key
  205.  
  206.                     self.fliesAdded += 1
  207.  
  208.                     // Create sprite
  209.                     print("New Fly")
  210.                     print("Level (self.level)")
  211.                     let fly = SKSpriteNode(imageNamed: "fly")
  212.                     fly.scale(to: CGSize.init(width: self.size.width/20, height: fly.size.height/fly.size.width*self.size.width/20))
  213.  
  214.                     fly.physicsBody = SKPhysicsBody(rectangleOf: fly.size)
  215.                     fly.physicsBody?.isDynamic = true
  216.                     fly.physicsBody?.categoryBitMask = PhysicsCategory.fly
  217.                     fly.physicsBody?.contactTestBitMask = PhysicsCategory.none
  218.                     fly.physicsBody?.collisionBitMask = PhysicsCategory.none
  219.  
  220.                     // Position the fly slightly off-screen along the top edge,
  221.                     // in the middle of the x axis
  222.                     fly.position = CGPoint(x: self.size.width/2, y: self.size.height + fly.size.height/2)
  223.  
  224.                     // Add the fly to the scene
  225.                     self.addChild(fly)
  226.  
  227.                     var flightSequence: [SKAction] = []
  228.  
  229.                     var currentY = fly.position.y
  230.                     var currentX = fly.position.x
  231.  
  232.                     let yDistanceToTravel = currentY - (self.net.position.y + self.net.size.height/2)
  233.                     let yIncrement = yDistanceToTravel / CGFloat(xCoords.count - 1)
  234.  
  235.                     var duration = CGFloat(8.28)/CGFloat(xCoords.count - 1)
  236.                     duration = duration/(1.0 + self.level/10)
  237.  
  238.                     // Create a sequence of moves for the fly
  239.                     for targetX in xCoords {
  240.                         // Set the parameters for the move
  241.  
  242.                         let targetY = currentY - yIncrement
  243.                         let flyTurn = SKAction.rotate(toAngle: -atan((targetX-currentX)/(targetY-currentY)), duration: 0.0, shortestUnitArc: true)
  244.                         flightSequence.append(flyTurn)
  245.                         let flyMovement = SKAction.move(to: CGPoint(x: targetX, y: targetY), duration: TimeInterval(duration))
  246.                         flightSequence.append(flyMovement)
  247.                         currentY = targetY
  248.                         currentX = targetX
  249.                     }
  250.  
  251.  
  252.  
  253.                     // After the fly passes the net send it vertically down
  254.                     let flyTurn = SKAction.rotate(toAngle: 0.0, duration: 0.0, shortestUnitArc: true)
  255.                     flightSequence.append(flyTurn)
  256.                     let flyMovement = SKAction.move(to: CGPoint(x: currentX, y: -fly.size.height/2), duration: TimeInterval(duration))
  257.                     flightSequence.append(flyMovement)
  258.  
  259.                     // Remove the fly after it passes the net and end the game
  260.                     let flightOver = SKAction.run() { [weak self] in
  261.                         guard let `self` = self else { return }
  262.                         if (self.gameKey != nil){
  263.                             self.recordDistance(fly: fly, net: self.net, gameKey: self.gameKey!, level: self.level, win: false)
  264.                         }
  265.                         fly.removeFromParent()
  266.                         self.gameOver()
  267.                     }
  268.                     flightSequence.append(flightOver)
  269.  
  270.                     fly.run(SKAction.sequence(flightSequence))
  271.  
  272.                 } catch {
  273.                     print(error)
  274.                 }
  275.  
  276.  
  277.             }
  278.  
  279.             task.resume()
  280.  
  281.  
  282.     }
  283.  
  284.     func gameOver() {
  285.  
  286.         if (lives == 1) {
  287.             let reveal = SKTransition.flipHorizontal(withDuration: 0.5)
  288.             let scoreScene = ScoreScene(size: self.size, score: fliesCaught, level: Int(level))
  289.             view?.presentScene(scoreScene, transition: reveal)
  290.         }
  291.         else {
  292.             lives = lives - 1
  293.             if let livesLabel = self.childNode(withName: "livesLabel") as? SKLabelNode {
  294.                 livesLabel.text = "(lives)/3 lives"
  295.             }
  296.             addFly()
  297.         }
  298.     }
  299.  
  300.  
  301.     func flyCaught(fly: SKSpriteNode, net: SKSpriteNode, gameKey: String?) {
  302.  
  303.         if (gameKey != nil) {
  304.             recordDistance(fly: fly, net: net, gameKey: gameKey!, level: self.level, win: true)
  305.         }
  306.  
  307.         fly.removeFromParent()
  308.  
  309.         fliesCaught += 1
  310.         //print("Score = (fliesCaught)")
  311.         if let scoreLabel = self.childNode(withName: "scoreLabel") as? SKLabelNode {
  312.             scoreLabel.text = "(fliesCaught)"
  313.         }
  314.         if levelCounter == 4 {
  315.             levelCounter = 0
  316.             level = level + 1.0
  317.             if let levelLabel = self.childNode(withName: "levelLabel") as? SKLabelNode {
  318.                 levelLabel.text = "level (Int(level))"
  319.             }
  320.         }
  321.         else {
  322.             levelCounter = levelCounter + 1
  323.         }
  324.         addFly()
  325.     }
  326.  
  327.     func recordDistance(fly: SKSpriteNode, net: SKSpriteNode, gameKey: String, level: CGFloat, win: Bool) {
  328.         let distance = fly.position.x - net.position.x
  329.         //print("Distance to center of net = (distance)")
  330.  
  331.         // prepare json data
  332.  
  333.         let json: [String: Any] = ["UserName": (UIApplication.shared.delegate as! AppDelegate).userName,
  334.                                    "DataKey": gameKey,
  335.                                    "Level": Int(level),
  336.                                    "Win": win,
  337.                                    "DistanceToCenter": distance,
  338.                                    "ScreenWidth": self.size.width]
  339.  
  340.         let jsonData = try? JSONSerialization.data(withJSONObject: json)
  341.  
  342.         // create post request
  343.         let url = URL(string: "---")!
  344.         var request = URLRequest(url: url)
  345.         request.httpMethod = "POST"
  346.  
  347.         // insert json data to the request
  348.         request.httpBody = jsonData
  349.  
  350.         let task = URLSession.shared.dataTask(with: request) { data, response, error in
  351.             guard let _ = data, error == nil else {                                                 // check for fundamental networking error
  352.                 print("error=(String(describing: error))")
  353.                 return
  354.             }
  355.  
  356.             if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
  357.                 print("statusCode should be 200, but is (httpStatus.statusCode)")
  358.                 print("response = (String(describing: response))")
  359.             }
  360.         }
  361.  
  362.         task.resume()
  363.  
  364.     }
  365.  
  366. }
  367.  
  368. extension GameScene: SKPhysicsContactDelegate {
  369.     func didBegin(_ contact: SKPhysicsContact) {
  370.         // 1
  371.         var firstBody: SKPhysicsBody
  372.         var secondBody: SKPhysicsBody
  373.         if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
  374.             firstBody = contact.bodyA
  375.             secondBody = contact.bodyB
  376.         } else {
  377.             firstBody = contact.bodyB
  378.             secondBody = contact.bodyA
  379.         }
  380.  
  381.         if ((firstBody.categoryBitMask & PhysicsCategory.fly != 0) &&
  382.             (secondBody.categoryBitMask & PhysicsCategory.net != 0)) {
  383.             if let fly = firstBody.node as? SKSpriteNode,
  384.                 let net = secondBody.node as? SKSpriteNode {
  385.                 //print("Collision with net")
  386.                 if fly.position.y > net.position.y + net.size.height/2 {
  387.                     //print("Fly Caught")
  388.                     flyCaught(fly: fly, net: net, gameKey: gameKey)
  389.                 }
  390.             }
  391.         }
  392.     }
  393. }
  394.  
  395. struct ResponseObject: Decodable {
  396.     let items: [RouteItem]
  397. }
  398.  
  399. struct RouteItem: Decodable {
  400.     let Key: String
  401.     let Origin: String
  402.     let Data: String
  403. }
  404.  
  405. struct LevelResponseObject: Decodable {
  406.     let level: String
  407. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top