Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #=
- แปลงมาจาก OX.py ในหนังสือ Artificial Intelligence
- with Machine Learning ของ รศ.ดร.ปริญญา สงวนสัตย์
- =#
- using Random
- O, X = [], []
- win = [[1,2,3],
- [4,5,6],
- [7,8,9],
- [1,4,7],
- [2,5,8],
- [3,6,9],
- [1,5,9],
- [3,5,7]]
- function randomChoice(args)
- args[rand(1:length(args))]
- end
- function checkWin(P)
- for w in win
- if all([in(v,P) for v in w])
- return true
- end
- end
- false
- end
- function displayOX()
- newMap = [in(v,O) ? "[O]" : (in(v,X) ? "[X]" : "[_]") for v in 1:9]
- for i = 1:3:9
- println(newMap[i]*newMap[i+1]*newMap[i+2])
- end
- end
- function ai()
- validMove = [v for v in 1:9 if !in(v,vcat(O,X))]
- for w in win
- xl = Dict([(v,in(v,X)) for v in w])
- if count(i->i==true,values(xl))==2 && any([in(v,validMove) for v in w])
- return [v[1] for v in pairs(xl) if v[2]==false][1]
- end
- end
- V = [-100,-100,-100,-100,-100,-100,-100,-100,-100]
- for v in validMove
- tempX = push!(copy(X),v)
- V[v], criticalMove = evalOX(O,tempX)
- if length(criticalMove) > 0
- #if checkWin(tempX)
- # return v
- #end
- move = [i for i in criticalMove if in(i,validMove)]
- return randomChoice(move)
- end
- end
- maxV = maximum(V)
- imaxV = [v[1] for v in pairs(V) if v[2] == maxV]
- randomChoice(imaxV)
- end
- function evalOX(o,x)
- SO, SX, criticalMove = calSOX(o,x)
- (1 + SX - SO), criticalMove
- end
- function calSOX(o,x)
- SO, SX = 0, 0
- criticalMove = []
- for w in win
- cO = [in(v,o) for v in w]
- cX = [in(v,x) for v in w]
- if !any(cX)
- #nO = length(cO[cO .== true])
- nO = count(i->i==true,cO)
- SO = SO + nO
- if nO == 2
- println("critical ", w)
- criticalMove = copy(w)
- end
- end
- if !any(cO)
- SX = SX + count(i->i==true,cX)
- end
- end
- SO, SX, criticalMove
- end
- while true
- print("Choose position [1-9]: ")
- move = tryparse(Int64,readline())
- println("")
- while isnothing(move) || in(move,vcat(O,X)) || move > 9 || move < 1
- print("Bad move: choose position [1-9]: ")
- move = tryparse(Int64,readline())
- println("")
- end
- push!(O,move)
- displayOX()
- if checkWin(O)
- println("O win")
- break
- end
- if length(O) + length(X) == 9
- println("Draw")
- break
- end
- push!(X,ai())
- displayOX()
- if checkWin(X)
- println("X win")
- break
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement