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;
the projectile of the bolo on different gravity
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
  1. 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.
  2. Use about 70% power. At 35° the safe power is 63% to 80%, and full power sends the ball over the bar.
  3. 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! 🌙⚽
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
  1. 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.
  2. 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.
  3. 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? 🛰️
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.
Animated Demonstration
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{{:});
The direction arrows are created with quiver, using s.U and s.V for their vector components:
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

  1. 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.
  2. 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.
  3. 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.
  4. 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.
Hamza Latif
Hamza Latif
최근 활동: 2026년 11월 23일 17:27

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
  • 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!
Hamza Latif
Hamza Latif
최근 활동: 2026년 11월 23일 16:07

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.
How to Play
In Circuit Runner, your goal is to make your way through a series of logic gates while staying ahead of the glitch chasing you.
Each gate has a set of binary inputs, either 0 or 1. Work out what the output should be and press when the scanner highlights the correct path.
  • Upper path: Output 1
  • Lower path: Output 0
Your first press locks in your answer for that gate, so make sure the correct path is highlighted before pressing.
If you choose the wrong path or fail to answer in time, your signal gets jammed, allowing the glitch to catch up. Keep getting the answers right to stay ahead!
STEM Concept: Boolean Logic
Boolean logic is the basis of how digital circuits work. It uses two possible values, 0 and 1, which can also represent false and true.
Logic gates take one or more binary inputs and produce an output based on a particular rule.
For example, an AND gate only produces an output of 1 when both its inputs are 1. An OR gate, on the other hand, produces 1 when at least one input is 1.
In this game, you'll come across different gates and need to quickly figure out their outputs. This is the same process used to construct truth tables in digital logic.
Timing Your Press!
You'll need to think quickly as the game progresses.
  • Read the gate and its inputs as soon as they appear. Try to work out the output before looking at the scanner.
  • The scanner starts at 0 for every new gate and switches between the two paths. Press when it highlights your answer.
  • As you move through the stages, the scanner switches faster and the gates approach more quickly, giving you less time to decide.
  • Try to get three correct answers in a row to activate a two-second speed boost. Every correct answer also helps you get further ahead of the glitch.
Getting an answer wrong temporarily jams your signal, so it's worth checking your answer rather than pressing too early.
Logic Gate Reference
Here's a quick reference for the gates you'll encounter:
  • AND: Outputs 1 only when both inputs are 1.
  • OR: Outputs 1 when at least one input is 1.
  • NOT: Reverses the input. If the input is 0, the output is 1, and vice versa.
  • XOR: Outputs 1 when the two inputs are different.
  • NAND: Outputs 1 when at least one input is 0.
  • NOR: Outputs 1 only when both inputs are 0.
  • XNOR: Outputs 1 when both inputs are the same.
A useful way to remember the gates is that NAND, NOR and XNOR are simply the opposites of AND, OR and XOR respectively.
If you're unsure about a gate, try thinking about when its output would be 0 instead.
How It Works in MATLAB!
The game uses MATLAB's logical operations to calculate the correct output for each gate.
At the start of each stage, the available gate types are shuffled to give you a different sequence of questions.
The game continuously updates the scanner as it switches between the two paths. When you press, MATLAB locks in the output that was highlighted on the last displayed frame and checks it against the correct answer.
The graphics are updated throughout the game to show the track, scanner position, score and distance from the glitch.
As you play, try to get familiar with the different gates rather than calculating each output from scratch. Once you recognise their patterns, answering becomes much faster, which is exactly what you'll need in the later stages.
EVERDROP is a falling-block game on a five-column board, played with a single button. The contest harness gives a game exactly one signal, pressed, which is true on the frame a tap arrives. There is no hold, no release and no mouse position. Here are three things that made the game work inside those limits, and a short story of how it was built.
Time-lapse of the game, played by a small test bot through the same tap input.
1. Two actions from one tap: act first, undo later
I wanted two moves: rotate the piece, and shift it sideways. The obvious way is to wait a moment after a tap to see whether a second one follows. That makes every rotation feel late.
So the first tap rotates at once and remembers the old shape. If a second tap comes within 0.3 seconds, the rotation is taken back and the piece moves one column instead.
if pressed
if s.tap < 0.3 && ~isempty(s.undoShape)
s = undoRotation(s);
s = stepSideways(s);
else
s.undoShape = s.shape;
s.undoCol = s.pc;
s = rotatePiece(s);
end
s.tap = 0;
end
s.tap is the time since the last tap, increased by dt every frame. Sideways movement goes right until the wall, then left, so one direction is enough.
2. Pixel art as text
imread is on the banned list, so a picture has to live in the code. I store it as a character matrix, one character per pixel, and turn it into colours with ismember:
art = ['....WW......WW...........'
'...BBBB....BBBB..........']; % 20 rows in the game
[~, idx] = ismember(art, '.BWKO');
image(ax, 'XData', [651 795], 'YData', [323 437], ...
'CData', reshape(shades(idx, :), [size(art), 3]), ...
'AlphaData', idx > 1);
shades is a small colour table with one row per letter. The dot is transparent through AlphaData. A 25 by 20 picture costs about 600 characters, and you can edit it in the MATLAB editor like a drawing.
3. Many lines, one graphics object
The floor grid and the mountain ridges are each a single line. Separate segments are joined by putting NaN between them in the coordinate vectors. The whole background is a handful of objects created once in init, and render never touches them.
One more small thing
The blinking prompt needs no timer. render sets its visibility from the running clock in the state: mod(s.clock, 0.8) < 0.55. Calling render twice with the same state gives the same picture, as the contract asks.
How it was built: one evening with an AI assistant
I built EVERDROP in one evening, working with an AI coding assistant (Claude), mostly from my phone. I described the idea in one sentence, asked for a sketch of the screen first, and then steered: how pieces move, what a tap does, what the screen should look like. The assistant wrote the code and ran it in my MATLAB with simulated taps after every change, so most mistakes were caught before I saw them.
Three things I learned:
  • Read the rules first. We spent hours on a version with sound, a window of its own and a hold-to-drop control. Then we read the contest rules: 10,000 characters, no audio functions, and a harness that only reports taps. The entry had to be rebuilt from the ideas, not the code. Hold-to-drop did not survive.
  • The AI tests logic, not feel. It could prove that a double tap moves a piece. It could not tell me whether 0.3 seconds feels right under a real finger. That part was mine.
  • Short instructions work, if you look at every result. Most of my messages were one line: "green on black", "remove moving lines", "add mountains". Each time I got a screenshot back and decided again. It also said no a few times. When I showed it a picture to copy, it drew its own instead.
The validator in the starter project made the loop safe: change, validate, play, repeat.
The game uses 8,731 of the 10,000 characters. You can play it here: https://www.mathworks.com/matlabcentral/communitycontests/contests/10/entries/16663
KARUPPASAMYPANDIYAN M
KARUPPASAMYPANDIYAN M
최근 활동: 2026년 11월 22일 5:41

In MATChess, you play chess against MATLAB with only your mouse click. MATLAB plays white and moves first. You play the dark pieces. Click a piece, then click a green square. That is all you need.
The goal is not just to move pieces. It is to think one step ahead of MATLAB, and to choose the level that matches your skill.
Play the game
Entry page: MATChess
Open the entry, click Play Game, then click Run this app in MATLAB Drive.
The start of a game. MATLAB (white) has made its first move. Now it is your turn.
How to play
  1. MATLAB moves first. Wait until the top line says Your move.
  2. Click one of your dark pieces.
  3. Green squares show every legal move for that piece.
  4. Click a green square to make your move.
  5. When the game ends, click anywhere to play again.
The game only lets you make legal moves. You cannot make a move that leaves your own king in check.
A dark knight is selected. Green squares show where it can go. Yellow squares show MATLAB's last move.
What the colours mean
The line at the top tells you what is happening: Your move., CHECK! Your move., MATLAB is thinking..., or the result when the game ends.
MATLAB is thinking. After your move, it waits half a second and then replies.
Choose your level
There are three buttons on the left side of the board: EASY, NORMAL and TOUGH. Click a button to start a new game at that level. The orange button shows the level you are playing. The game starts on NORMAL.
Try this: play the same first moves on EASY and on TOUGH. Where does MATLAB start to play differently?
How MATLAB chooses a move
MATLAB gives every position a score. A higher score is better for MATLAB. The score has three parts:
  • Piece value: pawn 100, knight 320, bishop 330, rook 500, queen 900, king 20,000.
  • Centre bonus: knights and bishops get extra points when they stand near the centre of the board.
  • Pawn push: pawns get extra points as they move forward.
Then MATLAB tries its moves and your replies, and keeps the move with the best score. It looks at captures first, so it can skip weak moves faster. This idea is called alpha-beta pruning. The king is worth so much that losing it ends the search, and a quicker win scores a little higher.
The rules in the game
Included:
  • All normal moves for every piece.
  • Pawns can move two squares from their first row.
  • Check, checkmate and stalemate.
  • A pawn that reaches the last row becomes a queen.
Not included:
  • Castling and en passant.
  • Draw by repetition and the 50-move rule.
  • Choosing a piece other than a queen when a pawn is promoted.
One click does every job
The game uses just one input: a click. Each click does one job, depending on where you click and what is happening:
  • Click a level button: start a new game at that level.
  • Click one of your pieces: select it.
  • Click a green square: move the selected piece.
  • Click after the game ends: play again.
Each square is 66 pixels wide. The game turns the click position into a column and a row with ceil((x-136)/66) and ceil((y-50)/66). After the game ends, it waits half a second before it accepts a click. This stops a quick click from hiding the result.
How the board is drawn
The board is stored as an 8-by-8 matrix. Positive numbers are MATLAB's white pieces and negative numbers are your dark pieces. The numbers are 1 pawn, 2 knight, 3 bishop, 4 rook, 5 queen, 6 king, and 0 for an empty square. A move is four numbers: the start row and column, and the end row and column.
The code is split into three parts: initialize, update and render. The graphics are created once and then reused. The board is one patch object with 64 squares, and only the colours change from frame to frame. The pieces are Unicode chess symbols in text objects. Each piece is drawn twice: a bigger black symbol behind and a smaller coloured symbol on top. This gives every piece a dark outline.
Try this
  • Can you beat TOUGH? How many moves does it take?
  • Play on EASY and try to catch MATLAB's random mistakes.
  • Can you trap a piece with a knight fork?
Which level can you beat? Tell me in the comments. Thank you for playing!
How to Play
The goal of Descent is to move the ball to the lowest point of the curve using gradient descent.
Watch the moving meter and press to select a learning rate. Each press moves the ball one step and uses up one move.
To complete a stage, you need to get within 0.06 of the target position before running out of moves. If the ball moves outside the plotted range, the game ends.
STEM Concept: Gradient Descent
Gradient descent is a method used to minimize a function, such as the loss function used when training machine learning models.
In this game, the slope of the curve tells you which direction to move, while the learning rate controls how far you move in that direction.
  • A small learning rate gives you smaller steps, which are safer but may take longer to reach the minimum.
  • A large learning rate gives you bigger steps, which can get you there faster but may also cause you to overshoot.
The challenge is to choose a learning rate that gets you close to the minimum without taking unnecessary steps.
Choosing a Learning Rate
Use the tangent line to understand the slope at your current position. After each move, check the loss value to see whether your choice helped.
For the first three stages, the meter is colour-coded:
  • Cyan: Moves you closer to the minimum quickly.
  • Amber: May overshoot the minimum but can still reduce the loss.
  • Red: May increase the loss instead of reducing it.
The last two stages have a neutral meter, so you'll need to judge the learning rate using the curve and the feedback from your previous moves.
A Few Hints for Each Stage :)
  1. First Contact: Try a learning rate of 1.000.
  2. The Steep Valley: The curve is steeper, so try a smaller rate of 0.250.
  3. Low Gravity: The slope is gentler, so a larger rate of around 3.333 works well.
  4. Shifted Reality: Try aiming for 0.625.
  5. The Final Descent: Start with smaller steps where the curve is steep. As you get closer to the minimum, you can try increasing the learning rate.
