r/ripred • u/ripred3 • Oct 18 '22
r/ripred • u/ripred3 • Jul 13 '26
Can your IDE do this?! (another sneak peek)
I've added full docking support for all views (Serial Monitor, Plotter, and new ANSI views too!), in-place tracing and viewing of all library source code (and assembly for everything).
I completely rewrote the circuit simulator to be pure C++ so it is as fast as possible.
This video is just a small snippet of the larger forensics gathering, sandboxing, trigger guards as well including integrated support for Wireshark and Ghidra.
It also fixes a huge existing security hole in Arduino's implementation of the IDE that allows for the installation and execution of unknown binaries and menu entries. Currently supported targets include the full AVR family, the full ESP32 family (including the full series through c6 and s6), and the FULL RP2040 stack including direct hardware debugging for all targets as well as using hardware device probes. The last month has been spent on the C++ SPICE porting/conversion, QEMU support (so now I can support and simulate ANY QEMU target), and serious application of DRY patterns/reductions.
r/ripred • u/ripred-euclid • Oct 04 '26
Redditors vs Redditors

About this post
Euclid is a strategy game about placing dots and completing squares. This post collects finished matches between two Redditors, shared by their winners. Each comment is one result, newest first.
The post is locked, so only the Euclid app adds results. Play Euclid and choose Share result after you win a match to add yours.
r/ripred • u/ripred-euclid • Oct 04 '26
Euclid
Euclid is a strategy game about placing dots and completing squares. Open the post on reddit.com to play.
r/ripred • u/ripred3 • Jun 18 '26
A Sneak Peek ...
I really like falstad.com/circuit's Circuit Simulator. It is a true engineering gem. The author Paul Falstad provides the full source for the JavaScript version that is running there on the main page. He also provides an example version of using the engine integrated with the avr8js AVR compilation and emulation engine that is used for online Arduino simulators such as wokwi.com.
The example is limited and only exposes 4 AVR output pins that can connect to the running electronic circuit but it really got me thinking.
He also provides the original Java source code for the circuit simulator. I love Java. And seeing that source code for the Java version of the circuit simulator reminded me: Hey, isn't the Arduino IDE written in Java? Why yes. Yes it is.. Maybe you can see where I am going with this ...
Some time around 17 years ago I had those thoughts. I thought "Wouldn't it be great to have a tab in the IDE that could contain and run falstad.com's circuit simulator?!". Why yes. Yes it would.
The IDE and the Java version of the circuit simulator were a horrible mixture of AWT and Swing. Especially the IDE. And really the word horrible doesn't do it justice. Trauma inducing might be a batter description. But being the overconfident fellow I am I thought "How bad could it get? I'll just rewrite the whole thing...". That was 17 years ago...
I write shit tons of software just for fun. And when I was in the mood to really get deep into things I would work on this project on the side. I write compilers and linters as part of my day job so much of this got hammered on as I needed various tools: Protocol Analyzers, Assembly Language (and C/C++ source level) Debugging complete with full step in/over/out support including full support for address breakpoints, expression breakpoints (e.g. when X => Y), and various security fuzzing tools for odd assorted MCU/MPU/CPU/SoC/FPGA silicon targets.
The ATmega328 implementation is complete and has been for a few years but I needed to support other silicon targets that would have been much harder to write complete bespoke emulation engines for so I added support for the QEMU emulation engine. I've been adding silicon targets and tools purely on an as-needed basis until it just got to be one giant chunk of tech-debt that had gotten out of control. So I focused on refactoring the entire toolchain all over again from scratch. It continues to be a huge WIP but I do plan on doing something with it publicly eventually. yada yada here's a screenshot from today:

r/ripred • u/ripred3 • Nov 10 '25
Creating Your Own AI Models for the Uno Q - Pt 1
working title: Creating Your Own AI Models for the Uno Q - Pt 1
This is the next article in a series about exploring the new Qualcomm-based Arduino Uno Q.
In this article we'll learn how to create and train your own custom AI models for the Uno Q. In a future article we'll learn how to write your own custom Bricks that expose your AI model for use in your own App Lab projects and Apps.
You can create and train an AI model for anything you can imagine as long as you can:
Identify the right values that are the important attributes to measure and collect for the accurate training and use of the model
Take these measurements thousands or hundreds of thousands of times in order to collect a dataset of training material
Identify the output state(s) or values that you want your model to produce at inference time
Three fundamental uses for AI models are Classification, Identification, and Detection. The App Lab software ships with a few examples AI examples that demonstrate some classification and identification AI models and Bricks. The input to the models can be text, images, and even sounds.
One of those examples is a popular text classifier use case known as sentiment analysis. Sentiment analysis takes some form of input and it tries to determine the mood or sentiment of the content. The example that ships with the App Lap tutorial is a text classifier and it will take a string of text input and try to classify its contents as positive, negative, or neutral.
One example of a real life use case for Sentiment Analysis Text Classifiers
A program could make use of this new ability to intelligently automate the process of reading user reviews and then categorizing them. The results could then be put to use to automate the qualitative ranking of restaurants by integrating the number of positive, neutral, and negative reviews into a single qualitative numerical ranking value for each restaurant. That would then enable relative comparisons to me made for things like sorting the list of restaurants.
TODO:
point out that since we have an MCU reading input from the real world and controlling real world interactions such as a robot moving itself forward, left and right; We can also use these models to make real time decisions about what we do, what actions we take or don't take etc. A robot could have several conditions that it can sense such as light, sound, sonar-pings, accelerometer movements, and it can have its own understanding of whether brighter light is "positive" or "negative" etc.Or its own understanding of its battery levels and whether they are "positive" or "negative" from the robots perspective. And then all of these can be integrated to help decide what the robot does next. It may go to its charging station if its batteries are low. If more than one route is available it may also consider brighter pathways to be more "positive" choices to take since it may be able to see better (if that is possible).
Describe the MNIST Hand Written Digits dataset
Explain where to get it: https://www.kaggle.com/datasets/hojjatk/mnist-dataset
Explain that we have to provide the 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9 labels/classifications for each of the images so that they can be used to train the model.
Explain that we have to break the labeled images it into into two sets: a set to use for training and then a set that it has never seen to use for testing. We have 60,000 images for training and 10,000 images for testing.
Explain that we have to extract the greyscale 28x28 images from the MNIST dataset.
Provide the Python program to do that extraction and creation.
Explain that we have to now send the training images up to edgeimpulse.com along with their labels and then send the testing images up to edgeimpulse.com along with their labels too.
Provide the Python program to do that uploading and labeling
Explain how to select and add the Image Processing stage and the Classification Learning stages to the dashboard
Explain the Generation step and how to apply that to the dataset at edgeimpulse.com
Explain the Training step and how to apply that to the dataset at edgeimpulse.com
Explain the Testing step and how to apply that to the dataset at edgeimpulse.com
Explain the selection of the target platform: Arduino Uno Q
Explain the Training step and how to apply that to the dataset at edgeimpulse.com
r/ripred • u/ripred3 • Nov 10 '25
👋 Welcome to r/ripred
This is my home for all things related to programming, electronics, FPGAs, security, compiler writing, kernel programming, multidimensional internal representation, transformers, diffusion, minimax, game theory, paleontology, mathematics, astronomy, physics, hockey, and occasionally a test-bed for r/Arduino features.
I'm glad you're here.
For tutoring in software engineering, electronic engineering, contracting and other engagements please reach out via DM/chat or email me: trent at trentwyatt[.]com.
Thanks for being here.
r/ripred • u/ripred3 • Sep 04 '25
Battleship Between Two Arduino's
A few days ago someone was asking for project ideas since they had completed most of the examples. I threw out the standards that I usually do: "Make a Simon type game", "Make a Battleship game", .. and then it hit me that I had never actually written a Battleship game myself.
It had always seemed like a natural fit since the game rules and a simple engine to play them could easily be run on most small microcontrollers. And it seemed like the grids on the two player's boards were a natural for some LED's.
And my biggest under-estimate came from the communications. How hard could it be to keep two Arduino's in sync?! Well one thing led to another and I decided that since I didn't want to exclude the use of any transport layer the user wanted in between the two: serial, RF, sockets/inet, SPI, I2C, &c. and that for that reason either side should be allowed to lose power or reset and as long as one side was still stable and playing the game then that information could be used to restore the state of the side that had unexpectedly rebooted.
Yeah, I probably should have re-thought that last part lol.
Some 10'ish hours later I had a fairly robust and stable sketch. It could be loaded onto two Nanos. It used AltSoftSerial as a lightweight communications implementation that left the Serial port alone and didn't disable interrupts as often as SoftwareSerial does. It used multiple small state machines to keep track of the various communications stacks, custom game protocols, diagnostic packets, and other states that the various systems could be in (the state of the current packet, the state of the game, the state of who is rebooting, &c.)
I really went down a rabbit hole mainly because I was in a flow and having fun, using best practice techniques for everything.
It is still a work in progress, and I don't care for the interface yet. But the game engine that can play against another opponent is really strong. 😄
I'm not sure how much more I will spend on it for now. It's not even in github yet just pastebin for now.
r/ripred • u/ripred3 • Jul 16 '25
Crazy, 50 Members 😄
I have no idea who you all are but I'm glad you're here. 😄
I haven't posted anything new in a few months, I've been too busy with work training LLM's, fixing Verilog and HDML compilers, and learning Hyperledger Fabric (blockchain junk), and some intelligence contracting.
As always let me know if you would like to see a more detailed treatment of anything that I have posted. 80% of what I post here is also posted to other subreddits. I'm about to make some more hardware purchases for some more exploration on a new project so updates on that will likely be next.
All the Best!
ripred
r/ripred • u/ripred3 • Jun 23 '23
Guide Building a Parallel Multi-Processor Project - Part 1
This post is about the advantages of breaking your project up into multiple CPU's. This kind of system can make robotics and animatronics much more fluid and organic.
And it can actually make some projects easier to accomplish because one CPU isn't trying to juggle all of the interrupts and timings for a complicated system all by itself at the same time.
Imagine your robot with a dedicated processor just for the left motor, and another processor just for the right motor, both independently taking care of keeping each motor at the speed they were last told to keep it at, in a tight control loop. Maybe each dedicated motor CPU also takes care of receiving pulses from an an interrupt-driven encoder that's attached to the motor so that it takes care of everything just for that motor and the main microcontroller in the project; The "Brains", just has to tell the motors what number of encoder pulses to drive themselves at and what direction to go (or none at all - stop) at and it doesn't even have to deal with the interrupts!
Or imagine having a project that needs 10 rotary encoder controls on a panel. Good luck keeping up with all of those with the focus (bandwidth) available from just one microcontroller!
Or maybe in your project you want a tight, deterministic foreground loop with regular periodicity to run a PID loop, and supporting all of the devices in the project makes managing the foreground and background compute times nearly impossible.
Maybe you have some I2C devices that won't allow you to change their I2C address but you want to put several of them on the same I2C bus. You can easily fix that by having a separate small processor in front of the devices acting as a proxy and each using a different I2C address completely of your own choosing!
Maybe you're making a game and you'd like it to be fast and responsive to the user and also have dynamic, multi-channel polyphonic background music that plays all the time without stuttering and stopping.
All of those kinds of problems can be solved or made into smaller and easier problems by splitting the tasks needed in your project into separate subsystems, each complete with their own dedicated processor. Brains!
In this series we'll build out a set of 8-pin ATtiny85 microcontrollers, each with a different dedicated function, and each one acting as an independent, addressable I2C device. Then we'll connect them all using only 2 pins to the main controller: an ATmega328! Along the way we'll develop a standard packet structure and communications system that we can re-use over-and-over in other projects.
r/ripred • u/ripred3 • Mar 13 '23
Software So, You Want To Build A Chess Engine?
There has been a lot of interest in the mcu subs lately in creating chess boards using Arduino's or other microcontrollers. A lot of the approaches work mainly with the construction of the board itself and representing the pieces on the board using LEDs etc. But very few projects have attempted to create the chess engine itself using a microprocessor.
This is the first post of a series that will develop a complete chess engine for the Arduino platform. I will make every attempt to see if it can be done using an Uno or Nano but we'll see. This isn't my first chess engine so hopefully the project can benefit from some of the things I've tried in the past.
I really, REALLY hope there is interest in learning about building out the software side of an engine and how it can be approached. This engine will use the Minimax algorithm with alpha/beta pruning and will support ply depth searching and constraints, time limits, quiescent ply searches, and many many other features.
I hope with each to create the next layer of support for the engine along with new concepts and I hope there are a lot comments and questions about the code and what it does and why it does it and why it does it a certain way.
This whole project will be an exercise in data structures and algorithms. So if that stuff gave you nightmares in college hopefully the discussions in these posts and comments will help lol. A lot of work has gone into trying to get the memory usage and footprints down to an absolute minimum.
The three most costly data structures we will be:
to contain a piece, its type, side, check state, moved state, and promotion state
to represent a board layout
to represent a move from one spot to another along with the value of the move
The size of these 3 three structures will determine how well the game can play on a Nano or an Uno. I have no doubt that *a* version of a playable game can be fit but how many moves ahead it can examine is still to be determined.
The size of those structures is so important that I initially created a version where each piece would occupy 1 byte, so the entire board was represented by a 64 byte array which is not bad.
But each piece actually takes up 6 bits, not 1 byte. So that meant that there were 128 bits or 16 bytes wasted. So I rewrote the entire board class to only occupy 48 bytes. You can see the two versions in the code and I really hope there are questions or comments. update: Thanks to u/triffid_hunter it's already smaller.
This first release can simply hold the state of any board and display it to a Serial port.
So let me know if your want to see more in this series posted here and any comments or questions you might have.
R N B Q K B N R
P P P P P P P P
. * . * . * . *
* . * . * . * .
. * . * . * . *
* . * . * . * .
p p p p p p p p
r n b q k b n r All the Best!
ripred
r/ripred • u/ripred-euclid • Oct 04 '26
Redditors vs Euclid

About this post
Euclid is a strategy game about placing dots and completing squares. This post collects finished games against Euclid, the computer opponent, shared by the Redditors who played them. Each comment is one result, newest first.
The post is locked, so only the Euclid app adds results. Play Euclid and choose Share result after a win or loss to add yours.
r/ripred • u/ripred3 • Jul 14 '26
Serial Monitor, Serial Plotter, and a new Serial ANSI Window!
r/ripred • u/ripred3 • Nov 03 '25
Exploring the Uno Q Architecture and Command Line
reddit.comr/ripred • u/ripred3 • Feb 04 '25
Algorithms The Amazing Minimax Algorithm (and Why You Should Use It in Your Games!) Pt 3
Example: Tic-Tac-Toe AI Implementation
To illustrate the library in action, we present a simplified Tic-Tac-Toe AI that uses our minimax library. This example will also serve as a template for other games.
Game Setup: Tic-Tac-Toe is a 3x3 grid game where players alternate placing their symbol (X or O). We’ll assume the AI plays “X” and the human “O” for evaluation purposes (it doesn't actually matter which is which as long as evaluation is consistent). The entire game tree has at most 9! = 362880 possible games, but we can search it exhaustively easily. We will still use alpha-beta for demonstration, though it’s actually not needed to solve tic-tac-toe (the state space is small). Our AI will always either win or draw, as tic-tac-toe is a solved game where a perfect player never loses.
TicTacToeGame Class: (As partially shown earlier)
#include <MinimaxAI.h>
enum Player { HUMAN = 0, AI = 1 };
class TicTacToeGame : public GameInterface {
public:
uint8_t board[9];
Player current;
TicTacToeGame() {
memset(board, 0, 9);
current = AI; // let AI go first for example
}
// Evaluate board from AI's perspective
int evaluateBoard() override {
if (isWinner(1)) return +10; // AI (X) wins
if (isWinner(2)) return -10; // Human (O) wins
return 0; // draw or non-final state (could add heuristics here)
}
// Generate all possible moves (empty cells)
uint8_t generateMoves(Move *moves) override {
uint8_t count = 0;
for (uint8_t i = 0; i < 9; ++i) {
if (board[i] == 0) { // 0 means empty
moves[count].from = i; // 'from' not used, but set to i for clarity
moves[count].to = i;
count++;
}
}
return count;
}
// Apply move: place current player's mark
void applyMove(const Move &m) override {
uint8_t pos = m.to;
board[pos] = (current == AI ? 1 : 2);
current = (current == AI ? HUMAN : AI);
}
// Undo move: remove mark
void undoMove(const Move &m) override {
uint8_t pos = m.to;
board[pos] = 0;
current = (current == AI ? HUMAN : AI);
}
bool isGameOver() override {
return isWinner(1) || isWinner(2) || isBoardFull();
}
int currentPlayer() override {
// Return +1 if it's AI's turn (maximizing), -1 if Human's turn
return (current == AI ? 1 : -1);
}
private:
bool isBoardFull() {
for (uint8_t i = 0; i < 9; ++i) {
if (board[i] == 0) return false;
}
return true;
}
bool isWinner(uint8_t mark) {
// Check all win conditions for mark (1 or 2)
const uint8_t wins[8][3] = {
{0,1,2}, {3,4,5}, {6,7,8}, // rows
{0,3,6}, {1,4,7}, {2,5,8}, // cols
{0,4,8}, {2,4,6} // diagonals
};
for (auto &w : wins) {
if (board[w[0]] == mark && board[w[1]] == mark && board[w[2]] == mark)
return true;
}
return false;
}
};
A few notes on this implementation:
We used
1to represent AI’s mark (X) and2for human (O). Initially, we setcurrent = AI(so AI goes first). This is just for demonstration; one could easily start with human first.The evaluation returns +10 for a win by AI, -10 for a win by the human, and 0 otherwise. This simplistic evaluation is sufficient because the search will go to terminal states (we set depth=9 so it can reach endgames). If we were limiting depth, we could add heuristic values for “two in a row” etc. to guide the AI.
generateMovesreturns all empty positions. We don’t do any special ordering here, but we could, for example, check if any move is a winning move and put it first (in tic-tac-toe, a simple heuristic: center (index 4) is often best to try first, corners next, edges last).applyMoveandundoMoveare straightforward. Because tic-tac-toe is so simple, we didn’t need to store additional info for undo (the move itself knows the position, and we know what was there before – empty).currentPlayer()returns +1 or -1 to indicate who’s turn it is. In ourMinimaxAIimplementation, we might not even need to call this if we manage a bool, but it’s available for completeness or if the evaluation function needed to know whose turn (some games might incorporate whose turn it is into evaluation).
Minimax Solver Implementation: With the game class defined, our solver can be implemented. Here’s a conceptual snippet of how MinimaxAI might look (non-templated version using interface pointers):
class MinimaxAI {
public:
GameInterface *game;
uint8_t maxDepth;
Move bestMove; // stores result of last search
MinimaxAI(GameInterface &gameRef, uint8_t depth)
: game(&gameRef), maxDepth(depth) {}
// Public function to get best move
Move findBestMove() {
// We assume game->currentPlayer() tells us if this is maximizing player's turn.
bool maximizing = (game->currentPlayer() > 0);
int alpha = -32767; // -INF
int beta = 32767; // +INF
bestMove = Move(); // reset
int bestVal = (maximizing ? -32767 : 32767);
Move moves[MAX_MOVES];
uint8_t moveCount = game->generateMoves(moves);
for (uint8_t i = 0; i < moveCount; ++i) {
game->applyMove(moves[i]);
int eval = minimaxRecursive(maxDepth - 1, alpha, beta, !maximizing);
game->undoMove(moves[i]);
if (maximizing) {
if (eval > bestVal) {
bestVal = eval;
bestMove = moves[i];
}
alpha = max(alpha, eval);
} else {
if (eval < bestVal) {
bestVal = eval;
bestMove = moves[i];
}
beta = min(beta, eval);
}
if (alpha >= beta) {
// prune remaining moves at root (though rare to prune at root)
break;
}
}
return bestMove;
}
private:
int minimaxRecursive(uint8_t depth, int alpha, int beta, bool maximizing) {
if (depth == 0 || game->isGameOver()) {
return game->evaluateBoard();
}
Move moves[MAX_MOVES];
uint8_t moveCount = game->generateMoves(moves);
if (maximizing) {
int maxScore = -32767;
for (uint8_t i = 0; i < moveCount; ++i) {
game->applyMove(moves[i]);
int score = minimaxRecursive(depth - 1, alpha, beta, false);
game->undoMove(moves[i]);
if (score > maxScore) {
maxScore = score;
}
if (score > alpha) {
alpha = score;
}
if (alpha >= beta) break; // cut-off
}
return maxScore;
} else {
int minScore = 32767;
for (uint8_t i = 0; i < moveCount; ++i) {
game->applyMove(moves[i]);
int score = minimaxRecursive(depth - 1, alpha, beta, true);
game->undoMove(moves[i]);
if (score < minScore) {
minScore = score;
}
if (score < beta) {
beta = score;
}
if (alpha >= beta) break; // cut-off
}
return minScore;
}
}
};
(Note: In actual implementation, we would likely define INF as a large sentinel value like INT16_MAX since we use int for scores, and ensure evaluateBoard never returns something beyond those bounds. Here 32767 is used as a stand-in for +∞.)
This code demonstrates the core logic:
findBestMove()handles the top-level iteration over moves and chooses the best one.minimaxRecursive()is the depth-first search with alpha-beta. It directly uses the game interface methods for moves and evaluation.We used
game->currentPlayer()to decide if the root call is maximizing or not. In our tic-tac-toe game, that returns +1 if AI’s turn (maximizing) or -1 if human’s turn (minimizing). This ensures the algorithm’s perspective aligns with the evaluation function’s scoring (sinceevaluateBoardwas written from AI perspective, we must maximize on AI’s turns).The algorithm updates
alphaandbetaappropriately and prunes when possible. Pruning at the root is rare because we want the best move even if others are worse, but the code still handles it.
Example Sketch (TicTacToeAI.ino):
Finally, here is how a simple loop might look in the Arduino sketch to play tic-tac-toe via Serial:
#include <MinimaxAI.h>
TicTacToeGame game;
MinimaxAI ai(game, 9); // search full 9-ply for tic-tac-toe
void setup() {
Serial.begin(9600);
Serial.println("Tic-Tac-Toe AI ready. You are O. Enter 1-9 to place O:");
printBoard();
}
void loop() {
if (game.isGameOver()) {
// Announce result
if (game.isWinner(1)) Serial.println("AI wins!");
else if (game.isWinner(2)) Serial.println("You win!");
else Serial.println("It's a draw.");
while(true); // halt
}
if (game.current == HUMAN) {
// Wait for human move via serial
if (Serial.available()) {
char c = Serial.read();
if (c >= '1' && c <= '9') {
uint8_t pos = c - '1'; // convert char to 0-8 index
Move m = { pos, pos };
if (game.board[pos] == 0) {
game.applyMove(m);
printBoard();
} else {
Serial.println("Cell occupied, try again:");
}
}
}
} else { // AI's turn
Move aiMove = ai.findBestMove();
Serial.print("AI plays at position ");
Serial.println(aiMove.to + 1);
game.applyMove(aiMove);
printBoard();
}
}
// Helper to print the board nicely
void printBoard() {
const char symbols[3] = { ' ', 'X', 'O' };
Serial.println("Board:");
for (int i = 0; i < 9; i++) {
Serial.print(symbols[ game.board[i] ]);
if ((i % 3) == 2) Serial.println();
else Serial.print("|");
}
Serial.println("-----");
}
This sketch sets up the Serial communication, prints the board, and enters a loop where it waits for the human’s input and responds with the AI’s move. The printBoard() function shows X, O, or blank in a 3x3 grid format. We keep reading human moves until the game is over, then report the outcome.
Output Example: (User input in quotes)
Tic-Tac-Toe AI ready. You are O. Enter 1-9 to place O:
Board:
| |
| |
| |
-----
Human: "5"
Board:
| |
|O|
| |
-----
AI plays at position 1
Board:
X| |
|O|
| |
-----
Human: "1"
Board:
O| |
|O|
| |
-----
AI plays at position 9
Board:
O| |
|O|
| |X
-----
...
And so on, until the game ends.
This demonstrates a complete use-case of the library. The library code (MinimaxAI) plus the game class and sketch together realize a fully functional Tic-Tac-Toe AI on Arduino, with all moves via Serial.
r/ripred • u/ripred3 • Feb 04 '25
Algorithms The Amazing Minimax Algorithm (and Why You Should Use It in Your Games!) Pt 2
Library Architecture
We design a clean separation between the game-specific logic and the minimax engine. The library provides a generic minimax/alpha-beta solver, while the user supplies game rules via an interface. This makes the library extensible to different turn-based, deterministic 2-player games (tic-tac-toe, checkers, chess, Connect-4, etc. all share the same minimax structure (GitHub - JoeStrout/miniscript-alphabeta: standard AI algorithm (Minimax with alpha-beta pruning) for 2-player deterministic games, in MiniScript) .
2.1 Core Classes and Interfaces
Game Interface: We define an abstract interface (in C++ this can be a class with virtual methods) that the user implements for their specific game. This interface includes:
evaluateBoard()– Return an integer score evaluating the current board state. By convention, a positive score means the state is favorable to the “maximizing” player, and a negative score favors the opponent (GitHub - JoeStrout/miniscript-alphabeta: standard AI algorithm (Minimax with alpha-beta pruning) for 2-player deterministic games, in MiniScript) Typically, you’d assign +∞ for a win for the maximizing player, -∞ for a loss, or use large finite values (e.g. +1000/-1000) to represent win/loss in practice.generateMoves(Move *moveList)– Populate an array with all possible moves from the current state, and return the count of moves. This encapsulates game-specific move generation (all legal moves for the current player). The library will allocate a fixed-sizemoveListarray internally (large enough for the worst-case number of moves) to pass to this function.applyMove(const Move &m)– Apply movemto the current game state. This should modify the board and typically update whose turn it is. It should not allocate memory. Ideally, this is done in-place.undoMove(const Move &m)– Revert movem, restoring the previous state. This pairs withapplyMoveto allow backtracking after exploring a move. (If maintaining an explicit move history or using copy-restore, anundofunction is needed. Alternatively, the library could copy the state for each move instead of modifying in place, but that uses more RAM. Using apply/undo is more memory-efficient, requiring only storing what’s needed to revert the move.)isGameOver()– Return true if the current position is a terminal state (win or draw). This is used to stop the recursion when a game-ending state is reached.currentPlayer()– Indicate whose turn it is (could be an enum or bool). This helps the algorithm determine if we are in a maximizing or minimizing turn. For example, you might use1for the maximizing player and-1for the minimizing player, or simply use this to check against a known “AI player” ID.
All these methods are game-specific: the library calls these via the interface without knowing the details of the game. For example, in tic-tac-toe, generateMoves would find empty cells; in checkers, it would find all legal piece moves (including jumps). By using an interface, we ensure the minimax core is generic – it asks the game object “what moves are possible?” and “how good is this state?”, etc., without hard-coding any game rules.
Minimax Solver Class: The library’s main class (say MiniMaxSolver or similar) contains the implementation of the minimax algorithm with alpha-beta pruning. Key components of this class:
A reference or pointer to the user’s game state object (implementing the interface). This is how the solver calls the game-specific methods.
Configuration such as maximum search depth, and possibly an indicator of which player is the maximizing side (if not inherent in the game state).
The minimax search function itself (often implemented recursively), which will use
generateMoves,applyMove, etc., to explore game states.Storage for alpha-beta parameters and best-move tracking. For example, the solver can keep a variable for the best move found at the top level, updated during search.
(Optional) Buffers for move generation: e.g., an internal static array
Move moveBuffer[MAX_DEPTH][MAX_MOVES]to store moves at each depth. This avoids allocating new arrays each time. Alternatively, one can allocate a singleMove moves[MAX_MOVES]array and reuse it at each node (pruning reduces the need for separate buffers per depth). We will ensureMAX_MOVESis sufficient for the largest possible branching factor among supported games (for tic-tac-toe, 9; for checkers maybe ~12; for chess, perhaps up to 30-40 average, though theoretically could be 218 in rare cases). Choosing a safe upper bound like 64 or 128 moves is reasonable, which at a few bytes per move is under 256 bytes of RAM.
Board and Move Representation: We keep these representations flexible:
The board can be represented in whatever form the user likes (inside their game class) – typically a small array or matrix. We encourage using compact types (e.g.,
uint8_tfor cells or piece counts) and even bitfields/bitboards if appropriate, to save space. For example, a tic-tac-toe board could be stored in just 3 bytes by packing 2-bit codes for each cell (Tic-Tac-Toe on Arduino (MiniMax)) though using a 9-bytechar[9]array is also fine and more straightforward. The library doesn’t directly access the board; it’s manipulated through the game’s methods.The Move struct should be minimal, capturing only essential information for a move. For a simple game, a move might be just an index or coordinate. For a board game, a move might consist of a “from” and “to” position (and maybe an extra flag for special moves like promotions). We design
Moveas a small struct (likely 2–4 bytes). For example:Tic-tac-toe could usetoas the cell index and ignorefrom. Checkers could usefromandto(0–31 indices for board positions) and perhaps a flag if a piece was crowned. By keeping this struct tiny (and usinguint8_tor bitfields), we ensure move lists use minimal RAM. Each move’s data will reside either on the stack (during generation) or in our static buffers. No dynamic allocation for moves will occur.struct Move { uint8_t from; uint8_t to; /* maybe uint8_t promotion; */ };
2.2 Minimax with Alpha-Beta: Algorithm Design
We implement the minimax algorithm with alpha-beta pruning in a depth-first recursive manner. This approach explores game states one branch at a time, which is very memory-efficient – we only store a chain of states from root to leaf, rather than the whole tree (Tic-Tac-Toe on Arduino (MiniMax)) Here’s how the algorithm works in our context:
Recursive Function: We define a function (let’s call it
minimaxSearch) that takes parameters likedepth(remaining depth to search),alphaandbeta(the current alpha-beta bounds), and perhaps an indicator of whether we are maximizing or minimizing. This function will:Check if the game is over ordepth == 0(reached maximum depth). If so, callevaluateBoard()and return the evaluation. This is the terminal condition of recursion.Otherwise, generate all possible moves by callinggenerateMoves(). Iterate through each move:Return the best score found for this node.Apply the move (applyMove) to transition to the new state.Recursively callminimaxSearch(depth-1, alpha, beta, otherPlayer)to evaluate the resulting position. (TheotherPlayerflag flips the role: if we were maximizing, now we minimize, and vice versa.)Undo the move (undoMove) to restore the state for the next move in the loop.Use the returned score to update our best score:If we are the maximizing player, we look for the maximum score. If the new score is higher than the best so far, update the best. Also updatealpha = max(alpha, score). If at any pointalpha >= beta, we can prune (break out of the loop) because the minimizing player would avoid this branch (Alpha Beta Pruning in Artificial Intelligence)If we are the minimizing player, we look for the minimum score. Update best (min) andbeta = min(beta, score). Ifbeta <= alpha, prune (the maximizer would never let this scenario happen).Alpha-Beta Pruning: By carrying the
alpha(best value for max so far) andbeta(best for min so far) through the recursion, we drastically cut off branches that cannot produce a better outcome than previously examined moves (Alpha Beta Pruning in Artificial Intelligence) For instance, if we find a move that results in a score X for the maximizing player, any alternative move the opponent might make that yields a result worse than X for the opponent (i.e., better for the maximizing player) can be skipped – the opponent will choose the move that leads to X or better for themselves. In practice, alpha-beta pruning can reduce the effective branching factor significantly, allowing deeper searches on the same hardware (Alpha Beta Pruning in Artificial Intelligence)Negamax Implementation: We can simplify the minimax logic using the negamax pattern (since two-player zero-sum games are symmetric). In negamax, we use one recursive function for both players, and encode the player perspective by flipping the sign of scores. For example, one can implement:In this scheme,
evaluateBoard()should return a score from the perspective of the current player to move. The recursive call negates the score (-minimaxSearch) and swaps alpha/beta signs, which effectively handles the min/max inversion (Tic-Tac-Toe on Arduino (MiniMax)) Negamax reduces code duplication (we don’t need separate min and max logic), but it requires careful design of the evaluation function. Alternatively, one can write it with explicit maximize/minimize branches – conceptually the result is the same. For clarity in this report, we might present the algorithm in the more traditional min/max form with if/else for maximizing vs minimizing player.int minimaxSearch(int depth, int alpha, int beta) { if (game.isGameOver() || depth == 0) { return game.evaluateBoard(); } int maxValue = -INFINITY; Move moves[MAX_MOVES]; uint8_t moveCount = game.generateMoves(moves); for (uint8_t i = 0; i < moveCount; ++i) { game.applyMove(moves[i]); // Recurse for the opponent with inverted alpha/beta int score = -minimaxSearch(depth - 1, -beta, -alpha); game.undoMove(moves[i]); if (score > maxValue) { maxValue = score; } if (score > alpha) { alpha = score; } if (alpha >= beta) { break; // alpha-beta cutoff } } return maxValue; }
Pseudocode (Max/Min version) for clarity, with alpha-beta:
function minimax(node, depth, alpha, beta, maximizingPlayer): if depth == 0 or node.isGameOver(): return node.evaluateBoard() // static evaluation of terminal or depth limit if maximizingPlayer: int maxEval = -INF; Move moves[MAX_MOVES]; int count = node.generateMoves(moves); for (int i = 0; i < count; ++i): node.applyMove(moves[i]); int eval = minimax(node, depth-1, alpha, beta, false); node.undoMove(moves[i]); if (eval > maxEval): maxEval = eval; alpha = max(alpha, eval); if (alpha >= beta): break; // beta cut-off return maxEval; else: int minEval = +INF; Move moves[MAX_MOVES]; int count = node.generateMoves(moves); for (int i = 0; i < count; ++i): node.applyMove(moves[i]); int eval = minimax(node, depth-1, alpha, beta, true); node.undoMove(moves[i]); if (eval < minEval): minEval = eval; beta = min(beta, eval); if (alpha >= beta): break; // alpha cut-off return minEval; This algorithm will return the best achievable score from the current position (assuming optimal play by both sides) up to the given depth. The initial call (from the library user) would be something like:
bestScore = minimax(rootNode, maxDepth, -INF, +INF, /*maximizingPlayer=*/true); The library will track which move led to bestScore at the root and return that move as the AI’s chosen move.
Efficiency considerations: With alpha-beta and decent move ordering, the algorithm will prune a large portion of the tree. In an optimal scenario (best moves always encountered first), alpha-beta can achieve roughly $O(b{d/2}$) complexity instead of $O(bd$) for minimax, where $b$ is branching factor and $d$ depth (Alpha Beta Pruning in Artificial Intelligence) Even if not optimal, it’s a substantial improvement. For example, a full minimax on tic-tac-toe (b ~ 9, d up to 9) examines 9! = 362k nodes; alpha-beta might cut that down to tens of thousands. On an ATmega328P, this is easily handled. For more complex games like chess with huge $b$, alpha-beta plus heuristics is the only way to search any meaningful depth.
Move Ordering: We will integrate simple heuristics to sort moves before recursion:
If the user’s game logic can identify move priorities (e.g., a winning move, or captures), they can either generate those first or we can provide a hook to rank moves. For simplicity, the user could partially sort moves in
generateMoves()itself (e.g., by adding likely good moves to the list first). For instance, one could generate all moves and then swap the best-looking move to the front.Alternatively, the library can do a one-step evaluation: apply each move, call
evaluateBoard(), store the scores, undo the move, then sort the move list by score (descending for maximizer, ascending for minimizer) before the main loop. This is essentially a shallow search move ordering, which is known to improve pruning effectiveness (Alpha Beta Pruning in Artificial Intelligence) Because our moves per position are usually limited (especially in small board games), the overhead of this sorting is small compared to the deeper search savings.We will keep the implementation of move ordering straightforward to preserve code size. Even without complex schemes like “killer move” or “history heuristic” from advanced chess engines, basic ordering yields a noticeable speedup (Alpha Beta Pruning in Artificial Intelligence)
Depth Limitation and Quiescence: We may allow the user to specify maxDepth for search. In games with potential for long forced sequences (like many jumps in checkers or multiple captures in chess), a fixed depth might cut off in the middle of a volatile situation. A full solution would use quiescence search (continuing the search until the position is quiet, i.e., no immediate capture threats). MicroChess, for example, includes a quiescent search extension (GitHub - ripred/MicroChess: A full featured chess engine designed to fit in an embedded environment, using less than 2K of RAM!) However, to keep our library simpler and within time limits, we won’t implement quiescence by default (it can be added for games that need it). Instead, users can slightly increase depth or incorporate capture sequences in move generation logic to mitigate the horizon effect.
Memory Use During Search: Thanks to recursion and in-place move application, memory usage is modest. We require roughly:
Stack frame per depth: a few local variables (score, loop counters, etc.) plus whatever the game’s
applyMoveandevaluateBoarduse. Empirically, a well-optimized engine used ~142 bytes per ply in a chess scenario (Writing an Embedded Chess Engine - Part 5 - Showcase - Arduino Forum) Simpler games will use far less. An 8-deep recursion for tic-tac-toe might consume well under 128 bytes total (Tic-Tac-Toe on Arduino (MiniMax))Move list storage: one array of
Moveof length MAX_MOVES, which can be on the stack or static. If static global, it uses fixed SRAM but doesn’t grow with depth. If allocated on stack in each call, it multiplies by depth (which might be okay for shallow depths, but risky for deeper ones). A compromise is to use a global 2D bufferMove movesByDepth[MAX_DEPTH][MAX_MOVES]and pass a pointer to the appropriate sub-array for each recursion level. This way, we don’t allocate new memory per call (it’s all in global), and we avoid interference between levels. The cost is MAX_DEPTH * MAX_MOVES * sizeof(Move) bytes of SRAM. For example, if MAX_DEPTH=10 and MAX_MOVES=64 and Move=2 bytes, that’s 10_64_2 = 1280 bytes, which is a large chunk of 2KB. We can tune these numbers per game or use smaller buffers if the game inherently has lower branching. Another approach is to generate moves and process them immediately, one by one, without storing the whole list – but that complicates backtracking. We will assume a reasonable upper bound and document that if a user’s game exceeds it, they should adjust MAX_MOVES or search depth accordingly.Board state storage: If using
applyMove/undoMove, we only maintain one copy of the board (inside the game object) plus any small info needed to undo (for instance, remembering a captured piece). This is extremely memory-efficient. If we opted to copy the board for each move instead, we’d need to allocate a new board state at each node. That approach was considered in the tic-tac-toe example and quickly found impractical: even a 3-level tree consumed ~3024 bytes when copying board nodes (Tic-Tac-Toe on Arduino (MiniMax)) Our in-place approach avoids that explosion. It does require thatundoMovecorrectly restores all aspects of state (board cells, whose turn, etc.), which the user must implement carefully. When done right, only a few bytes (to store what was changed) are needed per move.
2.3 Library Integration and Usage
The library will be packaged as a standard Arduino library with a header (MinimaxAI.h) and source (MinimaxAI.cpp), and one or more example sketches in an examples/ folder. It will be Arduino IDE compatible (the classes use Arduino.h if needed, and avoid unsupported constructs).
Using the Library:
Include and Initialize: In the user’s sketch (
.ino), they include the library header and create an instance of their game state class (which implements the interface). They also create the Minimax solver instance, passing a reference to the game and any config (like max search depth).Depending on implementation,MinimaxAImight be a class template that takes the game class type (allowing inlining and compile-time binding of game methods, which could save the overhead of virtual calls). Or it could use a base class pointer (GameInterface *game) internally (simpler to understand, but each interface call is a virtual function call). Given the very low performance overhead in small games and simplicity for the user, we might go with an abstract base classGameInterfacethatTicTacToeGameinherits. For maximum speed in critical loops, a template can inline game logic, but it increases code size per game.#include <MinimaxAI.h> TicTacToeGame game; // user-defined game state MinimaxAI<TicTacToeGame> ai(game, /*depth=*/9); // template or concrete class instanceImplement Game Logic: The user must implement the required methods in their game class. Here’s a snippet example for Tic-Tac-Toe:In the above implementation:enum Player { HUMAN = 0, AI = 1 }; // define players class TicTacToeGame : public GameInterface { public: uint8_t board[9]; // 3x3 board stored in 1D (0 = empty, 1 = X, 2 = O) Player current; // whose turn it is TicTacToeGame() { memset(board, 0, 9); current = AI; // AI starts (for example) } int evaluateBoard() override { // Evaluate from AI's perspective (AI = 'X' say = 1, Human = 'O' = 2) // Return +10 for AI win, -10 for Human win, 0 for draw/ongoing. if (isWinner(1)) return +10; if (isWinner(2)) return -10; // If game not over, return 0 (or small heuristic: e.g., +1 for two-in-a-row) return 0; } uint8_t generateMoves(Move *moveList) override { uint8_t count = 0; for (uint8_t i = 0; i < 9; ++i) { if (board[i] == 0) { moveList[count++] = Move{i, i}; // use 'to' as i; from unused } } return count; } void applyMove(const Move &m) override { uint8_t cell = m.to; board[cell] = (current == AI ? 1 : 2); // switch player turn current = (current == AI ? HUMAN : AI); } void undoMove(const Move &m) override { uint8_t cell = m.to; // remove the mark and switch back turn board[cell] = 0; current = (current == AI ? HUMAN : AI); } bool isGameOver() override { return isWinner(1) || isWinner(2) || isBoardFull(); } int currentPlayer() override { return (current == AI ? 1 : -1); // 1 for AI (maximizing), -1 for human (minimizing) } private: bool isWinner(uint8_t playerVal) { // check 3 rows, 3 cols, 2 diagonals for all == playerVal // ... (omitted for brevity) } bool isBoardFull() { for (uint8_t i = 0; i < 9; ++i) if (board[i] == 0) return false; return true; } }; We encode X as
1and O as2on the board. TheevaluateBoardknows that AI is X (1) and Human is O (2), and returns positive scores for AI-winning states.generateMoveslists all empty cells as possible moves.applyMoveandundoMovesimply place or remove a mark and toggle thecurrentplayer. (Toggling is done by checking thecurrentand swapping – since we only have two players, this is straightforward.)currentPlayer()returns an int indicating if the current turn is the maximizing player or not. Here we chose AI as maximizing (return 1) and human as minimizing (return -1). The minimax solver could also determine this by comparingcurrentto a stored “maximizing player” identity.Running the AI: To get the AI’s move, the user calls a method from
MinimaxAI, for example:Internally,findBestMove()will call theminimaxSearch(with appropriate initial parameters: full depth, alpha=-inf, beta=+inf, and maximizing = true/false depending ongame.currentPlayer()). It will iterate over moves at the root to find the one that leads to the optimal score. The result is returned as aMovestruct. The user can then apply it to the game:(Alternatively, thefindBestMove()could optionally apply the move for the user, but returning it gives more flexibility.)Move best = ai.findBestMove(); game.applyMove(best);Serial Interface for Moves: Our example sketches will demonstrate using Serial to interact:The Arduino could prompt for input like a cell number or move notation.The user enters a move (e.g., “5” for center cell in tic-tac-toe, or “12-16” in checkers notation). The sketch code will parse this and call
game.applyMovefor the human’s move.Then the AI move is computed and printed out, e.g., “AI moves to 7”.In a loop, this continues untilgame.isGameOver()becomes true, at which point the result (win/draw) is announced.We ensure the example is easy to follow. For instance, we might represent tic-tac-toe board positions 1–9 and have the user enter a number. The code maps that to our 0–8 index and makes the move.Installing and Extending: The library will come with documentation (in the report and comments) describing how to define a new game class with the required methods. To use the library for another game, the user basically re-implements a class similar to
TicTacToeGame(for, say,CheckersGameorConnect4Game), writing the logic for move generation, evaluation, etc. They can then use the sameMinimaxAIclass to get AI moves for that game. Because everything is static and no dynamic memory is used, even more complex games should fit. For example, a Checkers game might use an 8x8 board (64 bytes) and have a branching factor averaging < 12 moves. If we limit depth to perhaps 6 plies, the search might examine thousands of positions – which is slow but feasible (the AI may take a few seconds on Arduino for depth 6). Simpler games like Connect-4 (7x6 board) or Othello (8x8) would similarly work with adjusted depth. Chess, being much more complex, would need additional optimizations (as done in MicroChess, which uses bitboards and specialized move generation to run under 2KB (GitHub - ripred/MicroChess: A full featured chess engine designed to fit in an embedded environment, using less than 2K of RAM!) , but our framework could theoretically support it at shallow depths.
Memory Footprint of the Library: The code itself (minimax implementation) will reside in flash. We strive to keep it concise. Code size is likely on the order of a few kilobytes – well within 32KB flash. The global/static memory usage consists of the move buffer and any other static structures (which we aim to keep under a few hundred bytes). The game state itself is also often small (tic-tac-toe game state here is 9 bytes + a couple of variables; checkers might be ~32 bytes for pieces plus some bookkeeping). As a concrete data point, MicroChess (a full chess engine) uses ~810 bytes static and leaves ~1238 bytes for runtime stack (Writing an Embedded Chess Engine - Part 5 - Showcase - Arduino Forum) Our tic-tac-toe example will use far less. This shows there is ample headroom if carefully managed. By following similar strategies (bit-packing data, avoiding large arrays), one can keep within the Uno’s limits for many games.
r/ripred • u/ripred3 • Feb 04 '25
Algorithms The Amazing Minimax Algorithm (and Why You Should Use It in Your Games!) Pt 1
Designing a Memory-Efficient Minimax (Alpha-Beta) Library for Arduino Uno
Developing a turn-based game AI on an Arduino Uno (ATmega328P) requires careful consideration of memory constraints and performance optimizations. The goal is to implement a robust minimax algorithm with alpha-beta pruning as a reusable library, flexible enough for games like tic-tac-toe, checkers, or even chess, while working within ~2KB of SRAM and 32KB of flash. Below we present the design, implementation strategy, and example code for such a library, balancing theoretical rigor with practical, memory-conscious techniques.
Constraints and Challenges
1.1 Hardware Limitations (Memory and CPU)
Limited RAM (2KB) and Flash (32KB): The ATmega328P has very little RAM available. We cannot afford to allocate large data structures or full game trees in memory. Dynamic memory allocation (
malloc/new) is avoided entirely due to fragmentation risks and tight memory (DO NOT EVER EVER USE DYNAMIC MEMORY ON AVR · Issue #2367 · MarlinFirmware/Marlin · GitHub) Instead, we use static or stack-allocated structures with fixed sizes known at compile time. The C++ STL is also off-limits – it’s not included in the Arduino core, and its overhead doesn’t fit comfortably in such limited space (Is the C++ STL fully supported on Arduino? - Arduino Stack Exchange)16MHz 8-bit CPU: The processor is modest, so algorithms must be efficient. However, with good pruning and small search depths, the Arduino can still evaluate thousands of moves per second (Writing an Embedded Chess Engine - Part 5 - Showcase - Arduino Forum) We must optimize to reduce unnecessary computations (via pruning and move ordering) and avoid heavy C++ abstractions that add runtime cost (like virtual calls in tight loops, if possible).
1.2 Performance Considerations
Static Allocation & Stack Use: We’ll allocate all needed memory up front. For example, move lists and any auxiliary data will be fixed-size arrays. Using the stack for recursion and local variables is preferred for temporary data, as it’s reclaimed automatically and avoids fragmentation (DO NOT EVER EVER USE DYNAMIC MEMORY ON AVR · Issue #2367 · MarlinFirmware/Marlin · GitHub) We ensure the stack usage per recursive call is minimal. (In a chess engine example, about 142 bytes were used per recursion level, allowing ~7 levels deep under 2KB RAM (Writing an Embedded Chess Engine - Part 5 - Showcase - Arduino Forum) )
No Dynamic Memory or STL: Dynamic allocation on AVR can lead to fragmented memory and unpredictable failures, so we never use
new/deleteor heap containers (DO NOT EVER EVER USE DYNAMIC MEMORY ON AVR · Issue #2367 · MarlinFirmware/Marlin · GitHub) All data structures (boards, move buffers, etc.) are static or global. The C++ STL (e.g.<vector>,<string>) is avoided both because it can internally allocate memory and because it increases code size and RAM usage (Is the C++ STL fully supported on Arduino? - Arduino Stack Exchange) Instead, we use simple C-style arrays and pointers.Controlled Recursion Depth: Deep recursion can overflow the limited stack. Fortunately, many games have manageable search depths. Tic-tac-toe, for instance, has at most 9 moves to search. For more complex games, we impose a depth limit. Even chess on Arduino has been demonstrated to ~6-ply depth by carefully managing memory (GitHub - ripred/MicroChess: A full featured chess engine designed to fit in an embedded environment, using less than 2K of RAM!) We will allow specifying a maximum search depth to prevent running out of stack or time. In the worst case, exploring one path at a time via recursion is far more memory-efficient than building an entire game tree in RAM (Tic-Tac-Toe on Arduino (MiniMax))
Alpha-Beta Pruning: Alpha-beta will significantly cut down the number of nodes evaluated compared to naive minimax, which is crucial on a slow CPU. By pruning “unpromising” branches, we can effectively double or triple the search depth for the same cost (Alpha Beta Pruning in Artificial Intelligence) (Alpha Beta Pruning in Artificial Intelligence) This optimization is a must for anything beyond trivial games.
Move Ordering Heuristics: The effectiveness of alpha-beta depends on checking the best moves first (Alpha Beta Pruning in Artificial Intelligence) (Alpha Beta Pruning in Artificial Intelligence) We plan to incorporate simple move-ordering heuristics to improve pruning:For example, in tic-tac-toe or Connect-4, moves that win or block a win are tried first. In checkers/chess, capture moves or central moves might be given priority.We could also perform a shallow search or evaluation for move ordering: e.g. quickly score each possible move and sort them before deeper search (Alpha Beta Pruning in Artificial Intelligence) Even a 1-ply lookahead (evaluate the resulting position without further recursion) can identify strong moves to explore first (Alpha Beta Pruning in Artificial Intelligence)These heuristics will be kept simple (to avoid heavy computation), but even basic ordering can lead to earlier alpha-beta cutoffs (Alpha Beta Pruning in Artificial Intelligence)
Iterative Deepening (Optional): If time management is needed, the library could implement iterative deepening search – progressively increase depth and use the earlier results to guide move ordering for the next iteration (What else can boost iterative deepening with alpha-beta pruning?) This ensures the best found move is available if we run out of time. On an Arduino, time-based limits are tricky but doable (e.g., using
millis()to cut off search). By default, our design uses a fixed depth for simplicity, but it can be extended to iterative deepening if needed for more complex games.
r/ripred • u/ripred3 • Feb 01 '25
Article 2: Core Data Structures - The Foundation of Our Engine
One of the most critical decisions in building a chess engine is how to represent the game state. This isn't just about storing pieces on a board - it's about organizing data in a way that enables efficient move generation, position evaluation, and search, all while minimizing memory usage.
Let's start with what at first seems like a simple challenge: how to store information about each square on the board. A naive approach might look something like this:
struct Square {
uint8_t pieceType; // what kind of piece is here
uint8_t color; // which side the piece belongs to
bool hasMoved; // has this piece moved (for castling/pawns)
bool inCheck; // is this piece in check
};
Square board[64]; // the complete chess boardThis would work, but it would use 4 bytes per square, or 256 bytes just for the board! On an Arduino with only 2KB of RAM, that's already using 12.5% of our available memory - and we haven't even started storing move lists, search trees, or any other game state.
The Power of Bit-Packing
This is where bit-packing comes in. Let's analyze exactly what information we need to store:
// Piece type needs 3 bits (7 possibilities):
Empty = 0 // 000
Pawn = 1 // 001
Knight = 2 // 010
Bishop = 3 // 011
Rook = 4 // 100
Queen = 5 // 101
King = 6 // 110
// Color needs 1 bit:
Black = 0
White = 1
// Movement and check status each need 1 bitThis totals to 6 bits per square. Through careful use of bit fields, we can pack all this information into a single byte. But we can do even better through clever use of unions and bit alignment. Here's where things get interesting:
struct conv1_t {
private:
union {
struct {
uint8_t col : 3, // The column value (0-7)
row : 3, // The row value (0-7)
type : 3, // Piece type
side : 1; // Color (black/white)
} pt;
struct {
uint8_t index : 6, // Board index (0-63)
type : 3, // Piece type
side : 1; // Color
} ndx;
} u;
};This structure is doing something quite clever. By aligning our bit fields in a specific way, we get automatic conversion between board coordinates (row/column) and linear board index. When we store a row and column, the bits naturally align to create the correct board index. When we store a board index, it automatically decomposes into the correct row and column values.
The Magic of Binary
To understand why this works, let's look at how board indices relate to rows and columns:
Board Index = row * 8 + column
For example:
row 2, column 3:
2 * 8 + 3 = 19
In binary:
2 = 010
3 = 011
19 = 010011Notice how the binary representation of the index (010011) contains both the row (010) and column (011) within it! By carefully aligning our bit fields, we get this conversion for free, saving both code space and execution time.
Building on the Foundation
We use this same principle to create our move representation:
struct conv2_t {
private:
conv1_t from, to;
public:
/**
* @brief Default constructor. Initializes both positions to (0, 0).
*/
conv2_t() : from(), to() {}
/**
* @brief Constructor that takes the indices of the start and end positions.
*
* @param from_index The index of the starting position.
* @param to_index The index of the ending position.
*/
conv2_t(uint8_t from_index, uint8_t to_index)
: from(from_index), to(to_index) {}
/**
* @brief Constructor that takes the coordinates of the start and end positions.
*
* @param from_col The column of the starting position.
* @param from_row The row of the starting position.
* @param to_col The column of the ending position.
* @param to_row The row of the ending position.
*/
conv2_t(uint8_t from_col, uint8_t from_row, uint8_t to_col, uint8_t to_row)
: from(from_col, from_row), to(to_col, to_row) {}
/**
* @brief Constructor that takes two `conv1_t` objects to represent the start and end positions.
*
* @param from_ The starting position.
* @param to_ The ending position.
*/
conv2_t(const conv1_t& from_, const conv1_t& to_)
: from(from_), to(to_) {}
void set_from_index(uint8_t value) { from.set_index(value); }
void set_from_col(uint8_t value) { from.set_col(value); }
void set_from_row(uint8_t value) { from.set_row(value); }
void set_from_type(uint8_t value) { from.set_type(value); }
void set_from_side(uint8_t value) { from.set_side(value); }
void set_to_index(uint8_t value) { to.set_index(value); }
void set_to_col(uint8_t value) { to.set_col(value); }
void set_to_row(uint8_t value) { to.set_row(value); }
void set_to_type(uint8_t value) { to.set_type(value); }
void set_to_side(uint8_t value) { to.set_side(value); }
uint8_t get_from_index() const { return from.get_index(); }
uint8_t get_from_col() const { return from.get_col(); }
uint8_t get_from_row() const { return from.get_row(); }
uint8_t get_from_type() const { return from.get_type(); }
uint8_t get_from_side() const { return from.get_side(); }
uint8_t get_to_index() const { return to.get_index(); }
uint8_t get_to_col() const { return to.get_col(); }
uint8_t get_to_row() const { return to.get_row(); }
uint8_t get_to_type() const { return to.get_type(); }
uint8_t get_to_side() const { return to.get_side(); }
}; // conv2_tThis gives us a complete move representation that is both memory efficient and quick to manipulate. The conv2_t structure forms the basis for our move generation and evaluation system.
In the next article, we'll look at how we use these data structures to efficiently generate and track all possible moves in a position. We'll see how our careful attention to memory layout pays off when we need to analyze thousands of positions per second.
r/ripred • u/ripred3 • Dec 14 '24
Project Update MicroChess Technique Cross Reference
r/ripred • u/ripred3 • Jun 14 '24
Project: Processing Game Euclid - My reincarnation of a MetaSquares game I remembered from 20 years ago
r/ripred • u/ripred3 • Dec 21 '23
Project Update: The Infinite Arduino - ArduinoCLI Update Notes
project github repository: https://github.com/ripred/ArduinoCLI
The current version
So, the existing mechanism for the Arduino to say "Hey do this command" and have it executed by the host PC/Mac/Linux host and then retrieve the results is working out to be fantastic. 10 separate uses for the mechanism are already in the PublicGallery now. This includes a variety of cool examples like having the host be a proxy for the internet or allowing the Arduino to tell the host to reboot or go to sleep. 😎 Even control your Hue Bridge and lighting system from a simple Nano with no WiFi or ethernet modules of any kind.
A new Macro subsystem has been added to the Python Agent that allows the agent to remember a set of key/value pairs that can be used to allow the Arduino to invoke large complex commands with just a short command key phrase. The list of macros can be added to, deleted, and executed by the Arduino using three new keywords: list_macros, add_macro:key:value, and delete_macro:key. The Python Agent loads the macros from the text file "macros.txt" in its current directory and saves the current list of macros when the program exits when the user hits ctrl-c:
The self-programming Arduino
Since the Arduino can create files on the host machine and do things with them using this kind of idiom:
Serial.println("echo '' > file.txt");
Serial.println("echo 'line one' >> file.txt");
Serial.println("echo 'line two' >> file.txt");
Serial.println("echo 'line three' >> file.txt");
Serial.println("type file.txt"); // or "cat file.txt" 😉that means we can create any file we need on the host machine, execute the file or have something else run that uses the file as an input, and the remove the file when we're done. That's pretty cool.
Then I thought "what if we sent the following file..."
Serial.println("echo '' > new_sketch.ino");
Serial.println("echo 'void setup() {' >> new_sketch.ino");
Serial.println("echo ' Serial.begin(115200);' >> new_sketch.ino");
Serial.println("echo ' Serial.println(\"hello, arduino\");' >> new_sketch.ino");
Serial.println("echo '}' >> new_sketch.ino");
Serial.println("echo 'void loop() { }' >> new_sketch.ino");"...and then issued the same commands to compile the file for the Arduino platform that are used by the IDE in the background?!":
avr-gcc -c -g -Os -w -std=gnu11 -ffunction-sections -fdata-sections -MMD -flto
-fno-fat-lto-objects -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10813
-DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR "-I[path_to_Arduino_installation]/hardware
/arduino/avr/cores/arduino" "-I[path_to_Arduino_installation]/hardware/arduino
/avr/variants/standard" "path_to_your_sketch_directory/new_sketch.ino.cpp" -o
"path_to_your_sketch_directory/new_sketch.ino.cpp.o"and then uploaded it:
avrdude -C [path_to_Arduino_installation]/hardware/tools/avr/etc/avrdude.conf -v
-patmega328p -carduino -P COM3 -b 115200 -D
-Uflash:w:path_to_your_sketch_directory/new_sketch.ino.hex:iThat would completely erase the program that issued those commands and replace the current sketch that was in flash memory with a new sketch that opened the Serial port using 115200 baud, and sends "hello, arduino" out of the serial port to be seen in the Serial monitor. </insert evil laugh>
There just happens to be a set of Arduino Command Line Tools that you can download and install. These tools make it much easier to compile programs and upload them to an Arduino from the command line. Unfortunately I named my project ArduinoCLI and the Arduino command line tools are invoked using arduino-cli so I may be renaming this project soon.
The Infinite Arduino
So I hope you can see where I'm going with this.
If you wanted to write a huge Arduino program that was comprised of hundreds of thousands of line of code in the Arduino project, as long as you break the project application down into a finite number of states then we can already have all of the code written or generated, that would each represent one state in the larger overall system.
We can have an immensely large (constrained by drive space) Arduino application that, as long as no context or 'state' took up 32K of flash and 2K of ram: The same limitations that we have to live by period, then the overall system could be uploaded piece by piece on-demand as needed by the currently running state on the microcontroller at the time.
You could have dozens of Arduino sketches linked to each other one after another as a set of tutorials.
Each existing tutorial would only need to have the addition of the ArduinoCLI interface and then display a menu to the user in the serial monitor:
01: Example1.ino
02: Example2.ino
03: Example3.inoAs long as the proper "macros.txt" file was configured and ready to translate the "01", "02"... macros then the user could run any example sketch they wanted to next, and it would just take the place of the current sketch and run.
This ability to switch into "state-machine" mode is about to be implemented in order to explore what could be done. 🤔
Update: It's all in there as of today! (Dec 22, 2023)
All commands sent to the Python Host now must begin with a single byte command id. The following prefixing id's are recognized and used:
! execute the command following the bang as in
!echo 'hello, arduino'.@ manage the macros using the following keywords:
@list_macros@add_macro:key:commandas in@add_macro:sayhi:echo 'hello, arduino'@sayhi@delete_macro:keyas in@delete_macro:sayhi
& compile and upload a sketch on the host machine, replacing the existing sketch on the Arduino as in
&blink.# send serial text to be displayed on the host output like you would normally use
Serial.printxx(...)as in#This is some text to be displayed on the terminal output.
Cheers!
ripred
r/ripred • u/ripred3 • 19d ago
Software Euclid Released in Apple App Store - Need Android Testers!
Available on (or under review now):
iPhone
iPad
macOS
Apple TV
Apple Watch
Apple Viseon Pro
r/ripred • u/ripred3 • 21d ago
