在接受时重新安装游戏点击swift

时间:2015-07-06 07:16:05

标签: ios swift button

我无法为两位玩家重置游戏。

  • 播放器1按下重置游戏,弹出警告说“#34;等待播放器2接受游戏重置请求"
  • 播放器2收到警告说“#34;播放器1已请求重新启动游戏"并且它下面有两个按钮,表示拒绝和接受。
  • 当他/她按下接受时,游戏会重置Player2,但游戏不会为Player1重置

以下是视图控制器的代码

@IBOutlet var fields: [TTTImageView]!
var currentPlayer:String!

var appDelegate:AppDelegate!

override func viewDidLoad() {
    super.viewDidLoad()
    appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    appDelegate.mpcHandler.setupPeerWithDisplayName(UIDevice.currentDevice().name)
    appDelegate.mpcHandler.setupSession()
    appDelegate.mpcHandler.advertiseSelf(true)

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "peerChangedStateWithNotification:", name: "MPC_DidChangeStateNotification", object: nil)

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleReceivedDataWithNotification:", name: "MPC_DidReceiveDataNotification", object: nil)

    setupField()
    currentPlayer = "x"

}


@IBAction func connectWithPlayer(sender: AnyObject) {




    if appDelegate.mpcHandler.session != nil{
        appDelegate.mpcHandler.setupBrowser()
        appDelegate.mpcHandler.browser.delegate = self

        self.presentViewController(appDelegate.mpcHandler.browser, animated: true, completion: nil)

    }

}



func peerChangedStateWithNotification(notification:NSNotification){
    let userInfo = NSDictionary(dictionary: notification.userInfo!)

    let state = userInfo.objectForKey("state") as! Int

    if state != MCSessionState.Connecting.rawValue{
        self.navigationItem.title = "Player Connected"
    }

}

func handleReceivedDataWithNotification(notification:NSNotification){
    let userInfo = notification.userInfo! as Dictionary
    let receivedData:NSData = userInfo["data"] as! NSData

    let message = NSJSONSerialization.JSONObjectWithData(receivedData, options: NSJSONReadingOptions.AllowFragments, error: nil) as! NSDictionary
    let senderPeerId:MCPeerID = userInfo["peerID"] as! MCPeerID
    let senderDisplayName = senderPeerId.displayName

    if message.objectForKey("string")?.isEqualToString("New Game") == true{
        let alert = UIAlertController(title: "Game Restart Request", message: "\(senderDisplayName) has requested to restart the game", preferredStyle: UIAlertControllerStyle.Alert)
        let cancelAction = UIAlertAction(title: "No", style: .Cancel) { (acttion) in

        }

        alert.addAction(cancelAction)

        let OKAction = UIAlertAction(title: "Yes", style: .Default) { (action) in
            self.resetField()
        }

        alert.addAction(OKAction)

        self.presentViewController(alert, animated: true) {
        }


    }else{
        var field:Int? = message.objectForKey("field")?.integerValue
        var player:String? = message.objectForKey("player") as? String

        if field != nil && player != nil{
            fields[field!].playerr = player
            fields[field!].setPlayer(player!)

            if player == "x"{
                currentPlayer = "o"
            }else{
                currentPlayer = "x"
            }

            checkResults()

        }

    }


}


func fieldTapped (recognizer:UITapGestureRecognizer){
    let tappedField  = recognizer.view as! TTTImageView
    tappedField.setPlayer(currentPlayer)

    let messageDict = ["field":tappedField.tag, "player":currentPlayer]

    let messageData = NSJSONSerialization.dataWithJSONObject(messageDict, options: NSJSONWritingOptions.PrettyPrinted, error: nil)

    var error:NSError?

    appDelegate.mpcHandler.session.sendData(messageData, toPeers: appDelegate.mpcHandler.session.connectedPeers, withMode: MCSessionSendDataMode.Reliable, error: &error)

    if error != nil{
        println("error: \(error?.localizedDescription)")
    }

    checkResults()


}