In the first four stages, the loss function has the form:
Loss = a * (x - target)^2 + minimumLoss
For these curves, a learning rate of 1 / (2 * a) will take you directly to the minimum in one step.
Try to finish each stage with as many moves remaining as possible to earn a higher score!
How It Works in MATLAB
Every time you press, the game updates the ball's position using the gradient descent rule:
x_new = x - alpha * gradient
Here, x is your current position, alpha is the learning rate you selected, and gradient is the slope of the curve at that position.
MATLAB calculates the gradient from the derivative of the loss function and moves the ball to its new position.
The final stage uses a slightly more complicated function with a quartic term. This means the learning rate needed to reach the minimum in one step changes depending on your current position.
As you play, try experimenting with different learning rates and observe how they affect the ball's movement and the loss. The idea is to get a feel for why choosing the right learning rate matters when using gradient descent.
The MATLAB One-Button Game Mini Hack runs from November 2nd through November 29th, 2026! The challenge is to make a game that can be played with one button. I thought this would be a good opportunity to share some of the graphics and programming ideas behind Arcade, a collection of 15 games I developed in MATLAB using Claude Code and the MATLAB MCP Server.
Before the 2024 MATLAB Shorts Mini Hack, Tim Marston published his walkthrough of Little Nemo's airship. I learned a lot from Tim's article, and it inspired me to enter the contest. I hope that sharing some of what goes into these games might encourage a few more people to give it a try this time around as well.
You can download Arcade from File Exchange or GitHub, add the project folder to the MATLAB search path, and run:
Arcade();
You can also download the two smaller examples below and experiment with them individually.
Creating and updating graphics
Arcade sports neon-styled graphics. This is accomplished by layering ordinary MATLAB graphics against a dark background. The bright colors used come from the shared GameBase palette, which enables the different games to keep a consistent appearance and accounts for quite a bit of that look.
In Pong, the ball is made by drawing a colored dot, a semitransparent scatter marker and a smaller white dot at the same position. The ball and trail change from cyan through green, gold and red as the ball speeds up, while the center stays white. Against the dark background, these simple shapes give us the bright center and surrounding glow.
To experiment with the ball, download arcadeBallDemo.m, add its folder to the MATLAB path, and run:
arcadeBallDemo();
The example creates the three layers with line and scatter, using the playfield axes, ax:
worldSize = [854, 480];
position = worldSize / 2;
cyan = [0, 0.92, 1];
radiusParameter = max(3, round(min(worldSize) * 0.035));
baseCoreSize = 2 * radiusParameter;
baseDotSize = 5 * radiusParameter;
baseGlowArea = pi * (1.25 * radiusParameter)^2;
coloredDot = line(ax, NaN, NaN, ...
Marker=".", MarkerSize=baseDotSize, LineStyle="none", Color=[cyan, 0.15]);
glow = scatter(ax, position(1), position(2), baseGlowArea, cyan, "filled", ...
MarkerFaceAlpha=0.4);
core = line(ax, position(1), position(2), ...
Marker=".", MarkerSize=baseCoreSize, LineStyle="none", Color=[1, 1, 1, 1]);
ballLayers = {coloredDot, glow, core};
Here's how the ball looks as each layer is added:
Setting NextPlot="add" preserves the existing graphics as we add the layers. Specifying the axes limits by using XLim and YLim keeps the view in place as the ball moves.
Each drawing call returns a handle to its object. With those handles stored in ballLayers, moving the ball involves assigning its new position to the existing objects:
for layerIndex = 1:numel(ballLayers)
ballLayers{layerIndex}.XData = position(1);
ballLayers{layerIndex}.YData = position(2);
end
drawnow
MathWorks' graphics-performance guidance recommends retaining graphics and updating the properties that change. Pong also checks whether its scores have changed before assigning new score text. Its trail uses preallocated position buffers, wrapping around as new positions arrive, and two retained lines display that history as a broad dim stroke with a narrower bright stroke.
Handling inputs using callback functions
The ball example responds to mouse presses through a callback function. After creating the scene, it assigns a function handle to the figure's WindowButtonDownFcn callback property:
fig.WindowButtonDownFcn = @reverseVerticalDirection;
MATLAB executes the callback function when a mouse button is pressed in the window. In the example, it is nested inside the local animateBall function:
function reverseVerticalDirection(~, ~)
velocity(2) = -velocity(2);
end
The two arguments supplied by MATLAB are the source object and event data. The ~ placeholders indicate that this function doesn't use them. As a nested function, it can access velocity in the enclosing function. Each mouse press reverses the shared vertical velocity, which the next loop iteration uses to move the ball.
Arcade routes input through methods on the launcher. Its figure's KeyPressFcn callback property is assigned as follows, where obj is the launcher instance:
obj.Fig.KeyPressFcn = @(~, event) obj.onKeyPress(event);
The anonymous function forwards the event data to onKeyPress, where its Key property identifies the key. The launcher handles its own controls and passes appropriate input to the active game. Button release and scrolling have their own callback functions.
Mouse movement can control a paddle or aim a shot. To track the pointer as it moves within the figure, Arcade assigns a callback function to WindowButtonMotionFcn:
obj.Fig.WindowButtonMotionFcn = @(~, ~) obj.onMouseMove();
Here's the mouse-position tracking part of the launcher's method:
function onMouseMove(obj)
pointer = obj.Ax.CurrentPoint;
obj.MousePos = pointer(1, 1:2);
end
The axes' CurrentPoint gives the pointer position in game coordinates. MATLAB accounts for the axes' position and size, so the same code works when the playfield is resized or surrounded by margins.
On each game update, the launcher passes the stored position to the active game's onUpdate method. In Pong, obj now refers to the game instance. Once the incoming pos is available, its vertical coordinate determines the player's paddle position:
yLimits = obj.DisplayRange.Y;
if ~any(isnan(pos))
obj.PlayerPaddleY = max(yLimits(1) + obj.PaddleHalfH, ...
min(yLimits(2) - obj.PaddleHalfH, pos(2)));
end
The min and max calls keep the paddle's center at least half a paddle height from either edge. Moving the pointer into a margin therefore leaves the whole paddle inside the playfield. The graphics update then applies that position to the existing paddle patches.
The animation loop's drawnow displays pending graphics changes and processes pending callbacks. Keeping callback functions short allows control to return to the loop promptly.
Animating visual effects
When the orb is launched in Flick It!, a call to spawnHitEffect creates a ring and rays that expand and fade. The launcher advances these shared effects alongside the active game.
In arcadeEffectsDemo.m, each click creates a burst at the mouse position, allowing several bursts to expand and fade together. To try it out, download the function, add its folder to the MATLAB path, and run:
arcadeEffectsDemo();
The nested callback function combines mouse-press handling with the mouse-position tracking introduced earlier. Here's the part that creates and stores a new burst:
fig.WindowButtonDownFcn = @createManualImpact;
function createManualImpact(~, ~)
point = ax.CurrentPoint;
position = point(1, 1:2);
if any(~isfinite(position)) || any(position < 0 | position > worldSize)
return
end
[newRing, newRays] = createEffect(position);
activeEffects(end+1) = struct('Ring', newRing, 'Rays', newRays, ...
'Center', position, 'AgeSeconds', 0, 'LastTime', toc(animationClock));
end
The bounds check ignores clicks outside the playfield. createEffect creates the lines, and activeEffects stores their handles, center and timing state. The animation loop updates each burst independently, allowing further clicks while earlier bursts are still expanding.
We can drive the geometry, transparency and line width from a common progress value: 0 when the burst begins and 1 at the end of its lifetime. Inside the function, the ring is updated as follows:
progress = ageSeconds / lifetimeSeconds;
eased = 1 - (1-progress)^2;
opacity = max(0, 1-1.5*eased);
ringRadius = radiusParameter * (1+2.5*eased);
ring.XData = center(1) + ringRadius*ringCos;
ring.YData = center(2) + ringRadius*ringSin;
ring.Color = [cyan, 0.8 * opacity];
ring.LineWidth = max(0.5, 3*(1-eased));
The ease-out expression starts the expansion quickly and slows it down toward the end. The burst fades out before its nominal lifetime finishes. ringCos and ringSin hold the circle's fixed directions, calculated before the loop. Arcade controls the transparency of these lines by assigning an RGBA value to Color, with alpha as the fourth component, ranging from 0 (clear) to 1 (fully opaque).
The row vectors rayCos and raySin contain the eight ray directions. Each ray joins the inner and outer radii, which increase as the burst expands:
innerRadius = radiusParameter * (0.5+1.5*eased);
outerRadius = radiusParameter * (1+3*eased);
for rayIndex = 1:numel(rays)
rays(rayIndex).XData = center(1) + [innerRadius, outerRadius]*rayCos(rayIndex);
rays(rayIndex).YData = center(2) + [innerRadius, outerRadius]*raySin(rayIndex);
rays(rayIndex).Color = [cyan, 0.6 * opacity];
rays(rayIndex).LineWidth = max(0.5, 2*(1-eased));
end
The lines are created when the burst begins, updated throughout its lifetime and deleted when it expires.
Display scaling: Keeping the scene in proportion
Try making the ball example's window wider while keeping its height the same. Space appears beside the playfield, and the ball still travels between the same boundaries. The example's reference window is 854 by 480 pixels, matching worldSize numerically. Resizing scales the playfield on the screen while the game's coordinate system remains unchanged.
The figure and axes use Units="pixels". Taking the min of the width and height ratios relative to the reference window gives the largest scale factor that fits in both directions. Applying that same scale to both dimensions preserves the playfield's 16:9 aspect ratio.
For a 1200-by-480 window, the height limits the scale to 1. The fitted area remains 854 by 480, leaving (1200-854)/2 = 173 pixels on each side. In a 1280-by-720 window, the playfield grows to approximately 1.5 times its reference width and height. Here are four window sizes at a common page scale:
MATLAB already scales graphics defined in data coordinates as the axes resize. For example, a paddle drawn with patch grows with the axes. In the example, marker sizes, font sizes and line widths use points, while scatter sizes use points squared.
To make a circle twice as wide, we need four times its area. Doubling SizeData multiplies its width by only √2:
For resizing, we assign fitScene to the figure's SizeChangedFcn property:
fig.SizeChangedFcn = @fitScene;
The nested fitScene callback function combines the axes calculation with these size updates:
function fitScene(~, ~)
if ~isgraphics(ax)
return
end
availableSize = max(fig.Position(3:4), [1, 1]);
displayScale = min(availableSize ./ worldSize);
fittedSize = worldSize * displayScale;
ax.Position = [(availableSize - fittedSize)/2 + 1, fittedSize];
% Always derive sizes from their reference values
core.MarkerSize = baseCoreSize * displayScale;
coloredDot.MarkerSize = baseDotSize * displayScale;
glow.SizeData = baseGlowArea * displayScale^2;
instruction.FontSize = baseFontSize * displayScale;
playfield.LineWidth = 0.5 * displayScale;
end
The first two entries of ax.Position set the left and bottom position, splitting the unused space equally between opposite sides. The last two give the fitted width and height. The axes limits remain unchanged, so movement and collision calculations keep using the same game coordinates.
At scale 1.5, the marker sizes are multiplied by 1.5 and the scatter area by 2.25. The updated sizes are calculated from their stored reference values. A 34-point reference marker becomes 51 points at scale 1.5, then 68 points at scale 2.
You can also use Units="normalized" to size and position the axes relative to the figure. Arcade's axes setup uses [0 0 1 1] to allocate the full available area:
obj.Ax = axes(obj.Fig, "Units", "normalized", "Position", [0 0 1 1]);
obj.Ax.XLim = obj.DisplayRange.X;
obj.Ax.YLim = obj.DisplayRange.Y;
Arcade's resize method obtains the available dimensions in pixels with getpixelposition and calculates the same display scale. It uses pbaspect to preserve the playfield's aspect ratio. MATLAB fits the playfield within the available space, leaving margins where needed:
axPx = getpixelposition(obj.Ax);
newPs = min(axPx(3) / 854, axPx(4) / 480);
gameAR = diff(obj.DisplayRange.X) / diff(obj.DisplayRange.Y);
pbaspect(obj.Ax, [gameAR 1 1]);
For Arcade, I also wanted markers, text and line widths to grow proportionally with the playfield. MATLAB also supports automatic resizing for text through FontUnits="normalized", which expresses font size as a fraction of the axes plot box height. This works well for text in a playfield with a fixed aspect ratio. Arcade's shared resize helper modifies current property values, using the ratio of the new scale to the previous scale; for example, moving from 51 to 68 points requires multiplying by 2/1.5. The function applies a common display scale to text, markers and line widths, in order to preserve their relative sizes as the window is resized.
FPS scaling: Let elapsed time determine the motion
Suppose that the ball moves 5 game units on each update. At 60 updates per second it travels 300 units in a second, but at 30 it travels only 150. Calculating the state, drawing and processing input all contribute to the time between updates, so we need to measure that interval to maintain a consistent speed.
Gianluca Carnielli discusses the relationship between time and animation frames in Animating Science: Creating Time-Sensitive Animations with MATLAB. In his example, he explains how to create a frame-based animation from time-based coordinates, by choosing the video’s duration and frame rate, calculating the simulation timestep between two consecutive frames, and resampling the coordinates using retime.
In a live game, we process player actions and calculate each new state using the time elapsed since the previous update. Arcade expresses many motion parameters per reference interval, using 60 frames per second (FPS) as its reference frequency. An elapsed time of 1/60 seconds represents 1 reference interval, while 1/30 seconds represents 2. In the example, we define the velocity and reference frequency before the loop and start the clock with tic once the initial scene is displayed:
velocity = [5, 3]; % Game units per reference interval
referenceFPS = 60; % Reference intervals per second
animationClock = tic;
previousTime = 0;
Each iteration measures the time with toc and advances the position:
currentTime = toc(animationClock);
dtSeconds = min(currentTime - previousTime, 0.1);
previousTime = currentTime;
dtScale = dtSeconds * referenceFPS;
position = position + velocity * dtScale;
Here dtSeconds is in seconds, and dtScale counts reference intervals. A horizontal velocity of 5 now gives a movement of 10 game units over 1/30 second. Taking 30 steps of 10 units covers the same 300 units as 60 steps of 5 units. The samples are farther apart, so the motion can look less smooth:
The min(..., 0.1) caps a single represented interval at 0.1 seconds (10 FPS) to limit jumps after a stall. If an update arrives after 0.5 seconds, the code advances only 0.1 seconds, and the remaining 0.4 seconds are discarded.
The reference frequency is 60 FPS; the actual update rate depends on execution. We could also use game units per second and write position = position + velocityPerSecond * dtSeconds.
Arcade schedules its updates with a timer. The callback function assigned to its TimerFcn property calls the launcher's frame-update method:
obj.RenderTimer = timer(ExecutionMode="fixedSpacing", ...
Period=0.02, TimerFcn=@(~, ~) obj.onFrame());
start(obj.RenderTimer)
With fixedSpacing, the period begins after the preceding callback function finishes. The function's own work therefore contributes to the interval between updates. The launcher measures the full interval and passes the resulting time scale to the active game.
The ball example uses a loop with pause. Try increasing that pause:
arcadeBallDemo(Inf, 0.04);
Its measured interval includes both the pause and the surrounding work. Both Arcade and the example use the full drawnow command. The limitrate option can reduce rendering work by limiting display updates to 20 per second; its suitability depends on the animation's required display rate.
Flick It! multiplies its velocity by friction^dtScale, where friction is the fraction of velocity retained over one reference interval. Over 2 intervals, the multiplier is the square of that factor, equivalent to applying it once in each interval. This makes the velocity decay follow the elapsed time.
For accelerating objects, the numerical approximation can still change with step size, and collisions need to account for movement between samples. Pong checks when the ball crosses the paddle's front face and interpolates its vertical position there, allowing a contact to be detected between two displayed positions.
Organizing games using classes
Arcade's registry stores a constructor function handle for each game. When a game is selected, the launcher calls the corresponding constructor to instantiate the game class. Here's an adaptation of the launch sequence, with Pong selected explicitly and obj referring to the launcher:
createGame = @games.Pong;
game = createGame();
game.FontScale = obj.FontScale;
game.init(obj.Ax, obj.DisplayRange)
game.beginGame()
obj.ActiveGame = game;
Each game subclasses engine.GameBase. The shared init method sets up the session and calls the game's onInit, which creates its state and graphics. Assigning FontScale beforehand lets newly created markers and text use the current display size. The launcher stops its render timer before creating the game and restarts it after the initialized game is assigned to ActiveGame. This prevents timer callbacks from running while the game’s state and graphics are being created.
GameBase declares four abstract methods that each game class must implement:
The launcher calls onUpdate on its active game, and MATLAB dispatches that call to the selected subclass. Pong implements paddle and ball movement; Flappy Bird advances its bird and pipes. All games inherit methods for scoring, combo handling and visual effects from GameBase. Window management, menus, timing and common services stay with the launcher.
As a handle class, GameBase lets the launcher keep a reference to the same game instance while its state changes. Position arrays, velocities, scores and graphics handles belong to that instance. Property access attributes allow the host to read the common score while leaving changes under the control of the game classes.
Flappy Bird creates its pipe patches in onInit, then reuses them throughout the game. Their handles and state are stored in private properties of the game instance. Its onUpdate method moves the active pipes across the playfield. Spawning a pipe selects an available pair, assigns its position and gap, and adds it to the active list. Once it leaves the playfield, the pair is hidden and its slot becomes available again:
In the default gravity-and-flap mode, the onKeyPress input handler sets a pending flap flag. The next update applies the upward impulse and clears the flag.
When the window closes, Arcade stops and deletes its timer, calls the active game's onCleanup method and clears its effects before deleting the figure. The smaller examples use MATLAB's onCleanup object to delete their own figure when the function exits. The requestClose callback function assigned to the figure’s CloseRequestFcn property sets a stop flag, letting the current update finish before cleanup removes the graphics.
Recent work on MATLAB graphics and performance
The MathWorks graphics team has also been improving the underlying rendering system. Maddie Moon's article about WebGL describes the R2025a transition, which brought the renderer already used by uifigure to regular MATLAB figures, along with work on stability, consistency and smoothing. Will Jackson also explains related changes to built-in panning, zooming and rotation in his article on the new interactions system.
R2025b focused on quality and stability improvements, building on the changes introduced in R2025a. It also improved performance when capturing successive frames in a loop with getframe, the function used by Arcade’s recording helper to capture and store frames for GIFs and videos.
R2026a included memory and stability improvements for graphics such as scatter and surface plots, described in Adam Danz's overview and the release notes. In addition, Jessa Karlberg describes the redesigned axes toolbar in R2026a, which allows seamless hovering without the animation slowdown issues caused by the toolbar’s continuous mouse tracking in earlier releases, eliminating the need to remove the toolbar as a workaround.
R2026b improved responsiveness for large data visualizations, with plot and plot3 being able to display lines and markers incrementally and shortening the wait time for the first visible results. MathWorks also reports automatic selection of a dedicated rendering GPU on supported Windows and Linux systems with multiple GPUs. These changes are documented in the release notes and the GPU-selection update.
You can inspect your session's default renderer and device with rendererinfo:
info = rendererinfo;
info.GraphicsRenderer
info.RendererDevice
Mike Croucher also describes a new object-management system for R2026b, which can speed up object-oriented MATLAB code by reducing the cost of creating and deleting objects, as well as accessing their properties. The system is currently available as a beta and can be enabled through a package on File Exchange. Its documentation explains the changes to object lifecycle and compatibility.
Developing MATLAB code with AI
Arcade was developed with Claude Code through the MATLAB MCP Server, and the contest welcomes AI assistance as an option.
When working with an AI assistant, consider sharing your project's requirements and any existing code it can build on. Arcade's developer guide, for example, describes the shared game interface and explains how to add a new game. For your own game, you could begin with the main interaction and add features gradually, playing and improving it as you go. When something goes wrong, describe what happened and how to reproduce the problem, such as a ball passing through a wall at higher speeds.
The MATLAB Agentic Toolkit provides workflows for code review, analysis and testing. Its setup guide covers connecting MATLAB to AI applications including Claude Code, GitHub Copilot, OpenAI Codex, Gemini CLI and Amp, and installing MATLAB-specific skills. Through the MCP server, the AI assistant can run MATLAB code and tests, inspect the results, and use them to help diagnose problems and revise the code.
Several implementation choices in Arcade align with the MATLAB Coding Guidelines and performance rules: using a handle class for an object whose identity persists, restricting access to its state, retaining graphics, preallocating known-size arrays and cleaning up timers. The two downloadable examples presented above were checked with MATLAB Code Analyzer and tested for resizing, input, handle reuse and cleanup.
I hope that this article gives you something to experiment with, and perhaps a starting point for the One-Button Game Mini Hack. I look forward to seeing what you make!
thumper
thumper
최근 활동: 2026년 11월 18일 22:12

In Flip Break, the paddle moves on its own and turns around at the edges. You decide when to reverse it and when to boost it to triple speed. The goal is not just to catch the ball, but to meet it with the part of the paddle that sends it toward a surviving brick.
Play the game: [Flip Break]
Flip Break title screen
Play with two control schemes
On the title screen, NORMAL and SWAPPED alternate about every 1.5 seconds. Click or press Space to select the displayed scheme and start.
- NORMAL: The first press reverses the paddle. A second press within 0.24 s boosts it to 3× speed.
- SWAPPED: The first press boosts the paddle to 3× speed. A second press within 0.24 s cancels the boost and reverses the paddle.
The first press acts immediately. The second counts only if received in a later update, and it does not undo the movement from the first. Try both schemes on the same board: which action would you rather have on the first press?
Flip Break in play
Clear all 55 bricks to see Congratulations!. Press once to see Speed Up, then again to start the next round with the same controls. After n clears, both the paddle and ball use 1 + 0.05*n times their starting speeds: 100%, 105%, 110%, and so on. The double-tap window stays the same.
Aim with the point of contact
At a wall, the game reverses the velocity component perpendicular to it. At the paddle, it keeps the ball's speed but picks a direction from six preset angles. Try hitting just right of center (20° from vertical), then near the right edge (60°). Before the next collision, sideways travel divided by vertical rise is tan(θ). For the same rise, the 60° shot travels about 4.8 times as far sideways. The angles are game rules, not a physical model of a paddle.
Calculate what happens between frames
Rather than checking only the ball's end position, the game calculates when the moving circle first touches a brick's face or corner. It advances to the earliest event and then processes the rest of the update. The bounce follows a separate game rule: a brick corner reverses both velocity components. For the paddle, the game checks horizontal overlap when the bottom of the ball reaches the paddle's top, using the ball's horizontal velocity relative to the paddle. A boost can put the paddle under the ball just in time.
Implementation and testing
The collision and paddle-angle routines came from an earlier Breakout prototype. The Mini Hack version separates initialization, updates, and rendering, and reuses its graphics objects. Its single game.m passed the validator at 9,980 characters. The round test set up the last brick twice and let the game register each final hit. It checked both speeds at 105% and 110% and confirmed that a paddle bounce preserved ball speed. This was not a full manual playthrough.
So, I have a Calculus III midterm coming up. Naturally, instead of studying vector fields, I decided to make an entire game about them.
I'd call that studying, right?
After seeing that the MATLAB One-Button Game Mini Hack introduced a new STEM Education category, I immediately wanted to make something for it. Having spent the past few weeks learning about vector fields, divergence, curl, and line integrals, I figured this would be a fun way to put some of those concepts to use.
And that's how FIELD FLIP was born!
The idea is simple: you're a tiny particle navigating through a vector field, and your only ability is to reverse the direction of the field's force. Sounds easy enough, until you realize that Newton's laws of motion are not particularly interested in making your life easier.
With 10 increasingly challenging levels, you'll need to use momentum, polarity changes, and a little bit of vector calculus intuition to reach the exit.
How Do You Play?
You control a small particle traveling through a field of arrows. The arrows represent the combined force from the vector field and your particle's constant rightward thrust.
Your objective is to reach the green exit without crashing into any of the red obstacles or leaving the playable area.
There's just one button: SPACE (or click)!
  • Your first tap starts the level.
  • Every subsequent tap switches between positive and negative polarity.
  • Positive polarity makes the field exert force in its original direction.
  • Negative polarity reverses the field's force.
