swiftの学習(xcodeのゲームアプリサンプル)
コード部分のみ
GameScene.swift
// // GameScene.swift // swiftSampleGame1 // import SpriteKit class GameScene: SKScene { var turn_o = true required init(coder aDecoder: NSCoder) { fatalError("NSCoder not supported") } override init(size: CGSize) { super.init(size: size) anchorPoint = CGPoint(x: 0, y: 0) let background = SKSpriteNode(imageNamed: "bg") background.position = CGPoint(x: 0, y: 0) background.anchorPoint = CGPoint(x: 0, y: 0) addChild(background) } func transform(w: CGFloat) -> CGFloat { switch w { case let w where 0 < w && w < 80: return 0 case let w where 80 < w && w < 160: return 80 case let w where 160 < w && w < 240: return 160 default: return -80 } } func mark(location: CGPoint) { let imageName = turn_o ? "o" : "x" let sign = SKSpriteNode(imageNamed: imageName) sign.position = CGPoint(x: transform(location.x), y: 160 - transform(location.y - 400)) sign.anchorPoint = CGPoint(x: 0, y: 0) addChild(sign) turn_o = !turn_o } override func update(currentTime: CFTimeInterval) { /* Called before each frame is rendered */ } }
GameViewController.swift
// // GameViewController.swift // swiftSampleGame1 // import UIKit import SpriteKit class GameViewController: UIViewController, UIGestureRecognizerDelegate { var scene: GameScene! override func viewDidLoad() { super.viewDidLoad() let skView = view as SKView skView.multipleTouchEnabled = false scene = GameScene(size: skView.bounds.size) scene.scaleMode = .AspectFill skView.presentScene(scene) } override func prefersStatusBarHidden() -> Bool { return true } @IBAction func didTap(sender: UITapGestureRecognizer) { let location = sender.locationInView(view) println("tapped at x=\(location.x), y=\(location.y)") scene.mark(location) } }
実行
※ちょっとまて…
所感
背景の位置やタップ時の挙動がおかしいので後日再修正したものを作りなおそう。
勝ち負けの判定や順番などもあったほうがうれしい。
まあ、1つの端末で対戦というのも変な感じですが…