快速的国际象棋游戏,第二部分

好吧,如果您阅读了第一部分,那么一切都会说得通; 如果您没有阅读更多内容,请先阅读。

因此,假设您已阅读并遵循了简短的教程; 您现在有一个工作的国际象棋棋盘……但是它还需要更多。 它需要跟踪您赢/输的部分,这是我今天打算分享的代码字节。 最终游戏应该看起来像这样。

您在左侧和右侧看到的两列是所截取的部分。 它们是两个UIStackView,这是解决此问题的完美解决方案,因为我可以向其中动态添加内容。 您需要在第一部分中进行编码的第一个更改是将此处的代码添加到ViewController中。

  whiteWin = UIStackView() 
whiteWin.axis = UILayoutConstraintAxis.vertical
whiteWin.distribution = UIStackViewDistribution.equalSpacing
whiteWin.alignment = UIStackViewAlignment.center
whiteWin.spacing = 2.0

self.view.addSubview(whiteWin)
让margins = view.layoutMarginsGuide

whiteWin.translatesAutoresizingMaskIntoConstraints = false
whiteWin.leadingAnchor.constraint(equalTo:margins.leadingAnchor,常数:+32).isActive = true
whiteWin.centerYAnchor.constraint(equalTo:self.view.centerYAnchor).isActive = true

blackWin = UIStackView()
blackWin.axis = UILayoutConstraintAxis.vertical
blackWin.distribution = UIStackViewDistribution.equalSpacing
blackWin.alignment = UIStackViewAlignment.center
blackWin.spacing = 2.0

self.view.addSubview(blackWin)
blackWin.translatesAutoresizingMaskIntoConstraints = false
blackWin.trailingAnchor.constraint(equalTo:margins.trailingAnchor,常数:-32).isActive = true
blackWin.centerYAnchor.constraint(equalTo:self.view.centerYAnchor).isActive = true

在其中,您具有两个UIStackViews,它们具有最少的配置,最重要的是,布局限制确保了棋盘侧面。

在这里,我包括了用于其他主要更改的方法的完整代码。

  func dropInteraction(_交互:UIDropInteraction,performDrop会话:UIDropSession){ 
//消耗拖动项(在本示例中为UIImage类型)。
session.loadObjects(ofClass:UIImage.self){imageItems in
让images = imageItems作为! [UIImage]
让dropLocation:CGPoint = session.location(in:self.view)
用于self.image2A中的image2X {
如果(image2X.frame.contains(dropLocation)){
self.objectIndex = image2X.tag
如果self.objectIndex == self.sourceIndex {
//中止动作
返回
}
如果self.cpmap [self.objectIndex]!=无{
让lossPiece = UIImageView()
missingPiece.image = UIImage(name:self.cpmap [image2X.tag]!)
missingPiece.heightAnchor.constraint(equalToConstant:48).isActive = true
missingPiece.widthAnchor.constraint(equalToConstant:48).isActive = true
missingPiece.alpha = 0.5
如果((self.cpmap [image2X.tag] ?. prefix(1))!=“ b”){
self.blackWin.addArrangedSubview(losingPiece)
}其他{
self.whiteWin.addArrangedSubview(losingPiece)
}
}
self.cpmap [self.objectIndex] = self.cpmap [self.sourceIndex]
self.cpmap [self.sourceIndex] =无
image2X.image = images.first
self.image2M.image =无
}
}
}
}

当您将片段拖放到新位置时,此代码将运行。 现在,它将通过cpmap变量进行检查,以查看是否已经存在一个片段,如果存在,则将其添加到我们先前创建的两个stackViews中。 由于UIImageview没有固有尺寸,因此它也引入了一些其他约束。

抱歉,是的,我们在构建开发板时在viewController中填充了cpmap。 我需要阅读的条件部分中需要添加的代码行…

 如果cpieces [imageIndex]!= nil { 
image2D.image = UIImage(命名为:cpieces [imageIndex]!)
cpmap [imageIndex] = cpieces [imageIndex]!
}

使用cpmap,无非就是一个字典,它的声明与cpieces一起。

  var cpmap:[Int:String] = [:] 

至此,本更新结束。 我应该做更多吗? 您认为缺少什么? 请给出意见?

值得一提的是,请注意您从https://thenounproject.com下载的图像中看到的棋子; 它们是由jhonythomasang@gmail.com创建的。