One thing to remember: flipping polarity doesn't instantly reverse your velocity!
Your particle has momentum. Even if the arrows suddenly point in the opposite direction, your particle might continue moving the same way until the opposing force slows it down.
Trust me, you'll become very familiar with this concept
The Yellow Line Is Your Best Friend!
You'll notice a dashed yellow line extending from your particle.
This is your predicted trajectory, calculated using the particle's current position, velocity, and forces.
It predicts approximately 1.7 seconds of movement, assuming you don't flip polarity again.
Rather than just hoping your particle avoids an obstacle, use this line to see where you're heading.
Pro tip: If the yellow line is heading straight into a giant red circle, you might want to, you know, press SPACE.
Don't Follow The Arrows Blindly!
The arrows show the direction of the current applied force, including thrust, but that doesn't necessarily mean your particle is moving in that direction.
Remember Newton's Second Law?
F = ma
Force changes acceleration, which changes velocity, which eventually changes position.
This means you need to anticipate where your particle will go rather than simply react to where it currently is.
A well-timed polarity flip can slow your particle down, redirect it, or help it narrowly avoid a collision.
A poorly timed flip can send it directly into an obstacle.
I have extensive experience with the second option.
The equation for the current field appears at the bottom of the screen, along with its divergence and curl.
You don't need to solve any integrals to beat the game, but understanding how the fields behave can make navigating them significantly easier.
Who knew Calculus III could actually be useful?
Things Get Interesting After Level 5
Your particle now has less rightward thrust, making it possible for the vector field to push you backward.
You'll also encounter beacons that must be collected before the exit unlocks.
Level 6 introduces the mechanic with one beacon. Levels 7–10 take things further, requiring you to travel back and forth across the field to collect three sequential beacons before returning to the exit on the left.
Yes, that means going through the obstacles multiple times.
And no, the obstacles do not become any friendlier on your second visit.
Some Final Advice
If there's one thing I hope players take away from FIELD FLIP, it's that a vector field describes how forces behave throughout space, but understanding motion requires considering velocity and acceleration too.
The particle doesn't magically follow whichever direction an arrow points. Its movement is the result of forces acting over time.
That distinction is what makes the gameplay interesting, and it's also one of the reasons I wanted to build the game in the first place.
Hopefully, FIELD FLIP makes vector fields a little more intuitive for anyone learning vector calculus, physics, or engineering.
And hopefully, creating it has somehow prepared me for my Calculus III midterm.
If not, at least I have a game to show for it.
Good luck, have fun, and try not to become too personally acquainted with the red circles...
Let me know what level you make it to, and whether you manage to beat all ten!
JKMSMKJ
JKMSMKJ
최근 활동: 2026년 11월 18일 12:41

