Search code examples
luasaveartificial-intelligencemovetic-tac-toe

Lua Algorithm for saving moves in tic-tac-toe


So, I'm programming in lua, and im ATTEMPTING to make AI. Every time i run the code, (I only have the AI's move code in right now) it gives me a random spot drawn on the board, but it doesn't save previous moves. It's an entirely clean board with one space taken. Can anybody help me with this? It would be greatly appreciated if so! Code:

    function moves()
local Possible = {'1,1','1,2','1,3','2,1','2,2','2,3','3,1','3,2','3,3'}
math.randomseed(os.time())
    math.random()
    local AImove = Possible[math.random( #Possible )]
print('The Opponent Chose',AImove)
--[[
removal of numbers from possibility to only provide legal moves0
]]--
if AImove == '1,1' then
    table.remove(Possible,1)
    print("_ _ _") 
    print("_ _ _")
    print("X _ _")
end
if AImove == '1,2' then
    table.remove(Possible,2)
    print("___")
    print("X__")
    print("___")
end
if AImove == '1,3' then
    table.remove(Possible,3) 
    print("X _ _")
    print("_ _ _")
    print("_ _ _")
end
if AImove == '2,1' then
    table.remove(Possible,4)
    print("_ _ _")
    print("_ _ _")
    print("_ X _")
end
if AImove == '2,2' then
    table.remove(Possible,5)
    print("_ _ _")
    print("_ X _")
    print("_ _ _")
end
if AImove == '2,3' then
    table.remove(Possible,6)
    print("_ X _")
    print("_ _ _")
    print("_ _ _")
end
if AImove == '3,1' then
    table.remove(Possible,7)
    print("_ _ _")
    print("_ _ _")
    print("_ _ X")
end
if AImove == '3,2' then
    table.remove(Possible,8)
    print("_ _ _")
    print("_ _ X")
    print("_ _ _")
end
if AImove == '3,3' then
    table.remove(Possible,9)
    print("_ _ X")
    print("_ _ _")
    print("_ _ _")
end
end
moves()

Solution

  • You need something that stores the state of the game. I'll give you a very simple quick and dirty example. A table board that stores the 9 fields and a few functions that allow us to manipulate and display the board.

    This should give you a rough idea on how to get started.

    -- our board
    local board = {
    }
    
    -- check a field on our board
    function board:check(row, col, str)
      board[row][col] = str
      self:print()
    end
    
    -- print the board to the screen
    function board:print()
      print("---------")
      for i,v in ipairs(self) do
        print("| " .. table.concat(v, " ") .. " |")
      end
      print("---------")
    end
    
    -- init/clear the board
    function board:init()
      for row = 1, 3 do
        board[row] = {}
        for col = 1, 3 do
          board[row][col] = " "
        end
      end
      board:print()
    end
    
    board:init()
    board:check(2,2,"X")
    board:check(1,3,"O")