Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- O = {
- false,false,false
- false,false,false
- false,false,false
- }
- X = {
- false,false,false
- false,false,false
- false,false,false
- }
- 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}
- }
- is = require "inspect"
- rnd = math.random
- max = math.max
- floor = math.floor
- add = table.insert
- unpak = table.unpack
- concat = table.concat
- all = (player_move, win_case) ->
- player_move[win_case[1]] and
- player_move[win_case[2]] and
- player_move[win_case[3]]
- any = (player_move, win_case) ->
- t = 0
- t += (player_move[win_case[1]] and 1 or 0)
- t += (player_move[win_case[2]] and 1 or 0)
- t += (player_move[win_case[3]] and 1 or 0)
- t
- randomChoice = (args) -> args[rnd #args]
- checkWin = (P) ->
- for _, w in pairs win
- if all P, w
- return true
- false
- displayOX = ->
- newMap = {}
- for i = 1, 9, 3
- newMap[i] = O[i] and "[O]" or (X[i] and "[X]" or "[_]")
- newMap[i+1] = O[i+1] and "[O]" or (X[i+1] and "[X]" or "[_]")
- newMap[i+2] = O[i+2] and "[O]" or (X[i+2] and "[X]" or "[_]")
- print(newMap[i]..newMap[i+1]..newMap[i+2])
- calSOX = (o, x) ->
- SO, SX = 0, 0
- criticalMove = {}
- for _, w in ipairs win
- cO = any o, w
- cX = any x, w
- if cX == 0
- SO = SO + cO
- if cO == 2
- print "critical", "{".. concat(w,",").."}"
- criticalMove = w
- if cO == 0
- SX = SX + cX
- SO, SX, criticalMove
- evalOX = (o, x) ->
- SO, SX, criticalMove = calSOX o, x
- (1 + SX - SO), criticalMove
- ai = ->
- validMove = {
- true,true,true
- true,true,true
- true,true,true
- }
- validMove = [(not (O[i] or X[i]) and validMove[i]) for i = 1, 9]
- for _, w in ipairs win
- cX = any X, w
- if cX == 2
- for _, v in ipairs w
- return v if validMove[v]
- V = {
- -100,-100,-100
- -100,-100,-100
- -100,-100,-100
- }
- for i, v in ipairs validMove
- if v
- tempX, criticalMove = {unpak X}, {}
- tempX[i] = v
- V[i], criticalMove = evalOX O, tempX
- if #criticalMove > 0
- for _, c in pairs criticalMove
- if validMove[c]
- return c
- maxV = max unpak V
- imaxV = {}
- for i, v in pairs V
- if v == maxV then add imaxV, i
- return randomChoice imaxV
- chooseMove = (e)->
- if e
- io.write "Bad move: choose position [1-9]: "
- else
- io.write "Choose position [1-9]: "
- move = tonumber io.read!
- move = floor move if move
- print ""
- move
- while true
- move = chooseMove!
- validMove = true
- while (not move) or move > 9 or move < 1 or O[move] or X[move]
- move = chooseMove true
- O[move] = true
- displayOX!
- if checkWin O
- print "O win"
- break
- d = true
- for i = 1, 9 do d = (O[i] or X[i]) and d
- if d
- print "Draw"
- break
- X[ai!] = true
- displayOX!
- if checkWin X
- print "X win"
- break
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement