项目结构图如上
package PokerGame
/**
* 卡牌类
* Created by haivo on 2017-05-21.
*/
class Card(val point : String, val color : String) : Comparable<Card>{
override fun compareTo(other: Card): Int {
//用一副完整的扑克牌作为标准
val tmpPoker = Poker()
//将现有的卡牌放进标准扑克牌的对应位置,然后比较点数
var bigger = tmpPoker.points.indexOf(this.point) - tmpPoker.points.indexOf(other.point)
if (bigger == 0){
//若点数相同,比较花色
bigger = tmpPoker.colors.indexOf(this.color) - tmpPoker.colors.indexOf(other.color)
}
return bigger
}
override fun toString(): String {
return "$color$point"
}
}
package PokerGame
/**
* 扑克牌类
* Created by haivo on 2017-05-21.
*/
class Poker{
val points = listOf<String>("3","4","5","6","7","8","9","10","J","Q","K","A","2")
val colors = listOf<String>("黑桃","红桃","梅花","方块")
/**
* 返回按(点数,花色)有序存放好的一副完整的扑克牌
*/
fun getPoker() : MutableList<Card>{
val resultPoker = mutableListOf<Card>()
for (color in 1..colors.size)
for (point in 1..points.size){
resultPoker.add(Card(points[point-1],colors[color-1]))
}
return resultPoker
}
}
package PokerGame
import java.util.*
/**
* 玩家类
* Created by haivo on 2017-05-21.
*/
class Player(val id : Int, val names : String){
/**
*连续从给定的牌组cardList取count张牌,返回多张卡牌
*/
fun getCards(cardList : MutableList<Card>, count: Int) : MutableList<Card>{
val result = mutableListOf<Card>()
val random = Random()
for (a in 1..count){
//每次随机从cardList中取一张牌
val randomCard = cardList[(random.nextInt(cardList.size-1))]
result.add(randomCard)
//从cardList中移除这张牌,防止下一次取到相同的牌
cardList.remove(randomCard)
}
return result
}
override fun toString(): String {
return "$id:$names"
}
}
package PokerGame
import java.util.*
/**
* 程序入口,简化了一些输入玩家ID,姓名的操作,只展示最核心的结果
* Created by haivo on 2017-05-21.
*/
fun main(args: Array<String>) {
val mPoker = Poker()
val gameCardList = mPoker.getPoker() //将要被抽取的一组牌
val aPlayer = Player(1, "Jack") //玩家a是ID为1的Jack
val bPlayer = Player(2, "Mike")
val aPlayerCard = aPlayer.getCards(gameCardList,3) //玩家a从gameCardList中连续取3张牌
val bPlayerCard = bPlayer.getCards(gameCardList,3)
Collections.sort(aPlayerCard) //对玩家a的手牌进行排序
//由于重写了Player类的toString方法,所以可以直接$aPlayer的形式调用toString,$aPlayerCard同理
println("玩家$aPlayer 手牌是:$aPlayerCard")
Collections.sort(bPlayerCard)
println("玩家$bPlayer 手牌是:$bPlayerCard")
//将两个人最大的手牌比较
val a = aPlayerCard[2].compareTo(bPlayerCard[2])
if (a > 0)
println("玩家$aPlayer 获胜!")
else
println("玩家$bPlayer 获胜!")
}
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