I have submitted a Quantum Mechanics inspired game named "Quantum Collapse!" to celebrate the STEM week of the OBGMH contest.
The rest of this post can be read in the comment below as I seem to be unable to submit text with LaTeX code and/or multiple hyperlinks.
Can a single button create order from chaos?
BRASS & ENTROPY is an educational puzzle game inspired by Maxwell's demon. The goal is to create a temperature difference between two gas chambers by controlling a mechanical gate.
The game combines particle dynamics, thermodynamics and a Victorian visual aesthetic, entirely within MATLAB.
1. Turning physics into gameplay
Twelve particles move continuously through two chambers. Each button press temporarily opens the gate, allowing particles to move between them.
The player must guide faster particles toward the hot chamber and slower particles toward the cold chamber.
Across three experiments, the required temperature ratio increases, while population constraints and a limited number of gate openings make the final challenge more demanding.
2. Simulating elastic collisions
Particle collisions are calculated using the relative velocity projected onto the collision normal.
For two particles of equal mass:
nv=dv/dist;
vn=sum((s.v(i,:)-s.v(j,:)).*nv);
if vn<0
s.v(i,:)=s.v(i,:)-vn*nv;
s.v(j,:)=s.v(j,:)+vn*nv;
end
The condition vn<0 ensures that the velocity correction is applied only when the particles are approaching each other.
This preserves kinetic energy and momentum during particle-particle collisions.
3. Calculating relative temperature
Rather than assigning an arbitrary temperature to each chamber, the simulation calculates a relative temperature from the mean kinetic energy of its particles:
e=sum(s.v.^2,2)/2;
left=s.p(:,1)<400;
s.N=[sum(left) sum(~left)];
s.T=[sum(e(left)) sum(e(~left))]./max(s.N,1)/s.e0;
s.R=s.T(2)/max(s.T(1),1e-10);
Logical indexing and vectorized operations allow both chambers to be evaluated efficiently.
The temperature indicators therefore respond directly to the simulated particle dynamics.
4. Improving simulation stability
To reduce missed collisions, each frame is divided into smaller physics steps:
n=ceil(dt/.003);
h=dt/n;
This limits each simulation step to approximately 3 milliseconds, independently of the rendering frame rate.
During prototype testing, the maximum relative energy error was approximately 1.78 × 10⁻¹⁵.
5. Creating a Victorian laboratory
All visual elements are generated procedurally in MATLAB, including brass frames, glass chambers, particle trails, analog temperature gauges and the animated mechanical gate.
Graphics objects are created during initialization and reused throughout gameplay, avoiding unnecessary object creation.
6. What the experiment teaches
The game illustrates how selective particle transport can create a difference in mean kinetic energy.
It is an idealized model of Maxwell's demon. Information processing and memory-erasure costs are not included, so the simulation does not imply a violation of the second law of thermodynamics.
Developed using OpenAI Codex and MATLAB MCP, the game was manually playtested, numerically verified and successfully validated within the 10,000-character limit.
Play BRASS & ENTROPY:

Tips & Tricks 정보

Looking to improve your skills and efficiency? Reach your coding goals quickly and more easily with how-tos, tutorials, and shortcuts posted by our staff and community power users.

Do you have your own tips and tricks to share? Help other community users with your insights and experience.