Skip to content

Instantly share code, notes, and snippets.

@echiesse
Created October 18, 2017 18:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save echiesse/354f10a1fa0db46e2aae0a01abed7e7b to your computer and use it in GitHub Desktop.
Save echiesse/354f10a1fa0db46e2aae0a01abed7e7b to your computer and use it in GitHub Desktop.
Ajuda em um jogo da velha no LuaBR
board =
{
{1,2,3},
{4,5,6},
{7,8,9},
}
function play(piece)
local pos = tonumber(io.read())
while not isFree(board, pos) do
print("Posicao ocupada. Tente outra:")
pos = tonumber(io.read())
end
local i, j = getIndices(pos)
board[i][j] = piece
end
function isPiece(piece)
return piece == "O" or piece == "X"
end
function isFree(board, pos)
local i, j = getIndices(pos)
return not isPiece(board[i][j])
end
function getIndices(pos)
local i = math.floor((pos-1)/3) + 1
local j = (pos-1) % 3 + 1
return i, j
end
function win()
return (board[1][1] == board[1][2] and board[1][2] == board[1][3]) or
(board[2][1] == board[2][2] and board[2][2] == board[2][3]) or
(board[3][1] == board[3][2] and board[3][2] == board[3][3]) or
(board[1][1] == board[2][1] and board[2][1] == board[3][1]) or
(board[1][2] == board[2][2] and board[2][2] == board[3][2]) or
(board[1][3] == board[2][3] and board[2][3] == board[3][3]) or
(board[1][1] == board[2][2] and board[2][2] == board[3][3]) or
(board[1][3] == board[2][2] and board[2][2] == board[3][1])
end
function getFreePositions(board)
local ret = {}
for pos = 1, 9 do
if isFree(board, pos) then
table.insert(ret, pos)
end
end
return ret
end
function cpuPlay(piece)
local freePlaces = getFreePositions(board)
local index = math.random(1, #freePlaces)
local pos = freePlaces[index]
print(pos)
for i = 1,3 do
for j = 1,3 do
if pos == board[i][j] then
board[i][j] = piece
end
end
end
end
function getGameResult(board)
local ret = "c" -- continue
if win() then
ret = "w" -- Há um ganhador
elseif #getFreePositions(board) == 0 then
ret = "v" -- Deu velha
end
return ret
end
function printGameResult(result)
local results =
{
w = "Ganhou",
v = "Deu velha",
}
print(results[result])
end
function printBoard(board)
for i, line in ipairs(board) do
print(line[1] .. "|" .. line[2] .. "|" .. line[3])
end
print("")
end
function runGame()
printBoard(board)
local gameResult = "c"
while true do
print("Sua vez:")
play("X")
printBoard(board)
gameResult = getGameResult(board)
if gameResult ~= "c" then
break
end
print("CPU:")
cpuPlay("O")
printBoard(board)
gameResult = getGameResult(board)
if gameResult ~= "c" then
break
end
end
printGameResult(gameResult)
end
runGame()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment