Strategy:kotlin

気を付けたこと

  • プライベートなコンストラクタの書き方
  • staticは無いのでコンパニオンオブジェクトで代用
  • singletonもコンパニオンオブジェクトをクラス内で宣言して実装するものらしい
  • 初期化してフィールドに設定するときはコンストラクタの引数宣言にvalを付ける
  • kotlinではpublicなクラスを一つのファイル内に複数書けるので全部同じファイルにまとめた
  • forの記述がjavaと違う(でも楽)
import java.util.Random
import kotlin.system.exitProcess

fun main(args:Array<String>) {
    if(args.size != 2){
        println("Wrong Usage")
        exitProcess(0)
    }
    val seed1 = args[0].toLong()
    val seed2 = args[1].toLong()
    val player1 = Player("Taro", WinningStrategy(seed1))
    val player2 = Player("Hana", ProbStrategy(seed2))
    for(i in 0..10000){
        val nextHand1 = player1.nextHand()
        val nextHand2 = player2.nextHand()
        if (nextHand1.isStrongerThan(nextHand2)) {
            println("winner:${player1}")
            player1.win()
            player2.lose()
        }else if (nextHand2.isStrongerThan(nextHand1)) {
            println("Winner${player2}")
            player1.lose()
            player2.win()
        }else{
            println("even")
            player1.even()
            player2.even()
        }
    }
    println("Total result:")
    println(player1.toString())
    println(player2.toString())
}
interface Strategy{
    abstract fun nextHand(): Hand
    abstract fun study(win:Boolean)
}
class ProbStrategy(private val seed:Long):Strategy{

    private val random = Random(seed)
    private var prevHandValue = 0
    private var currentHandValue = 0
    private val history = arrayOf(arrayOf(1, 1, 1), arrayOf(1, 1, 1), arrayOf(1, 1, 1))
    override fun nextHand(): Hand {
        val bet = random.nextInt(getSum(currentHandValue))
        var handvalue = 0
        if (bet < history[currentHandValue][0]) {
            handvalue = 0
        }else if (bet < history[currentHandValue][0] + history[currentHandValue][1]) {
            handvalue = 1
        }else{
            handvalue = 2
        }
        prevHandValue = currentHandValue
        currentHandValue = handvalue
        return Hand.getHand(handvalue)
    }
    private fun getSum(hv:Int):Int{
        var sum = 0
        for(i in 0 until 3){
            sum += history[hv][i]
        }
        return sum
    }

    override fun study(win: Boolean) {
        if(win){
            history[prevHandValue][currentHandValue]++
        }else{
            history[prevHandValue][(currentHandValue + 1)%3]++
            history[prevHandValue][(currentHandValue + 2)%3]++
        }
    }
}
class WinningStrategy(private val seed:Long):Strategy{
    private val random = Random(seed)
    private var won  = false
    private var prevHand:Hand? = null
    override fun nextHand(): Hand {
        if(!won){
            prevHand = Hand.getHand(random.nextInt(3))
        }
        return prevHand!!
    }

    override fun study(win: Boolean) {
        won = win
    }
}
class Player(private val name:String,private val strategy:Strategy){
    private var wincount = 0
    private var losecount = 0
    private var gamecount = 0
    fun nextHand() = strategy.nextHand()
    fun win(){
        strategy.study(true)
        wincount++
        gamecount++
    }
    fun lose(){
        strategy.study(false)
        losecount++
        gamecount++
    }
    fun even(){
        gamecount++
    }

    override fun toString(): String {
        return "[${name}:${gamecount}games,${wincount}win,${losecount}lose]"
    }
}
//アクセス修飾子を付ける場合はconstructorキーワードが必要
//省略すると他と同じ(public)になる
class Hand private constructor(private val handvalue:Int){
//    最初こんなふうに書いてたけどこれはセカンドコンストラクタの扱いになる
//    private constructor(private val handvalue:Int)
    companion object {
    const val HANDVALUE_GUU = 0
    const val HANDVALUE_CHO = 1
    const val HANDVALUE_PAA = 2
    private val name =
        arrayOf("グー","チョキ","パー")
    val hand = arrayOf(Hand(HANDVALUE_GUU),Hand(HANDVALUE_CHO),Hand(HANDVALUE_PAA))
    fun getHand(handvalue:Int)=hand[handvalue]
}
    fun isStrongerThan(h:Hand)=fight(h) == 1
    fun isWeakerThan(h:Hand)=fight(h) == -1
    fun fight(h:Hand):Int{
        if( this === h){
            return 0
        }else if ((this.handvalue + 1) % 3 == h.handvalue) {
            return 1
        }else{
            return -1
        }

    }
    override fun toString(): String {
        return name[handvalue]
    }
}

元のコードは以下の本からの引用です。サンプルコードは著者さんのサイトで配布されています。リンクはAmazonアソシエイトを使用しています。

増補改訂版Java言語で学ぶデザインパターン入門

ライセンス表記

Copyright (C) 2001,2004 Hiroshi Yuki.

hyuki@hyuki.com
This software is provided ‘as-is’, without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution.

コメント

タイトルとURLをコピーしました