So im making a tetris game with 2 bots playing agaisn’t each other, i already implemented most of the optimizations i can think of such as localize global functions, reducing the amount of for loops i do in my code, and some other micro-opts. Why i really want to improve my code is because 1 bot takes up around 15-30% of my CPU (which is a bad cpu but i still think there’s room for improvement in my code) so that’s why im asking here. Also, with an interval of 0.1 seconds, the ai code calculates the best possible move twice for different pieces, and moves accordingly to the desired position.
Code:
-- This function is ran twice to improve efficiency of the bot
local function getMoves(board, piece, isHeldPiece, custom) -- custom is a custom matrix (used for next piece knowledge)
local matrixSize = board.MatrixSize
local placementData, scores, matrixClones = {}, {}, {}
local start = 5
local amountOfLoops = 4
-- these if statements are necessary to reduce the amount of for loops
if piece == "O" then
amountOfLoops = 1
elseif piece == "S" or piece == "Z" or piece == "I" then
amountOfLoops = 2
end
for rotationState = 1, amountOfLoops do
local positions, matrixList = getAllPossiblePositions(board, piece, rotationState, custom)
for index, position in positions do
local matrixClone = matrixList[index]
local pos = position
-- simulateLockPiece simulates placing the piece in that position without rendering it
-- the other functions are self-explanatory (i can still send them if you want)
local cleared = simulateLockPiece(board, matrixClone, pos, piece, rotationState)
local holes = checkHoles(board, matrixClone)
local bumpiness, totalHeight = getBumpiness(board, matrixClone, 10)
local landingHeight = getLandingHeight(pos, piece, rotationState)
-- calculateScore is also self-explanatory (it has weights assigned to each of these arguments and adds or subtracts them accordingly)
local score = calculateScore(
landingHeight,
cleared, holes,
bumpiness,
totalHeight,
board:_GetColumnHeight(10)
)
--data is the placement data so the bot knows where to place the piece
local data = {
Position = pos,
RotationState = rotationState,
Hold = isHeldPiece
}
tableInsert(scores, score)
tableInsert(placementData, data)
tableInsert(matrixClones, matrixClone)
end
end
return placementData, scores, matrixClones
end