Canaux de discussion
Bienvenue, prenez place !
Discussions est votre espace pour apprendre à connaître vos pairs, relever ensemble de plus grands défis et vous amuser en chemin.
- Vous souhaitez voir les dernières mises à jour ? Suivez les Highlights !
- Vous recherchez des techniques pour améliorer vos compétences MATLAB ou Simulink ? Tips & Tricks est juste pour vous !
- Vous souhaitez partager la blague mathématique, le jeu de mots ou le mème parfait ? Ne cherchez pas plus loin que l՚espace Fun !
- Vous pensez qu՚il manque un canal de discussion ? Dites-nous en plus dans Ideas
Discussions mises à jour
INTRODUCTION
When I came across the MATLAB One-Button Game Mini Hack, I wanted to approach it from an engineering perspective.
As a Mechanical Engineering student with practical experience around heavy-duty diesel engines, I decided to build something inspired by a subject I was already familiar with: diesel engine operation and fuel injection timing.
That idea became PISTON PULSE: The Diesel Timing Challenge.
The game combines an animated piston-and-crank mechanism with a circular timing gauge. The player's task is to observe the rotating indicator and press the SPACEBAR at the right moment to achieve a successful injection.
Developing this game taught me several useful lessons about MATLAB programming, game development and working with AI coding assistants. Here are some of them.
1. START WITH A CONCEPT YOU UNDERSTAND
Rather than choosing a random game idea, I drew inspiration from the operation of a four-stroke diesel engine.
My engineering background helped me decide on the theme and understand the mechanical components I wanted to represent.
I would recommend starting with a subject you understand or genuinely find interesting. It makes the development process more meaningful and gives you a better foundation for evaluating the result.
2. USE AI AS A DEVELOPMENT PARTNER
I used Claude AI to assist with the development of PISTON PULSE.
However, I learned that generating code is only one part of the process. You still need to understand the concept, communicate your expectations, test the output and identify areas that need improvement.
I approached the project by discussing the game concept, reviewing the generated implementation and testing it in MATLAB.
My biggest lesson here is that AI can accelerate development, but you still need to guide the process and take responsibility for the final result.
3. UNDERSTAND THE STARTER PROJECT'S STRUCTURE
One of the most important things I learned was understanding the structure required by the competition.
The starter project uses three main function handles:
g.init = @initState;
g.update = @updateState;
g.render = @renderFrame;
Each function has a specific responsibility:
- initState initializes the game and creates the graphics objects.
- updateState handles the game logic, movement and button input.
- renderFrame updates the graphics based on the current game state.
Understanding this structure helped me appreciate why the competition provides a starter project instead of allowing participants to submit just any standalone MATLAB script.
4. MAKE THE ONE-BUTTON INPUT MEANINGFUL
The competition has a simple but important restriction: the player can only use SPACEBAR or a mouse click.
For PISTON PULSE, I made the SPACEBAR the fuel-injection control.
The challenge is not simply pressing a button. It is deciding when to press it based on the timing indicator.
Another important detail is that the framework provides an edge-triggered input through the pressed variable. This means the game receives a signal for each tap rather than continuously detecting whether a key is being held down.
Understanding this helped me design the gameplay around deliberate timing.
5. USE DT FOR TIME-BASED MOVEMENT
The update function receives dt, which represents the time elapsed between frames, in seconds.
A useful practice is to scale movement by dt rather than moving an object by a fixed amount every frame.
For example:
state.x = state.x + state.speed * dt;
This makes movement depend on elapsed time rather than the number of frames processed.
It is an important consideration when developing games that should behave consistently across different computers.
6. CREATE GRAPHICS ONCE AND UPDATE THEM
Another useful lesson from the starter project was the importance of graphics management.
Instead of repeatedly deleting and recreating graphics objects during gameplay, create them during initialization and update their properties during rendering.
For example:
% Create the object during initialization
state.player = rectangle(ax, ...
'Position', [400 300 30 30]);
% Update its position during rendering
state.player.Position = [state.x state.y 30 30];
This approach avoids unnecessary graphics operations and is particularly useful when developing animated games.
7. TEST AND VALIDATE YOUR GAME
I also learned that a game working as a normal MATLAB script does not automatically mean it satisfies the competition requirements.
It is important to test it using the actual competition framework.
The starter project provides these commands:
minihackContest.validate
minihackContest.play
The validation command checks the game against the competition requirements, while play allows you to test the game locally.
I found this particularly useful because it allowed me to identify whether my implementation followed the expected framework before submitting it.
MY BIGGEST TAKEAWAY
Developing PISTON PULSE has been a valuable learning experience.
I started with an engineering concept and gradually turned it into a working one-button game using MATLAB, with AI assistance along the way.
As someone still developing my MATLAB programming skills, completing this project has shown me how much can be learned by taking an idea, experimenting with it and improving it through testing.
My advice to other participants is simple: start with an idea you understand, learn the framework, make the gameplay interesting and don't be afraid to experiment.
I hope someone finds these lessons useful!
PROJECT: PISTON PULSE: The Diesel Timing Challenge
TOOLS: MATLAB and Claude AI.
When I first started developing games for the MATLAB One-Button Game MiniHack competition, my biggest challenge was to create interesting and engaging games using just one button. Most traditional games require multiple controls for movement and other actions. Initially, I struggled to find suitable game concepts, but gradually, I started exploring different possibilities to make effective use of the single-button option.
I used Claude and ChatGPT as AI coding assistants throughout the game development process. For each game, I first developed a concept, visualized the expected output and defined the gameplay, rules, scoring system and user interactions. I then provided detailed prompts to these AI tools to convert my ideas into MATLAB code.
The initial outputs were not always as expected. I followed an iterative development approach by testing the generated code, sharing screenshots, providing specific feedback and correcting errors. I used techniques such as detailed prompting, reference-based prompting, step-by-step development and AI-assisted debugging to continuously improve the graphics, animations and gameplay. I also explored alternative coding approaches.
From a technical perspective, I used separate initialization, update and rendering functions to manage game operations. State-based programming was used to manage different stages of the game. MATLAB functions such as patch, surf, plot3 and hgtransform were used to create 2D and 3D graphics. Trigonometric functions, rotation matrices, coordinate transformations and mathematical equations were used to generate movements and animations. I also implemented randomization, collision detection, scoring mechanisms and dynamic difficulty based on the requirements of each game.
To make effective use of the one-button option, I automated certain game operations and allowed the player to control the most important action. I implemented techniques such as automatic movement, timing-based interactions, visual indicators, automatic cycling through available options and context-based controls. Depending on the game situation, the same button performs different actions, making the games simple to play while requiring concentration, timing and decision-making.
Another major challenge was developing visually attractive games within the character limit specified by the competition. I used alternative programming approaches, vectorization, reusable functions, simplified mathematical expressions and compact graphics operations. Several iterations of code optimization and testing were carried out to reduce the character count while retaining the gameplay and visual quality as much as possible.
My Learning Experience
This competition helped me understand the importance of combining human creativity, mathematical knowledge, programming skills and artificial intelligence.
AI helped me accelerate the development process, but defining the problem, selecting the right approach, making decisions, testing the output and improving the gameplay required continuous human involvement.
One of my biggest learnings is that the quality of AI-generated output depends significantly on how clearly we communicate our ideas and how effectively we evaluate and refine the results.
Thank you, MathWorks, for organizing this wonderful competition and providing a platform to explore creativity and innovation
I invite you all to check out my entries in the MATLAB One-Button Game MiniHack competition. Please try playing the games and explore the different gameplay concepts. If you enjoy playing the games, please give them a like and share your feedback.
Explore and play all my entries:
Happy Gaming!
When I started developing a game for the MATLAB One-Button Game MiniHack, my biggest challenge was deciding how to control a Rubik’s Cube with just one button. A normal cube needs several different moves, and each face can be turned in two directions. How could I give the player these choices with a single click?
I realised that the button did not have to select the face and direction directly. Instead, the game could automatically cycle through the available moves, and the player could click at the right moment. This became the main idea behind my One-Button Cube.

The starting screen with the solved cube.
How I used AI to develop the game
I used an AI tool as a coding assistant to turn my idea into MATLAB code. I described the cube, the one-click restriction, the automatic scramble and the visual guidance I wanted. I refined the approach through prompts, focusing on the game logic, graphics and player experience. The AI helped translate these requirements into functions and mathematical operations. The key was to give clear instructions rather than simply ask for a cube game.
How I implemented the cube in MATLAB
The cube is built from 27 small cubes arranged in a 3 × 3 × 3 grid. Each small cube has a position and a rotation matrix. Coloured stickers are placed on the outer faces. MATLAB patch objects display the cube, while a mathematical camera projection, depth sorting and lighting calculations give it a 3D appearance.
For each turn, the code selects the nine small cubes on the chosen face and rotates them smoothly by 90 degrees. At the end of the animation, the rotation is rounded to exact integer values to avoid numerical drift. The game uses three main functions: init to create the scene, update to handle moves and timing, and render to display the cube and messages.

The cube automatically scrambles at the start of a level.
Making one click do more
I limited the available moves to the red, blue and white faces, with clockwise and counter-clockwise turns for each. The game automatically cycles through these six choices. It stores the reverse of each scramble move in a list, so it knows which move should be undone next. A green highlight identifies that move; yellow indicates that the player should wait.
The same click starts the game, applies a selected move and advances to the next level. A short grace period of up to 0.3 seconds after the correct highlight helps players who click slightly late. This design avoids extra buttons and makes timing the main challenge.
How to play
- Click to start and watch the cube scramble automatically.
- Wait while the highlight cycles through the six possible moves.
- When the outline and arrow turn GREEN and “TAP NOW!” appears, click once.
- Repeat until the cube is solved. Click again to start the next level.

Yellow highlight: wait for the correct move.

Green highlight: click to apply the correct move.
Tips and tricks

Follow the green highlight, even when the face is not green.
- Focus on the highlight colour, not the sticker colour. Green means click; yellow means wait.
- Use the UNDO list at the top to see the next moves. CW means clockwise and CCW means counter-clockwise.
- Avoid repeated or random clicks. A wrong move adds another move to undo, but you can still recover.
- Try to match PAR, the number of original scramble moves. Level 1 starts with three moves; later levels increase the scramble up to eight moves and the selection speed increases.
- There is no countdown. Take your time to learn the rhythm, then try to improve your best time and turn count.
Play the game: One-Button Cube on MATLAB Central
MATSTAR : Mission to the Moon by NRF
One button. One mission. Reach the Moon
I created MATSTAR: Mission to the Moon, a one-button space game for the MATLAB Mini Hack.
The player controls a spacecraft travelling from Earth toward the Moon. The objective is to collect stars, avoid asteroids, and complete the lunar mission using simple controls.
About the MATLAB Code
I developed the game using MATLAB functions and a structured game-state approach.
The main function, game, acts as the entry point and connects the three core parts of the game:
function g = game()
g.init = @initState;
g.update = @updateState;
g.render = @renderFrame;
end
This structure separates the game into three stages:
- Initialization (initState) — Sets up the initial game state, including the spacecraft position, velocity, score, shield, and game status.
- Update (updateState) — Handles gameplay logic such as spacecraft movement, gravity, boost controls, star collection, asteroid collisions, and mission progress.
- Rendering (renderFrame) — Draws the game scene, spacecraft, stars, obstacles, and mission information.
I also used local functions to keep the code organized and easier to maintain.
Gameplay Features:
- Spacebar or mouse-click boost control
- Gravity-based spacecraft movement
- Star collection and scoring
- Asteroid collision detection
- One shield for protection
- Boundary bounce mechanics
- Mission progress from 0% to 100%
- Lunar landing and victory condition
Tips & Tricks I Learned
- Keep the code modular: Separating initialization, updates, and rendering makes the game easier to understand and debug.
- Manage the game state carefully: Variables such as display, position, velocity, score, shield, and mission status need to be updated consistently.
- Test gameplay in small steps: Start with movement, then add obstacles, scoring, and collision logic.
- Use validation before submission: Check the required function structure, function handles, character limit, and restrictions before publishing.
- Keep the gameplay simple: A one-button control scheme can still create an engaging challenge when combined with gravity, obstacles, and timing.
MATSTAR was a fun way to explore MATLAB game development while combining programming logic, physics-inspired movement, and space-themed creativity.
A 450 DPI PNG is easy to insert into a lab report, and a vector PDF keeps line plots and text sharp when zoomed. Pass the same axes handle to both exportgraphics calls.
figure;
t = linspace(0, 0.06, 601);
plot(t, sin(2*pi*50*t), 'LineWidth', 1.5);
grid on
xlabel('Time (s)');
ylabel('Amplitude (p.u.)');
ax = gca;
exportgraphics(ax, 'sine_50hz.png', 'Resolution', 450);
exportgraphics(ax, 'sine_50hz.pdf', 'ContentType', 'vector');
For several plots in one figure, pass the handle returned by tiledlayout in place of ax. The companion function writes both files in one call and checks for existing output files. The example and helper were tested in MATLAB R2024b.
If you try it on a lab plot or a tiled layout, feedback on the exported result is welcome.
AI assisted with drafting this post and implementing the companion function.
In my previous game (Quantum Collapse!), I decided to represent a quantum particle as a point after measurement just like a classical particle for "comparison" purposes. But a more accurate depiction would be the original spread-out wavefunction being localized at a specific position (as a δ-function). So in the new version of the game (Quantum Collapse! 2) I have incorporated this conceptual shift along with a few more game-y upgrades / changes:
- The probability of the quantum particle being found inside the capture (measurement) zone is prominently displayed at the top of the zone, as a "visual" equivalent to the classical ball's obvious position (one of my daughter's most vehement request!).
- The capture (measurement) zone now moves at varying speeds as the game plays out, making it slightly trickier to time the tap.
- As the quantum wavefunction collapses in response to a tap, a ring-burst emerges from the location of the δ-function "visualizing" the tap forcing a measurement.
- More score points are awarded if one has a quick eye-finger coordination!
- Revised outcome texts which make more sense (I think) and the final verdict (collocations related to new physicists) now accompanies stats summary like final score, accuracy, highest energy reached, longest time spent in an energy level, etc.
Give this sequel a go and see if you can do better than my nⁿ-th attempt.

Well, that is all for this contest season from me. Thanks to all the participants and organizers (@Adam Danz, @Chen Lin, @David, @Matt Tearle, @Mike Croucher, @Ned Gulley, @Stephen23) of this grand event.🎉
Happy Thanksgiving and Season's Greetings! 🍂🍁❄️☃️
Another week, another fantastic collection of One-Button Games!
We saw some fantastic entries in our STEM Educationcategory:
- Roatis / BRASS & ENTROPY — The Maxwell Experiment
- VMM / How well can you read contour maps?
- JKMSMKJ /QUANTUM COLLAPSE!
- KARUPPASAMYPANDIYAN M / MATLAB MILLIONAIRE
Congratulations!
And our winners in the other categories are:
Originality:
Arcade:
Visualization:
A huge congratulations to all our Week 3 winners!
🏁 The Contest Is Almost Over. Get Your Games Played!
We’ll be recognizing the most-played games, so share your entries with friends, classmates, coworkers, family, and anyone else who might enjoy them.
And there’s something in it for the players too: community members who play and vote have opportunities to win MathWorks swag! 🎁
So spread the word, discover some new games, and vote for your favorites.
In our dynamics and kinematics course we simulated robots in low gravity, and I wondered what astronauts would do for fun after work. My answer is Moon Kick: tap once to lock the angle, tap again to set the power, and send the ball floating past a robot goalkeeper. Instead of storing pictures, the game calculates its sky, kick and goalkeeper with a little trigonometry.Play Moon-Kick
functions, used and its role
The contest needs only three handles. Everything else is a helper that takes the game state and returns the new state.
function g = game()
g.init=@ini; g.update=@upd; g.render=@rnd;
end
Every other part, like the goal check and the effects, is a small helper that takes the game state and returns the new state.
Two taps, two sine waves
Angle and power swing back and forth on sine waves, and your tap freezes the value.
s.ang = 8 + 70*(.5 + .5*sin(3.2*u));
v = 390*s.pw; s.vx = v*cosd(s.ang);
s.vy = v*sind(s.ang);
The Moon is just a smaller number
Lowering gravity in the step update makes every kick fly about six times farther.
s.vy = s.vy - 117*d;

A galaxy from polar coordinates
Each star's angle grows with its distance from the centre, which makes a spiral. Squashing the vertical part tilts it, and adding to the angle each frame rotate it .
r = 120*rand(n,1).^.7; a = r/18 + randn(n,1)*.25;
x = 400 + r.*cos(a); y = 430 + .45*r.*sin(a);

Moon-Bot, the goalkeeper
Moon-Bot glides up and down on a sine wave with a random phase. The shot is decided when the ball reaches the goal line. I work out the ball's height on that line, so even a fast ball can't skip past him
yy = y + (640-x)/(s.bx-x)*(s.by-y);

In few words for you to enjoy the game you have to master th power and angles as follow:
Tricks to play
- Lock the angle between 30° and 45°. This gives a long arc that lands inside the goal. Below 25° the ball needs almost full power, and above 50° it drops short or goes over the bar.
- Use about 70% power. At 35° the safe power is 63% to 80%, and full power sends the ball over the bar.
- Watch Moon-Bot's rhythm before you kick. He moves up and down about once per second. A flatter kick (30°) reaches him sooner, so he has less time to get in the way.
Final word
Behind every floating kick in Moon Kick, there is nothing more than a few trigonometric functions. A sine wave sweeps the aim, cosine and sine turn your tap into a flying ball, and polar coordinates draw a whole galaxy. This is what I love about MATLAB: a few simple functions can become a game.
So the next time you tap to lock the angle, remember that you are playing with trigonometry. Try the tricks above, then change a number and see what happens. I hope you discover how much fun it can be.
Thanks for reading, and enjoy the joy of trigonometry! 🌙⚽
From inverse perspective mapping to depth sorted sprite rendering and pixel level RGB composition
Introduction
As Thanksgiving gives way to the Christmas season, festive themes become a natural source of inspiration for game development. I wanted to capture that seasinal spirit through Santa's Christmas Flight, incorporating snowy landscapes, presents, and familiar holiday imagery. The project also provided an opportunity to explore pseudo 3D graphics in MATLAB. Its rendering pipeline combines perspective transformations, depth based object ordering, geometric mask rasterization, and direct RGB image manipulation to create an animated environment without relying on a conventional 3D graphics engine.
Game Demonstration
The playable game and accompanying animation illustrate the interaction between the rendering pipeline and the one button gameplay mechanics. The demonstration highlights the perpective based environment, animated sprites, and depth dependent object movement.
Animated Demonstration

Constructing the Rendering Pipeline
The rendering routine, rnd( ), orchestrates the transformation of the simulated environment into a two dimensional image. Its sequence integrates inverse perspective mapping, depth ordered object rendering, geometric mask construction, and RGB image composition. Each operation contributes to the spatial coherence and visual depth of the resulting scene.
So, with the rendering architecture established, let's look at a few techniques that make the implementation work. The following tips focus on the perspective calculations, depth ordering, and pixel level operations used to construct the game environment.
Tip 1-Establishing the Perspective Transformation
The perspective calculation begins with the depth dependent scaling factor in rnd( ):
zr=ch*f./((1:H-h0)');
xw=((1:W)-(W/2).*zr/f+cam;
The first expression assigns a depth value to each image row, while the second reconstructs horizontal coordinates relative to the camera displacement. Together, these calculations establish the coordinate mapping used to generate the perspective environment.
Tip 2-Projecting Objects at Different Depths
The rendering routine uses the following calculations to position individual objects:
u=f/z;
x=W/2+(q(2)-cam)*u;
yb=h0+(ch-q(3))*u;
The reciprocal depth factor u determines the projected scale, while x and yb establish the object's screen coordinates. As an object approaches the viwer, its projected dimensions increase, reinforcing the illusion of forward motion.
Tip 3-Rendering Objects in Back to Front Order
When several objects occupy different depths, their drawing order determines which objects appear infront of others. Your code addresses this by sorting the depth values before rendering:
[~,o]= sort(L(1,:); 'descend');
The first row of L contains the objects' depth values. Sorting these values in descending order places farther objects earlier in the rendering sequence, allowing nearer objects to becdrawn afterward. This is the Painter's algorithm: objects are composited from back to front so that foreground elements visually obscure background elements.
This small sorting operation is essential to the scene's depth perception. Without it, overlapping sprites could appear in the wrong visual order, weakening the perspective illusion.
Tip 4-Constructing Geometric Masks for Sprite Rendering
My dr( ) function uses normalized coordinates and a radial test to determine which pixels vpbelong to a rendered shape:
u=((x1:x2)-x)/w;v=((y1:y2)'-y)/h;r=u.^2+v.^2;
The variables u and v represent normalized horizontal and vertical distances from the shape's centre. Their squared sum, r, provides a convenient geometruc test for circular regions. This allows the renderer to construct shapes directly within the image array rather than relying on seperate graphics objects.
The technique is particularly useful for lightweight sprite rendering because the mask is evaluated only over the relevant pixel region.
Tip 5-Projecting Particles Using Depth Dependent Coirdinates
The same perspective principle used for scene objects also governs the placement of the environmental particles:
z=mod(s.fz0-s.dist*1.3,17)+.8;y=mod(s.fy-t*.9,6);
px=round(W/2+(s.fxx-cam).*f/z);py=round(h0+(ch-y).*f./z);
Here ,z determines each particle's simulated depth, while y supplies its vertical position. The expressions for px and py convert these coordinates into image locations using the focal parameter f and camera offset cam. The mid operations keep the particle coirdinates within repeating ranges as the scene advances.
What makes this implementation interesting is that the particles are not simply moved across the screen. Their apparent positions are recalculated through perspective projection, helping the environment convey continuous forward motion.
Concluding Remarks
Santa's Christmas Flight was an opportunity to bring together game development, mathematical modeling, and engineering principles within MATLAB. Although the game is designed around a simple one button interaction, its visual environment relies on concepts associated with computer graphics, including perspective projection, coordinate transformations, depth ordering, and geometric rasterization.
I particularly enjoyed exploring how a relatively compact rendering pipeline could reproduce visual effects commonly associated with three dimensional environments. The underlying mathematics also has broader engineering relevance: coordinate transformations and geometric projections are fundamental to robotics, machine vision, navigation, and simulation. Even the game's sense of forward movement depends on carefully manipulating spatial coordinates and their relationship to the camera.
From a physics perspective, the project illustrates how mathematical relationships can translate an abstract spatial model into a convincing visual experience. It reinforced an idea I find especially compelling: engineering principles need not remain confined to conventional technical applications. They can also become the foundation for interactive experiences that make mathematical and computationl concepts more approachable.
I hope these techniques encourage other MATLAB users to experiment with custom rendering, explore the mathematics behind visual effects, and discover new possibilities within the One Button Game format. I would also welcome comments, suggestions, and alternative approaches from the MATLAB community.
The MATLAB One-Button Game Mini Hack asks us to fit an entire game into 10,000 characters of MATLAB code. That becomes quite a challenge once we start adding detailed backgrounds, animated characters, and visual effects. But, as we've seen in previous Mini Hacks, embracing limitations can often spark ingenuity. And this year is no exception, as the contest's restrictions have brought out some rather creative programming, with participants finding ways to fit far more into their entries than the character limit might initially suggest.
In my earlier article on making games in MATLAB, I shared some of the graphics and programming ideas behind Arcade. This time, I would like to show how I created the artwork for my Mini Hack games and encoded it to fit inside the submitted code. We can draw a scene in MATLAB, reduce its images to the information needed to reconstruct them, and let the game recover the artwork from its own source. The same idea extends to the coordinates used to build 3D objects and their effects.
Saloon Brawl Knockout uses the characters from my earlier Western games for its fighters, background crowd, and bartender. Their separate body parts let them walk, duck, and throw punches while keeping the original pixel-art appearance:
The backgrounds and characters are prepared separately, so the same cast can appear in different locations. These are the four backgrounds from Trigger-Happy Mayhem, each drawn in MATLAB as a 150-by-200 image before the characters and props are added:
Together with the character parts and props, the original image arrays contain more than 1.5 million pixels. Sharing repeated artwork considerably reduces the data before compression. The encoded data is stored directly in game.m, alongside the code that reconstructs the images during initialization.
Drawing with palette indices
Let's start with a small piece of the artwork: the beer mug from Tipping Point. Its dark outline, amber fill, and foam fit into a 15-by-15 indexed image. Each array element stores a single integer that selects a color from a shared RGB palette, with 0 reserved for transparent pixels.
Filled polygons form the mug's body. The handle is added beside it, followed by the highlights and foam:
For example, these vertices define the dark outline of its body:
pixels = zeros(15, 15, 'uint8');
[x, y] = meshgrid(0:14);
outline = [1 3; 10 3; 10 12; 8 14; 3 14; 1 12];
pixels(inpolygon(x, y, outline(:,1), outline(:,2))) = 1;
The drawing coordinates run from 0 to 14, and meshgrid supplies the pixel centers. inpolygon selects the points inside or on the outline, so we can assign the value 1 to those pixels using logical indexing. A smaller polygon fills the body with amber. Rectangles add the visible part of the handle and the highlights, and further polygons form the foam.
The attached mugEncodingDemo.m contains the complete drawing, encoder, and decoder. Calling it with false returns the pixel array and RGB palette, which can be used to display the mug:
[pixels, palette] = mugEncodingDemo(false);
figure;
image(pixels, CDataMapping="direct", AlphaData=pixels ~= 0);
colormap(double(palette) / 255);
axis image off
For a uint8 indexed image, image maps each pixel value to the corresponding colormap row, following MATLAB's integer-image color mapping. AlphaData hides the pixels whose value is 0, while colormap assigns the palette after its RGB values have been scaled from the range 0–255 to 0–1.
The larger Western backgrounds use the same drawing operations. In Quickdraw, horizontal bands and alternating pixels form the sunset, polygons form the road and the hills, and rectangles build the storefronts, windows, signs, and boards. Loops are used to generate the repeated details. Once the scene is drawn, we can encode its pixel values into the game directly and omit the lengthy drawing routines.
Packing repeated pixels
Many neighboring pixels in the mug have the same value. Instead of writing each value separately, we can record the pixel value and length of each uninterrupted run. For example, in the fourth column highlighted below, the five consecutive pixels with value 9 become the pair 9, 5:
Tipping Point has 32 palette entries, so five bits are enough to represent a color index. Using another five bits for the run length lets us combine a color index from 0 to 31 with a length from 1 to 32:
token = colorIndex + 32 * (runLength - 1);
Dividing by 32 separates the two values: the remainder is the color index, and adding 1 to the integer quotient recovers the run length. Runs longer than 32 pixels are split into several tokens. To store those tokens compactly in the source file, we convert them to characters and recover their numeric codes when decoding:
values = double(pixels(:)');
starts = find([true, diff(values) ~= 0]);
runLengths = diff([starts, numel(values)+1]);
tokens = [];
for k = 1:numel(starts)
remaining = runLengths(k);
while remaining > 0
runLength = min(32, remaining);
tokens(end+1) = values(starts(k)) + 32 * (runLength-1);
remaining = remaining - runLength;
end
end
packed = char(19968 + tokens);
diff identifies changes between consecutive pixel values. Converting to double first preserves decreases as well as increases; unsigned integer subtraction would clip negative differences to 0. find returns the starting position of each run, and the differences between consecutive positions determine the run lengths.
Adding 19968 shifts the 1,024 possible token values into a range of Unicode character codes; char converts those codes to printable text. This range contains no quotation marks or control characters, so we can write the result between single quotes in game.m as a character vector literal. Each character represents one token, replacing the decimal digits and separators that would be needed to write that token as a number. This encoding takes place while preparing the artwork; the game starts with the resulting literal already in its source.
At initialization, double recovers the numeric character codes. Subtracting the offset restores the tokens, and mod and floor separate their colors and lengths. repelem expands the runs, and reshape reconstructs the original pixel array:
tokens = double(packed) - 19968;
colors = mod(tokens, 32);
lengths = floor(tokens / 32) + 1;
decoded = repelem(colors, lengths);
restored = uint8(reshape(decoded, 15, 15));
The mug's 225 pixels become 74 tokens, stored in 74 characters. The attached example verifies that decoding them reproduces every original pixel. Tipping Point combines the runs from all its images with their dimensions and palette, then compresses that collection further before embedding it in the game.
The double(packed) conversion above requires a character vector. A string scalar, written with double quotes, behaves differently: double("123") converts the text to the number 123. mxym discusses this distinction in their article on PULSE // PALS. The game also packs geometry, palette, and note-chart values into characters.
Pixel runs can also help when drawing an image. In their Ember Fox article, Cephas describes defining sprites as grids of # and . characters. Each horizontal run of # characters becomes one rectangle, reducing the number of shapes needed to draw the sprite. In addition, SunHuilin describes storing image data as pixel runs and each 7-by-7 effect pattern as seven integers in their Purrfect Fit article. The individual bits select the filled pixels, allowing the same drawing loop to produce hearts, paws, sparkles, and other effects.
Small numeric tables can also be packed into characters. Street Racer uses a 3-by-5 font, with each row represented by three bits. For the letter A, the five row values are 2, 5, 7, 5, 5, corresponding to 010, 101, 111, 101, 101. Five base-8 digits occupy 15 bits, so the whole glyph fits in one character:
rows = [2; 5; 7; 5; 5];
packed = char(256 + sum(rows .* 8.^(0:4)'));
rows = mod(floor((double(packed) - 256) ./ 8.^(0:4)'), 8);
pixels = logical(mod(floor(rows ./ [4 2 1]), 2));
The last line separates each row into its three bits, with 4, 2, and 1 corresponding to the left, middle, and right pixels. The same packing idea works for small coordinates and dimensions: Street Racer stores its car artwork as colored rectangle parameters, which the renderer uses to draw the intact and damaged cars.
Stefan Abendroth packs each car pixel in Drift Boss into four bits: three select one of eight palette colors, and one marks the pixel as opaque or transparent. Two pixels fit in each byte. Base64 represents those bytes as ASCII text in the source; during initialization, matlab.net.base64decode recovers the bytes before the color indices and opacity bits are separated.
Sharing character parts
Quickdraw's cowboy is assembled from separate layers for the body, trousers, head, hat, mustache, and arms. Most of these parts can remain in place while the arm moves through eight poses to draw the revolver. Keeping the layers separate also allows a well-timed shot to send the hat or mustache flying while the face underneath stays intact.
The original layers all use an 80-by-64 canvas, so the body parts align when overlaid. Much of each canvas is transparent. Before encoding it, the preparation code crops the layer to its nontransparent bounding box and stores the crop's position and size. During reconstruction, those values position the recovered pixels within the original canvas.
To animate the draw, the renderer selects the appropriate arm layer and overlays its nonzero pixels on the character. Transparent pixels leave the underlying image unchanged. Each pose is drawn beforehand from specified hand and elbow positions. Thick strokes form the sleeves and forearm, an ellipse forms the hand, and a small revolver image is rotated into position before the pose is encoded.
Trigger-Happy Mayhem shares parts across different characters as well. The preparation code groups crops that can be reconstructed from a common template and stores the color maps separately. The three rivals below share the same body template, with different maps supplying their jacket colors. Their faces, hats, arms, and lower bodies have separate template and color-map records. Rivals 1 and 3 also reuse identical faces, mustaches, legs, and trousers. The strips compare the maps used for the body:
The shared body template is a pixel array; the top strip lists its distinct values, using gray shades to distinguish them. Each rival's row shows the pixel values returned by its lookup table, colorMap, and the palette colors they select. Applying that table to every template pixel reconstructs the crop:
crop = reshape(colorMap(double(template(:)) + 1), size(template));
Each rival's color map preserves 0 for transparent pixels and maps the remaining template values to that rival's pixel values. For example, Rival 1's map converts both 2 and 3 to 52, while Rival 2's maps them to 55 and 52, and Rival 3's to 58 and 52. The stored crop offset places the result back in its original canvas.
The game reconstructs 207 image arrays from 64 templates and 85 color maps, including the four backgrounds, character layers, and props. A short record identifies each image's template and color map and specifies its original canvas size and crop position.
During preparation, the template pixels are compressed using their surroundings to estimate the probability of each possible value. Pixels are processed row by row, using their left, upper, upper-left, and upper-right neighbors as the context. Values assigned higher probabilities take less space to encode. As the decoder recovers each pixel, it updates the same probability model, allowing it to reproduce the original template and apply the appropriate color map.
Transforming pixel artwork
The separate body parts also let us change a character's pose during play. In Saloon Brawl Knockout, the sheriff bends at the waist to dodge a punch, while the rivals approach from the back of the room and rotate as they fall onto the table.
The game reconstructs the indexed artwork from shared templates and color maps, as in Trigger-Happy Mayhem. Each character layer is then converted into colored rectangles. The conversion groups vertically adjacent pixels of the same color into runs. Runs in neighboring columns are then merged when their colors and upper and lower edges match. Here's the conversion for one of the hat layers:
The hat's 375 colored pixels become 65 rectangles: about 83% fewer faces to transform and draw than using one rectangle per colored pixel. Each rectangle is defined by four corners and a palette index; transparent pixels need no geometry. The outlines mark the boundaries between the rectangles. The colors and silhouette remain unchanged.
To place a character, the renderer scales the vertices about a fixed origin and translates them to the character's position in the room. Increasing the scale makes the rival grow as he approaches:
The sheriff leans back at the waist and lowers his torso to dodge the punch. After the counterpunch, the rival's fall combines rotation with changes in position and scale. The face, hat, and mustache rotate with the body:
The renderer scales and rotates the rectangles directly, so that their corners are not restricted to the original pixel grid. The head, torso, and leg pieces are prepared during initialization and reused, while the pose calculations place the parts around the moving joints. Characters and moving props are drawn through one reusable patch object. The background remains a separate 150-by-200 indexed image, and the original palette supplies the colors for both.
Generating poses during initialization
We can also prepare a character's animation frames before play begins. Run & Gun generates its sprite images during initialization, building them from polygons, rectangles, disks, and connected limb segments. Changing the limb positions produces the running poses, while folding the body and rotating the assembled sprite produces the somersault:
The rifle is drawn with the body before rotation, so both turn together. The player frames are prepared once and retained; during play, the renderer selects the frame for the current action.
Preparing artwork during initialization is useful for scenery as well. Tharikaa Ramesh Kumar describes this in their Slingshot Home article, where a grid and a lighting expression generate the planet textures. Run & Gun prepares separate sky, scenery, and road arrays, which its renderer reuses to scroll the scenery at different speeds.
Copying repeated patterns
When encoding sprite images, repeated details provide another opportunity to save space. Repeated wheels, windows, or patches of shading can contain identical sequences of palette indices. We can store a reference to an earlier occurrence of a repeated sequence and have the decoder copy its values.
In Paperboy: Back on the Block, seven 24-by-24 sprites are joined into one array. Their 4,032 pixels are represented by 407 tokens. Each token either contains a pixel value or specifies a distance back into the decoded data and the number of values to copy.
This format reserves token values below 33 for individual pixels. For a copy token, the integer quotient after division by 33 is the distance, and adding 2 to the remainder recovers the copy length. The decoder starts with an empty array and appends either a pixel or a copied sequence for each token:
distance = floor(token / 33);
if distance == 0
decoded(end+1) = token;
else
copyLength = mod(token, 33) + 2;
indices = numel(decoded) - distance + 1 ...
+ mod(0:copyLength-1, distance);
decoded = [decoded, decoded(indices)];
end
The modulo operation allows the copied pattern to repeat when the requested length exceeds the distance. For example, when decoded ends with [4 7], a copy with distance 2 and length 6 appends [4 7 4 7 4 7]. During preparation, the encoder searches the preceding pixels for these matches and chooses between writing a pixel value and a copy token. The decoder follows the recorded choices; it doesn't need to repeat the search. Once all tokens have been expanded, reshape restores the original sprite array.
Generating character variations
colorbar generates its customers from a shared set of 34 shapes. Varying their proportions, colors, hairstyles, and accessories produces over 400 distinct appearances. The generator and its decoder use under 2,000 characters, including the encoded geometry and palette.
Ellipses form the faces, ears, eyes, and hands, while polygons form the clothing and other details. Each ellipse is stored as four values: its center coordinates and two radii. For example, the shared face ellipse can be encoded and reconstructed as follows:
parameters = [0, -82, 18, 23];
packed = char(19968 + 2*parameters);
parameters = (double(packed) - 19968)/2;
angles = (0:15)' * pi/8;
vertices = [parameters(1) + parameters(3)*cos(angles), ...
parameters(2) + parameters(4)*sin(angles)];
Multiplying by 2 allows half-unit values to be packed as integers. The decoder expands each four-character ellipse record into 16 vertices. For polygons, each pair of integer coordinates is combined into a single character, using the same remainder-and-quotient approach as the earlier color and run-length tokens. The shared palette supplies the base colors, and a short list of roles assigns skin, hair, clothing, or detail colors to each shape.
A customer's number selects the skin tone, hair and jacket colors, body width, and head proportions through modular arithmetic. For example, mod(identity,6) cycles through six hairstyles, while mod(identity,5) selects one of five skin tones. The number also determines which optional parts appear, including glasses, facial hair, ties, and earrings. These choices are linked by the same number, producing a repeating sequence of appearances. The game retains the resulting geometry until the customer's identity changes; blinking, service reactions, and movement are applied to those vertices during play.
The attached colorbarCharacterDemo.m expands those compact functions for readability and adds a gallery for browsing all 14 sheets of 30 customers. The numbers match the identities used by the game. Run colorbarCharacterDemo() to open it, or return the complete collection without opening a window:
customers = colorbarCharacterDemo(false);
Calling colorbarCharacterDemo(ExportFolder="customers") also saves the 14 numbered sheets as PNG images. The example includes the shared data and helpers, so it can be used independently of the game.
Encoding glass geometry
Shatterglass uses five flat profiles and eight glass volumes. The renderer assigns their face and outline colors from the game's palette:
The vertex coordinates are multiplied by 1000 and rounded to integers. Adding an offset of 20000 shifts these integers into a range of character codes, similarly to the mug's run tokens. The indices used to draw the exterior edges are packed into characters as well. These short vectors describe the original shapes; the game calculates their changing positions and orientations in real time.
There’s more to store than just the geometry. The palette, fracture weights, graphics settings, and other fixed game data are grouped into a collection of constants. To compress that collection together, we first need to turn its differently sized arrays and text values into a single sequence. MATLAB's jsonencode writes them as structured JSON text. The compressor works with byte values from 0 to 255, so unicode2native converts the text to bytes using the UTF-8 encoding. The diagram below illustrates the encoding and decoding process:
The attached glassEncodingDemo.m includes the original packed data and all the functions needed to decode it and draw the volumes. It also reproduces the encoding, using the following preparation code:
prepared = prepareGlassArrays(constants);
json = jsonencode(prepared, ConvertInfAndNaN=false);
bytes = unicode2native(json, 'UTF-8');
packed = encodeAssetBytes(bytes);
byteCount = numel(bytes);
prepareGlassArrays preserves array information that JSON would otherwise lose. For example, the game's empty 0-by-9 and 0-by-17 arrays would both become []; recording their dimensions lets the decoder distinguish and rebuild them. ConvertInfAndNaN=false also retains the nonfinite values used by the game in MATLAB's JSON representation. The original byte count is saved with the packed data so the decoder knows how many bytes to recover.
The custom encodeAssetBytes helper compresses those bytes using adaptive range coding. It estimates probabilities for the next byte from counts of values previously seen after contexts of up to four bytes. Those estimates divide a numeric interval among the possible next values, allocating larger portions to more probable values. Each input byte selects its portion and narrows the interval. The decoder follows the same divisions to recover the bytes, updating its counts in the same order as the encoder. Both build the model as they go, so its frequency table can be omitted from the stored data.
We still need to include the compressed output in the MATLAB source. The compressor produces 20-bit integers, which are larger than the mug's 10-bit tokens. MATLAB stores a char array as 16-bit elements using UTF-16; some Unicode characters are represented by a pair of these elements. The helper splits each compressed integer into two 10-bit parts and places them in such a UTF-16 surrogate pair. The 3,413 input bytes become 633 packed integers, occupying 1,266 elements of the character vector written into game.m.
At initialization, the following sequence reverses the process:
bytes = decodeAssetBytes(packed, byteCount);
json = native2unicode(bytes, 'UTF-8');
constants = restoreGlassArrays(jsondecode(json));
decodeAssetBytes unpacks the characters and recovers the byte sequence. native2unicode interprets those bytes as UTF-8 to recover the text, and jsondecode turns it back into MATLAB values. restoreGlassArrays reconstructs arrays from their recorded dimensions and converts the remaining column vectors to rows.
The constants are decoded once, during initialization. Running glassEncodingDemo() displays the reconstructed volumes, and glassEncodingDemo(false) returns the decoded data without opening the figure.
The recovered constants include the packed coordinate and edge-index vectors for each volume. We can now turn these back into the points, triangular faces, and outline used to draw the shape:
vertices = reshape(double(packedCoordinates) - 20000, 3, [])' / 1000;
faces = convhull(vertices);
edgeIndices = double(packedEdges) - 20000;
outlineVertices = [vertices; NaN(1,3)];
edges = outlineVertices(edgeIndices, :);
Subtracting 20000 recovers the stored integers; dividing by 1000 restores their coordinate scale. Each row of vertices contains one point's x, y, and z coordinates. convhull returns triangles covering the boundary of the convex solid, which can be passed to patch. For the octahedron, this produces its eight outer triangular faces, with no surface between the upper and lower halves.
The exterior edge path is stored separately because the triangulation also contains diagonals across flat faces. Drawing only the selected edges keeps those diagonals out of the glass outline. The appended NaN row provides breaks between the separate segments when the outline is drawn with line.
Deriving the shards and reflections
The triangular faces also provide the geometry for the shattering effect. A common set of weights selects each face's corners, edge midpoints, and an interior point. Matrix multiplication combines these weights with the coordinates of the face's three vertices to divide it into six smaller triangles. The same subdivision works for every volume. The animation below uses the game's collision and rendering functions to demonstrate the shattering effect and reflections:
The cube has 12 surface triangles and produces 72 shards. Each shard is assigned an initial velocity; its position and rotation are calculated from the time since impact. The shards fall under gravity, then bounce and slow down as they settle flat on the floor.
The reflection uses a second copy of the displayed geometry with its vertical coordinate reversed. For a floor at z = 0, the operation is:
reflectedVertices = vertices .* [1, 1, -1];
The wall reflections reverse the x coordinates about each wall's position, while the ceiling reflection reverses the z coordinates about its height. Intact glass, moving shards, and balls are mirrored from their current geometry. The renderer reduces the opacity of the reflected glass and darkens the ball reflections. The orientations of the glass faces also determine their shading and transparency as the fragments turn. Shatterglass creates its graphics objects once and reuses them, changing their vertices, colors, and transparency as the objects move or break.
Validating the game
The encoder can remain in the development files, but the submitted game needs to include everything required to reconstruct its graphics. That includes the palettes, dimensions, lookup tables, and decoder. A small font or a few rectangles may need only a short unpacking expression. A larger collection can share a more elaborate decoder across many assets, and may also benefit from retaining drawing routines for repeated shapes or poses.
For Shatterglass, an equivalent version using direct MATLAB routines and ordinary numeric arrays uses 16,399 counted characters. Encoding the game brings this down to 10,000:
The counts cover the complete game, including the code needed to decode and use the stored values. Both versions retain the same gameplay, graphics, shattering, and reflections.
The preparation code checks each representation by decoding its output and comparing it with the source arrays. For example, isequal checks that every palette index in the reconstructed mug matches the original. For the glass, the comparison uses the rounded coordinates. The mug and glass demos include these reconstruction checks. All three attachments contain their own data and helpers, so they can run independently of the games.
When validating the character count, use the contest tools on the game.m file. The validator also parses and reformats the code before counting it, excluding comments. Mohammad Aryayi discusses this in their account of reducing Stack OverDad, which also describes packing the coordinates of rectangles, ellipses, and polygons into character codes. Save the file as UTF-8 in order to preserve the packed character literals, then run minihackContest.validate before submitting the game.
I hope these examples give you a few useful ways to make room for more of your own graphics. If you try a different representation or find a particularly effective way to pack your artwork, I would be interested to see it! I look forward to seeing many more amazing games from everyone taking part in the Mini Hack!
A proton or carbon-ion beam deposits most of its dose at the very end of its path, in the Bragg peak, and almost nothing beyond it. That is the whole promise of particle therapy: cover the tumour, stop right after it, spare the organ behind. It is also its weak point. The beam stops where the tissue says it stops, and if the range is off by a few millimetres you either leave part of the tumour cold or overshoot into the brainstem.
Choosing where the beam stops felt like a natural fit for one button. After *X-Ray Guided* (coronary stenting) and *Y-90: Target the Liver Tumour* (radioembolization), this is my third entry. I am a medical physicist, and this time I wanted to play with something every particle therapy physicist worries about: range, and the choice of the particle.
How to play
Each patient is an axial CT slice, brain or lung, with the tumour in red and the organs at risk in colour. The beam always comes from the left.
- Choose the beam: PROTONS and CARBON IONS are highlighted in turn, tap to pick one. The depth-dose panel on the right previews both along the tumour. The yellow line on the patient card is the clue: a hypoxic tumour, a child, the heart behind the tumour, a long path through lung.
- Fire: the tumour is treated band by band. A cyan marker shows where the beam will stop (the distal edge, R80). It sweeps back and forth at constant *water-equivalent* speed, so it races through lung and crawls through bone. Tap to fire the band.
- Report: tumour control or recurrence, cold spots in blue, organ doses in green or red on the card.
The catch is the range uncertainty. The tumour is judged with the range 3 % short, the organs at risk with the range 3 % long. Stopping exactly on the tumour edge is not enough: aim a little past it, but not so far that the organ behind takes the dose. A recurrence or any toxicity costs a life; three lives per shift, and the marker gets faster patient after patient.

Protons or carbon?
Every case has a reason to prefer one particle, taken from the real arguments (simplified):
- Hypoxic tumour: protons cannot control it, carbon ions can (higher LET, less dependence on oxygen).
- Long path through lung: the proton entrance plateau is higher, so the lung in front of the tumour gets more dose. Carbon wins.
- Child: the carbon RBE is less certain in growing tissue, so the game adds a larger safety margin on organ doses, and the low-dose fragmentation tail beyond the peak reaches the hippocampus behind the tumour. Protons win.
- Heart behind the tumour: the same tail exceeds a strict mean-heart-dose limit. Protons win.
- Meningioma: either works, just aim well.
Real vs. playable
What I kept real
- Range in water-equivalent depth: each tissue has its own stopping power, so the same energy goes further in lung and less far in bone.
- Spread-out Bragg peak (SOBP) covering the tumour thickness, with an entrance plateau that is higher for protons and a distal fall-off that is wider for protons and sharp for carbon.
- Dose in Gy(RBE): RBE 1.1 for protons, variable for carbon (about 1.3 in the plateau, 2-3 in the SOBP), plus a fragmentation tail beyond the peak.
- Robust evaluation against ±3 % range uncertainty, as in robust optimisation: worst case for the target, worst case for the organs.
- Organ constraints in the clinical form (Dmax, mean, Vx, Dx).
What I changed for playability
- One beam, one 2D slice, analytic depth-dose curves instead of a dose engine.
- Synthetic anatomy made of ellipses.
- Some limits are game values, tuned so that the choice of the particle matters (the mean heart dose and hippocampus limits, for example). Hypoxia is all or nothing.
- The beam energy is not chosen from a list:** the marker sweeps and you tap.
Three things I learned
- A "choice" is only a choice if the game can prove it.** My first versions had cases where both particles worked, or neither did, for reasons the player could not see. In the end I wrote a bot that plays every scenario with both particles and a perfect aim, 50 patients each, and kept tuning anatomy and limits until the right particle succeeded almost always and the wrong one almost never. The table it prints became my design document.
- Uncertainty makes a timing game a margin game.** Without the ±3 % rule the best tap is "exactly on the edge". With it, there is a window: too short and the tumour is cold in the short scenario, too long and the organ behind is hot in the long one. The window is wider for carbon's sharp edge than for the proton fall-off, which is exactly the physics.
- Characters: the validator reformats your code.** Spaces around operators, `( ` and ` )` in calls, and four spaces per indentation level all count. Flattening nested `if`s saved more than any variable renaming. Two other tricks did a lot:
% anatomy as a string: tissue digit, then cx cy a b angle, one char each
for q = reshape(A,6,[])
v = (q'-64)/4;
I(E(s,[o+v(2:3) v(4:6)])) = q(1)-48;
end
% rotated ellipse with complex numbers (s.Z = X + iY)
z = (s.Z-v(1)-1i*v(2))*exp(-1i*v(5));
e = (real(z)/v(3)).^2+(imag(z)/v(4)).^2 < 1;
How many patients do you get through? And if you work in particle therapy: what did I oversimplify?
My initial idea was one game covering a satellite's full attitude-control operation: stop the spin after launch, then point at a target. It didn't fit in 10,000 characters of MATLAB. Real spacecrafts don't do it all in one go either, so I split it into two games:
Keywords:
AOCS (Attitude and Orbit Control System) is the part of a spacecraft that knows which way it's facing and turns it where it needs to point.
Detumbling is the first job after a satellite separates from its rocket. It's usually spinning, so the AOCS has to bring that rotation close to zero before anything else can happen.
Pointing comes next: aiming a camera, antenna or laser at a target and keeping it there while the satellite moves along its orbit.
Conservation of angular momentum links detumbling and pointing: with no external torque, total spin can only move between parts, so spinning a reaction wheel one way turns the satellite the other way.
H = I_body·ω_body + I_wheel·ω_wheel = constant
Why two games? Different phases, different needs
A spacecraft's needs change over a mission. Right after launch it has to stop tumbling; later it has to point accurately at targets, and each phase calls for a different control approach. So I split the two: each game covers one phase, simplified with one wheel on one axis.
Phase 1: Single-Wheel Detumble

Your satellite is tumbling at 10–19°/s. Hold the button to spin the wheel and absorb the spin. Get the rate below 0.5°/s and hold it there for 2 seconds.
Phase 2: Single-Wheel Target Tracking

A ground station moves beneath your orbit. Turn the satellite until the camera's boresight is on it, then keep it within 3° for 3 seconds.
How to play both games
- Hold = wheel motor on. Release = off.
- The direction alternates with every press. The arrow on the wheel shows which way it spins.
- Watch the BODY + WHEEL = TOTAL H chart: as one goes up the other goes down. That's conservation of angular momentum!
Which did you find harder, stopping the spin or holding the target? 🛰️
This Week's Quiz
148 responses
A MATLAB Implementation of the Biot-Savart Law, Field-Uniformity Analysis, and Boris Integration
Introduction
Developing HELMHOLTZ HERO was far more challenging than I initially expected. I spent many long hours working through the physics, refining the MATLAB implementation, troubleshooting numerical errors, and trying to make several independent components work together without compromising the underlying science. One of the biggest challenges was translating the Biot-Savart law into a numerical calculation that could represent the magnetic field generated by two interacting circular coils. Getting the 96 segment integration, field superposition, spatial interpolation, RMS uniformity calculation, and Boris particle integrator to work together required patience and a fair amount of experimentation.
I am sharing some of the techniques and lessons I learned during that process because getting a physics-based STEM project to work involves considerably more than writing code that runs. The mathematical model must be consistent with the physical system, numerical approximations must be understood, and the visual output must accurately reflect the calculations behind it. The tips that follow focus on the approaches that helped me develop and troubleshoot this particular simulation, including some of the mistakes and technical details that I would pay closer attention to if starting the project again.
HELMHOLTZ HERO: A Numerical Exploration of Electromagnetism
Before discussing the technical lessons behind the project, I invite you to explore HELMHOLTZ HERO, my MATLAB One Button Game entry. It is an interactive physics simulation that brings magnetostatics and charged-particle dynamics into a hands on learning experience. Through a simple one-button control scheme, players explore magnetic-field uniformity, adjust physical parameters, and observe how those changes influence particle motion.
The animated demonstration below illustrates the simulation in action, showing how the magnetic-field configuration changes.

The following tips describe some of the numerical methods, MATLAB programming techniques, and practical problem-solving approaches I used during development.
Tip 1: Validate the Numerical Field Calculation Before Visualizing it
One of the most important lessons I learned while developing HELMHOLTZ HERO was to validate the numerical calculation before refining the visual presentation. A field map may look physically plausible, but its appearence alone does not establish numerical accuracy. In my implementation, I used the Biot-Savart law to calculate the magnetic field components at each observation point. The circular integration is approximated using 96 angular midpoint samples, defined directky in the bf() function:
c=cos(((1:96)-0.5)*2*pi/96);
For each current loop, the function calculates the axial displacement zr, applies the relative current cur, and evaluates the geometric denominator D:
zr=z-(k-1.5)*d;
cur=1+(r-1)*(k-1);
D=(x.^2+1+zr.^2-2*x*c).^1.5;
The radial and axial field components are then accumulated using the angular samples:
bx=bx+cur*sum(c.*zr./D,2)/96;
bz+cur*sum((1-x.*c)./D,2)/96;
A useful verification technique is to compare the numerical result with a known analytical solution. For the ideal Helmholtz configuration, the normalized magnetic field at the midpoint is:
BH_over_B0=2*(4/5)^(3/2);
The expected value is approximately 1.4311. This provides a reference for checking the numerical implementation before relying on its field visualization and uniformity calculations.
Practical takeaway: Validate the numerical physics against an analytical benchmark before trusting the visual output.
Tip 2: Create Graphics Objects Once and Update Them During Animation
One programming decision that made HELMHOLTZ HERO more manageable was seperating graphics intialization from frame by frame updates. Instead of repeatedly creating new plots, surfaces, and graphical objects during gameplay, I created the graphics handles in initState(ax) and updated their properties through renderFrame. This seperation is particularly useful in an animated MATLAB application, where graphics are refreshed reoeatedly as the simulation progresses.
Keeping the initialization and rendering responsibilities seperate has two practical advantages: it avoids unnecessary graphics object creation and makes the rendering routine easier to maintain. It also helps prevent the accumulation of obsolete graphical objects during animation.
Practical takeaway: Intialize your graphics once, retain their handles, and update the existing objects rather than recreating the entire visualization every frame.
Tip 3: Implement a Boris Style Magnetic Rotation for Particle Motion
A particularly interesting part of HELMHOLTZ HERO is the numerical integration of the particle trajectory. I used a Boris style rotation to update the particle velocity in response to themsgnetic field calculated at its current position. The method relies on vector cross products to produce the velocity rotation rather than using a straightforward component by component update.
The particle starts with the following initial position and velocity:
q=[0 0 -1,8];
v=[0.5 0 1];
The integration uses 12 substeps per frame. At each substep, rho gives the particle's distance from the symmetry axis, and bf() calculates the local radial and axial magnetic field components using the current coil parameters:
rho=hypot(q(1),q(2));
[br,bz]=bf(rho,q(3),s.d,s.r);
The radial field component is then resolved along the particle's Cartesian coordinates. The small denominator safeguard prevents division by zero when the particle approaches the symmetry axis. The vectors tv and sv determine the magnetic rotation:
f=br/max(rho,1e-9);
tv=0.02*[f*q(1) f*q(2) bz];
sv=2*tv/(1+tv*tv');
The velocity update applies the cross product rotation, after which the particle position is advanced:
v=v+cross(v+cross(v,tv),sv);
q=q+0.01*v;
Repeating these operations over the 12 substeps produces the trajectory shown in the game. Notice that the implementation uses fixed increments of 0.02 and 0.01; it does not currently scale these values with the frame time argument dt. The method also models magnetic rotation only, without an electric field contribution.
Practical takeaway: Evaluate the magnetic field at the particle's current position, perform the velocity rotation, and then advance the position. Keeping these operations in a clear sequence makes particle integration easier to inspect and troubleshoot.
Tip 4: Quantify Magnetic Field Uniformity with RMS Error
A key part of HELMHOLTZ HERO is measuring how uniformly the magnetic field is distributed around the center of the simulation. Instead of relying only on the visial field map, I use the magnetic field magnitude at the center as a reference and calculate the relative deviation across the grid.
The following lines from field(s) calculate the field magnitude, establish the central reference value, and determine the relative deviation:
b=hypot(bx,bz);
bc=b(13,20);
e=b/bc-1;
The code then selects a seven by seven region around the center of the grid and calculates its root mean square (RMS) deviation:
w=e(10:16,17:23);
s.rms=sqrt(mean(w(:).^2));
Using w(:) converts the selected region into a column of values for the calculation. Squaring the devistions prevents positive and negative differences from canceling each other. The square root then returns the RMS result to the scale of the original relative deviations.
In this implementation, the RMS value measures variations in magnetic field magnitude within the selected region; it does not independently measure the uniformity of each field component.
Practical takeaway: Establish a reference field value, select a consistent measurement region, and use RMS error to quantify local field uniformity. This provides a numerical basis for comparing simulation results rather than relying on visual inspection alone.
Tip 5: Use MATLAB Graphics Handles to Animate a Physics Simulation
A useful technique in HELMHOLTZ HERO is to create the graphics objects once and update their properties as the simulation changes. In initState(ax), I create the field map image and magnetic firld direction arrows, storing their handles in s.g.im and s.q.q. The field map is created using the calculated RGB data in s.E:
s.g.im=image(ax,[50 544],[391,79],s.E,o{{:});
s.q.q=quiver(ax,cx+s.ZZ(1:4:25,2:4:38)*...
S,cy-s.XX(1:4:25,2:4:38)*S,s.U,s.V,0,...
'Color',[1 1 1],'LineWidth',1,o{:});
In renderFrame, I update these existing graphics objects using their stored handles. The CData property refreshes the field map colors, while UData and VData update the arrow components:
h.im.CData=s.E;
h.q.UData=s.U;
h.q.Vdata=s.V;
The same approach updates the particle trail and its moving marker. The trail uses the coordinate arrays s,tx and s.ty, while the particle marker follows the latest recorded position:
h.tr.XData=s.tx;
h.tr.YData=s.ty;
h.hd.XData=s.tx(max(s.i,1));
h.hd.YData=s.ty(max(s.i,1));
This seperation between graphics initialization and rendering keeps the visualization synchronized with the changing magnetic field and particle trajectory without repeatedly creating new graphics objects.
Practical takeaway: Store graphics handles when creating plots, images, and vector fields. Update their data properties during animation to keep MATLAB visualizations efficient and easier to maintain.
Final Thoughts: Turning Magnetostatics into an Interactive Experience
Developing HELMHOLTZ HERO brought together several areas of computational physics and MATLAB programming in a single interactive project. The implementation combines a numerical Biot-Savart field calculation, magnetic field uniformity analysis, Boris style particle integration, and graphics updates to create a playable exploration of magnetostatics.
The one button design makes the experience accessible while preserving meaningful physics concepts. Players adjust the seperation between the simulated circular current loops and their relative current ratio, observe how these parameters affect magnetic field uniformity, and see how a charged probe responds to the resulting magnetic field.
My goal was to make the underlying physics more approachable through experimentation rather than passive observation. I hope HELMHOLTZ HERO encourages other MATLAB users to explore computational physics, experiment with numerical methods, and develop interactive learning experiences of their own.
Thankyou for exploring HELMHOLTZ HERO!
Update: I’ve released waitForFigureLayout as a standalone utility to make it easier to use in your own apps. You can download the packaged version from MATLAB Central File Exchange.
I wanted to read a grid child’s Position immediately after resizing its parent. Sometimes drawnow returned while the child still had its old size. A second read, with no further changes to the figure, gave a different rectangle.
A MATLAB uifigure has a browser-based client that computes grid layout and reports the resulting positions back to MATLAB. So when can MATLAB code read the updated values? In the layouts I tested, a wait inside that client gave me the same Position values as a later read. The wait starts with 220 ms without a container resize notification, then lets the client finish the layout work it has queued.
This post is an abridged English adaptation of my own article on Qiita (in Japanese). I used AI assistance to prepare the English write-up and reproduction files.
Caution: This trick relies on undocumented, private MATLAB internals. It was verified only by testing on Windows and may stop working in any release.
Why a position can change after drawnow
The uigridlayout documentation mentions that a child’s Position may lag when it is added to a grid. I saw the same kind of lag when resizing an existing grid. MATLAB updates the component properties as position change events arrive from the uifigure client. A read can occur while the client still has another relayout pending.
In the Windows releases I inspected (R2023a through R2026b), the Grid Layout controller used a 200 ms Lodash throttle for parent resize events, with both leading and trailing calls enabled. The first resize can run immediately. If another comes in during that interval, the trailing call can run on a timer, using the latest resize. If the grid contains another resizable container, that relayout can trigger another resize further down the tree.
The internal ViewModel method stabilize() waits for registered asynchronous work. The trailing timer hasn’t registered a relayout yet, so the ViewModel can report that its current work is done while the timer is still pending. A single requestAnimationFrame can also run before that timer fires.
How I waited for updated positions
Run JavaScript in the uifigure client
Reaching that window through the figure's hidden Controller follows the approach Yair Altman described in Customizing uifigures on Undocumented MATLAB. In the releases I tested, the window is on the controller's PlatformHost rather than its Container. The code registers a listener on the figure's ViewModel, then calls executeJS on that window. The JavaScript sends a completion event through the ViewModel after waiting for the layout. These steps use private APIs and require a figure whose host exposes a CEF window.
On Windows, use an ordinary uifigure from R2023a through R2024b. To use the same code in the desktop from R2025a through R2026b, create a separate figure window with the undocumented matlab.ui.internal.uifigureIsolated. Use fig = matlab.ui.internal.uifigureIsolated; in place of fig = uifigure; when creating the figure.
Wait for the grid’s resize work
- Wrap emitContainerResizeControllerEvent on the figure’s container controllers. Record the time of the most recent resize notification and keep that timestamp across waits. When installing a new hook, start the quiet period afresh because earlier notifications may have been missed.
- Wait for 220 ms without another notification. That is the Grid Layout controller’s 200 ms throttle interval plus a 20 ms margin. Each resize restarts the quiet period, so nested relayouts have time to schedule their own work. Give up after three seconds of continued activity.
- Await stabilize() when it exists, then wait one animation frame. In R2023a and R2023b, the grid relayout itself was scheduled as an animation-frame callback. In R2024a and later, the relayout was registered with the ViewModel.
- Send the completion event through the figure’s ViewModel so that it follows position notifications already dispatched on that channel. On receipt, read the MATLAB properties.
The 220 ms interval is derived from the throttle in the implementation I inspected. Both the throttle interval and the private APIs can change between releases.
Validation
I used a panel containing a two-row grid with a 'fit' label above a tab group. The second tab contained a nested grid and label. After the initial layout had settled, I measured a second wait and compared the outer label’s and tab group’s Position and the nested label’s getpixelposition(...,true). I took the first reading after the wait and a drawnow, and the second 0.5 seconds later.
In interactive MATLAB desktop sessions on Windows, I ran six trials per scenario in each release from R2023a through R2026b. All three rectangles agreed in all 192 trials.
The per-release median waits ranged from 241 to 249 ms after resizing the panel, enlarging the fit-row label, switching tabs, and enlarging the nested label. They ranged from 233 to 246 ms after only the panel resize and label enlargement, and from 296 to 375 ms after two panel resizes 50 ms apart. With no change, the wait took 8 to 12 ms.
The attached layoutWaitDemo.zip contains a smaller reproduction fixture, a single grid whose parent is resized twice within the throttle interval, and the same waitForFigureLayout.m and waitForFigureLayout.js shown below. To compare drawnow alone with the browser wait, extract the ZIP and run this command from the extracted folder.
matlab -batch "layoutWaitDemo(false, 8); layoutWaitDemo(true, 8)"
In this smaller fixture on Windows R2023a, R2024b, and R2026b, each release showed a position change after the first read in 8/8 baseline runs and 0/8 runs with the browser wait. The median extra waits were 362, 375, and 377 ms, respectively.
Using the wait in your own code
Save the two blocks below as waitForFigureLayout.m and waitForFigureLayout.js in the same folder and put that folder on the MATLAB path. Call the function once before editing the layout to install the resize hooks. After making your changes, call it again before reading Position. Keep the figure visible while waiting for the animation frame.
fig = uifigure;
panel = uipanel(fig, "AutoResizeChildren", "off", "Position", [20 20 300 250]);
grid = uigridlayout(panel, [1 1]);
child = uilabel(grid, "Text", "Grid child");
drawnow
waitForFigureLayout(fig); % Install hooks before the first layout change.
panel.Position(3:4) = [400 300];
drawnow
waitForFigureLayout(fig); % Wait for the queued resize work and its reply.
drawnow
position = child.Position
MATLAB file: waitForFigureLayout.m
function waitForFigureLayout(fig)
% waitForFigureLayout Dispatch the browser wait and receive its result on the figure ViewModel.
arguments (Input)
fig (1, 1) matlab.ui.Figure
end
% Find the browser window that hosts the figure.
% struct() reads every hidden property, so besides MATLAB:structOnObject it can
% emit unrelated deprecation warnings (JavaFrame, GraphicsSmoothing, ...).
% Silence all warnings only for these three calls.
warningState = warning("off", "all");
warningCleanup = onCleanup(@() warning(warningState));
figureData = struct(fig);
controller = struct(figureData.Controller);
host = struct(controller.PlatformHost);
clear warningCleanup
assert(isfield(host, "CEF") && ~isempty(host.CEF), ...
"This figure has no CEF window. Use uifigure through R2024b. " + ...
"In R2025a or later, create the figure with matlab.ui.internal.uifigureIsolated.");
viewModel = controller.ViewModel;
% Use a unique completion event for this request and subscribe before dispatch.
requestId = erase(string(java.util.UUID.randomUUID()), "-");
eventName = "FigureLayoutWaitCompleted_" + requestId;
reply = [];
listener = viewModel.addEventListener(char(eventName), @receive);
listenerCleanup = onCleanup(@() delete(listener));
configuration = struct("figureId", string(viewModel.getId()), ...
"channel", string(matlab.ui.internal.FigureServices.getUniqueChannelId(fig)), ...
"eventName", eventName);
source = fileread(fullfile(fileparts(mfilename("fullpath")), "waitForFigureLayout.js"));
script = replace(string(source), "__LAYOUT_WAIT_CONFIGURATION__", string(jsonencode(configuration)));
host.CEF.executeJS(char(script), 10);
% Yield to MATLAB callbacks and bound the wait for a missing browser reply.
clock = tic;
while isempty(reply) && toc(clock) < 8
pause(0.01);
end
assert(~isempty(reply), "Timed out waiting for the figure ViewModel reply.");
if isfield(reply, "error")
error("Browser layout wait failed: %s", string(reply.error));
end
clear listenerCleanup
function receive(~, event)
% receive Store the payload for this request's completion event.
reply = event.data;
end
end
JavaScript file: waitForFigureLayout.js
(config => {
const delay = milliseconds => new Promise(resolve => setTimeout(resolve, milliseconds));
require(["viewmodel/impl/ViewModelManagerFactory", "MW/componentframework/ControllerService"],
async (factory, service) => {
const managers = Object.values(factory._viewModelManagerCache)
.filter(manager => manager.hasById(config.figureId));
if (managers.length !== 1) {
throw new Error("Expected one ViewModel manager for this figure.");
}
const manager = managers[0];
const viewModel = manager.getById(config.figureId);
const send = result => viewModel.dispatchEvent(config.eventName, viewModel,
result);
try {
// Keep resize timestamps across calls in this demo figure.
const resize = viewModel.figureLayoutWaitResize ??= {
last: performance.now(), hooked: new WeakSet()
};
const cache = service.getInstance(config.channel)._controllerCache;
const controllers = cache instanceof Map ? [...cache.values()] : Object.values(cache);
let watched = 0;
for (const controller of controllers) {
const original = controller?.emitContainerResizeControllerEvent;
if (typeof original !== "function") continue;
watched++;
if (resize.hooked.has(controller)) continue;
controller.emitContainerResizeControllerEvent = function (...args) {
resize.last = performance.now();
return original.apply(this, args);
};
resize.hooked.add(controller);
resize.last = performance.now();
}
if (watched === 0) throw new Error("No resize emitters found.");
// Let pending browser work run, then wait out the trailing resize timer.
document.body.getBoundingClientRect();
await delay(0);
const started = performance.now();
while (performance.now() - resize.last < 220) {
if (performance.now() - started >= 3000) {
throw new Error("Resize activity did not settle within 3 seconds.");
}
await delay(10);
}
// Drain registered layout work where supported, then wait one frame.
const root = manager.getRoot();
if (typeof root.stabilize === "function") await root.stabilize();
await new Promise(resolve => requestAnimationFrame(resolve));
send({ completed: true });
} catch (error) {
send({ error: String(error) });
}
});
return config.eventName;
})(__LAYOUT_WAIT_CONFIGURATION__)
I'd rather not believe this far too hacky way is the only thing to do. Has anyone found a supported way to wait until a grid layout's updated positions are available on the MATLAB side? I'd also be interested in results from other platforms or nested layouts.
Hope you remember the little working games when you were a kid :D
I made a little café game called A Little More using MATLAB and Codex, where you make drinks for different customers using just the Space bar.
The fun part was figuring out how to make everything work with one button.
Instead of choosing from a long menu, players pick a brewer, adjust the strength, and add ingredients like milk, ice, or different flavors. With 6 brewers, 6 mix-ins, and 5 flavors, there are 180 possible combinations.
Here's a small part of the code that handles the automatically cycling options:
function i=pick(s,p)
i=1+mod(floor(s.t/.95),numel(s.menu{p-1}));
end
The timer keeps moving through the available choices every 0.95 seconds, and pressing Space selects whichever option is highlighted.
I also reused graphics objects for the animations, so the coffee changes color when milk is added, ice appears in cold drinks, and the cup slides across the counter when served.
It's been fun experimenting with how much you can do in MATLAB while staying within the 10,000-character limit.

I made TOP BINS — PENALTY SHOOTOUT using MATLAB and Codex, and wanted to share a small trick I used for the one-button controls.
The idea is simple: the target keeps moving around the goal using sine and cosine. Pressing SPACE locks the aim, and then a power slider starts moving automatically. Press SPACE again to shoot at the selected power.
I used different game modes to make the same button do both things:
s.t = s.t + dt;
if s.mode == 1 && tap
s.mode = 2;
s.t = 0;
elseif s.mode == 1
s.aim = aimAt(s);
elseif s.mode == 2
s.p = 1 - abs(1 - mod(.79*s.t, 2));
if tap
s = launch(s);
end
end
The green power range also changes depending on where you're aiming, so each shot needs slightly different timing.
It's a simple way to get two different actions out of just one button. Thought it might be useful for anyone making a game for the Mini Hack. Also you can notice the cheeky billboard ad with MATLAB on it and the crowd :D
Here's my game, ENJOY!: https://www.mathworks.com/matlabcentral/communitycontests/contests/10/entries/16673

- Optimize AST, not whitespace: tree2str expands spacing back out, so save characters by cutting duplicate variables, struct fields, and repeated property strings—not spaces.
- Use complex numbers (x + 1i*y) for 2D math: One array holds both X and Y, abs(z1 - z2) handles hitboxes, and z .* exp(1i*theta) rotates shapes in one step.
- Batch sprites into single handles: Pre-allocate one patch or line per object type in init, then update all active instances at once with NaN-separated vectors.
- Wrap repeated graphics calls: Short inline handles like p=@(x,y,c)patch(ax,x,y,c,'EdgeColor','none','HitTest','off') save hundreds of characters across UI and sprites.
- Pack scalar state into one vector: Store timers, score, lives, and flags in a single numeric array v instead of separate struct fields.
The MATLAB One-Button Game Mini Hack does not allow commonly used audio functions such as sound and audioplayer. However, two other built-in functions, uihtml and sendEventToHTMLSource, are available. By combining these functions with HTML and JavaScript, you can play background music and sound effects in your game!
Here is a working example:
Feel free to check it out!
I made a little game called TIDE//SHIFT for the One-Button Game Mini Hack using MATLAB and Codex.
One thing I experimented with was adding momentum to the movement. Instead of instantly changing direction when you press Space, the character drifts a little before turning.
I used a simple damping formula:
target = 110 * polarity;
blend = 1 - exp(-4.4 * dt);
v = v + (target - v) * blend;
A small change, but it makes the game much more fun to control.
If you're making a one-button game, try experimenting with momentum. It really changes how the game feels.

À propos de Discussions
Discussions is a user-focused forum for the conversations that happen outside of any particular product or project.
Get to know your peers while sharing all the tricks you've learned, ideas you've had, or even your latest vacation photos. Discussions is where MATLAB users connect!
Get to know your peers while sharing all the tricks you've learned, ideas you've had, or even your latest vacation photos. Discussions is where MATLAB users connect!
Plus d՚espaces communautaires
MATLAB Answers
Posez ou répondez aux questions concernant MATLAB et Simulink !
File Exchange
Téléchargez un code soumis par un utilisateur ou proposez votre contribution !
Cody
Résolvez des groupes de problèmes, découvrez MATLAB et gagnez des badges !
Blogs
Découvrez le point de vue des initiés sur MATLAB et Simulink !
AI Chat Playground
Utilisez l’IA pour générer un draft initial de votre code MATLAB et répondre aux questions !