func setupField (){
    for index in 0 ... fields.count - 1{
        let gestureRecognizer = UITapGestureRecognizer(target: self, action: "fieldTapped:")
        gestureRecognizer.numberOfTapsRequired = 1


        fields[index].addGestureRecognizer(gestureRecognizer)
    }
}

func resetField(){
    for index in 0 ... fields.count - 1{
        fields[index].image = nil
        fields[index].activated = false
        fields[index].playerr = ""
    }

    currentPlayer = "x"

}
@IBAction func newGame(sender: AnyObject) {

    let alertWait = UIAlertController(title: "Request Sent", message: "Waiting for other player to accept this request", preferredStyle: UIAlertControllerStyle.Alert)

    self.presentViewController(alertWait, animated: true) {

    }


    let messageDict = ["string":"New Game"]

    let messageData = NSJSONSerialization.dataWithJSONObject(messageDict, options: NSJSONWritingOptions.PrettyPrinted, error: nil)

    var error:NSError?

    appDelegate.mpcHandler.session.sendData(messageData, toPeers: appDelegate.mpcHandler.session.connectedPeers, withMode: MCSessionSendDataMode.Reliable, error: &error)

    if error != nil{
        println("error: \(error?.localizedDescription)")
    }


}

func checkResults(){
    var winner = ""

    if fields[0].playerr == "x" && fields[1].playerr == "x" && fields[2].playerr == "x"{
        winner = "x"
    }else if fields[0].playerr == "o" && fields[1].playerr == "o" && fields[2].playerr == "o"{
        winner = "o"
    }else if fields[3].playerr == "x" && fields[4].playerr == "x" && fields[5].playerr == "x"{
        winner = "x"
    }else if fields[3].playerr == "o" && fields[4].playerr == "o" && fields[5].playerr == "o"{
        winner = "o"
    }else if fields[6].playerr == "x" && fields[7].playerr == "x" && fields[8].playerr == "x"{
        winner = "x"
    }else if fields[6].playerr == "o" && fields[7].playerr == "o" && fields[8].playerr == "o"{
        winner = "o"
    }else if fields[0].playerr == "x" && fields[3].playerr == "x" && fields[6].playerr == "x"{
        winner = "x"
    }else if fields[0].playerr == "o" && fields[3].playerr == "o" && fields[6].playerr == "o"{
        winner = "o"
    }else if fields[1].playerr == "x" && fields[4].playerr == "x" && fields[7].playerr == "x"{
        winner = "x"
    }else if fields[1].playerr == "o" && fields[4].playerr == "o" && fields[7].playerr == "o"{
        winner = "o"
    }else if fields[2].playerr == "x" && fields[5].playerr == "x" && fields[8].playerr == "x"{
        winner = "x"
    }else if fields[2].playerr == "o" && fields[5].playerr == "o" && fields[8].playerr == "o"{
        winner = "o"
    }else if fields[0].playerr == "x" && fields[4].playerr == "x" && fields[8].playerr == "x"{
        winner = "x"
    }else if fields[0].playerr == "o" && fields[4].playerr == "o" && fields[8].playerr == "o"{
        winner = "o"
    }else if fields[2].playerr == "x" && fields[4].playerr == "x" && fields[6].playerr == "x"{
        winner = "x"
    }else if fields[2].playerr == "o" && fields[4].playerr == "o" && fields[6].playerr == "o"{
        winner = "o"
    }

    if winner != ""{
        let alert = UIAlertController(title: "Tic Tac Toe", message: "The winner is \(winner)", preferredStyle: UIAlertControllerStyle.Alert)
        alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { (alert:UIAlertAction!) -> Void in
            self.resetField()
        }))

        self.presentViewController(alert, animated: true, completion: nil)
    }

}



func browserViewControllerDidFinish(browserViewController: MCBrowserViewController!) {
    appDelegate.mpcHandler.browser.dismissViewControllerAnimated(true, completion: nil)
}

func browserViewControllerWasCancelled(browserViewController: MCBrowserViewController!) {
    appDelegate.mpcHandler.browser.dismissViewControllerAnimated(true, completion: nil)
}


override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
}

0 个答案:

没有答案