Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- --[[
- Tic Tac Toe with some real AI
- by Wassil Janssen a.k.a. Creator
- ]]--
- if not AI then os.loadAPI("AI") end
- grid = {
- {1,2,3},
- {4,5,6},
- {7,8,9}
- }
- 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},
- }
- local myNet = 0
- function seewin(taken)
- for i=1,8 do
- local first = win[1]
- if taken[win[i][1]] and taken[win[i][2]] == taken[win[i][3]] and taken[win[i][2]] == taken[win[i][1]] then
- return true
- end
- end
- return false
- end
- if fs.exists("tic.net") then
- file = fs.open("tic.net","r")
- local buf = file.readAll()
- file.close()
- myNet = AI.unserialize(textutils.unserialize(buf))
- else
- myNet = AI.Net({18,19,19,19,9})
- end
- function game()
- taken = {}
- moves = 0
- function draw()
- term.setBackgroundColor(colors.black)
- term.setTextColor(colors.white)
- term.clear()
- local count = 1
- for i=1,3 do
- for m=1,3 do
- term.setCursorPos(m,i)
- term.setTextColor(taken[count] == "X" and colors.green or taken[count] == "O" and colors.red or colors.white)
- term.write(taken[count] or count)
- count = count + 1
- end
- end
- end
- while true do
- local nInput = 0
- repeat
- draw()
- term.setTextColor(colors.white)
- term.setCursorPos(2,5)
- term.write("Input your number, player 1:")
- term.setCursorPos(31,5)
- local sInput = read()
- nInput = tonumber(sInput)
- until #sInput == 1 and nInput and not taken[nInput]
- taken[nInput] = "X"
- moves = moves + 1
- if seewin(taken) then return "X won" end
- if moves == 9 then return "A tie" end
- local results = myNet.getResults()
- local input = 1
- local scale = 0
- for i=1,9 do
- if not taken[i] and results[i] > scale then
- input = i
- end
- end
- taken[input] = "O"
- moves = moves + 1
- local buffer = {}
- for i=1,9 do
- buffer[i] = taken[i] == "X" and 1 or 0
- buffer[i+9] = taken[i] == "O" and 1 or 0
- end
- local buffer2 = {}
- for i=1,9 do
- buffer2[i] = i == nInput and 1 or 0
- end
- myNet.feedForward(buffer)
- myNet.backProp(buffer2)
- if seewin(taken) then return "O won" end
- end
- end
- while true do
- print(game())
- read()
- file = fs.open("tic.net","w")
- file.write(textutils.serialize(myNet.serialize()))
- file.close()
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement