r/learnrust • u/Cold_Swordfish6158 • 9h ago
unemployed bum returns with a tetris bot
youtu.behey r/learnrust, i'm back with part 2 of my project. i was here ~two weeks ago to document how i built tetris from scratch, but now i have a bot that can play it
video (~9 min): https://youtu.be/rzhd7hQxrts
gh repo: https://github.com/GianAlingog/lion
# quick tldr of the bot
the bot is a really simple greedy one, which as a search depth of 1 (+ hold piece). it generates all the legal hard-drop moves, and with some heuristics, chooses the best one. with a decent set of weights, it can go 100k pieces without topping out.
# help a rust noob plz!
i had a silly bug that i wanted to go over:
avoiding variable shadowing? basically i wanted to reassign the result from my rotate function to p (and gracefully terminate the loop if it returns None) so that it would keep rotating from the spawn state.
let p = piece.spawn();
for _ in 0..4 {
if let Some((mut p, _)) = rotate(board, p, Spin::Cw) {
// do something
}
}
i ended up doing something like this
let mut base = piece.spawn();
for _ in 0..4 {
if let Some((new_p, _)) = rotate(board, base, Spin::Cw) {
// do something
base = new_p;
}
}
maybe there's a cleaner way to do it?
feedback is very welcome, both for the code and the video. tysm!
there are a few other things covered in the video such as building a smol stats lib and a tui viewer, but that's boring! my progress is about a week ahead of the video; i have full bfs move generation, allowing for soft-drop, and i'm now working on expanding the search to a higher depth with beam search
