Results for
In week 2, we are excited to see that the overall quality of entries went up. The games became more polished, creative, and ambitious.
Week 1: We were supposed to pick 5 winners. We picked 12.
Week 2: We tried to be more selective. We picked 13!
We’re especially excited about our new STEM Education category. This week we selected 6 winning entries, spanning topics including physics, biology, health, and engineering:
- Soobok / TRANSCRIPTION - one-button climber
- Roatis / RESONANCE — Master the Frequency
- Ahmed / Beat the PID
- Raffaele / X-Ray Guided: a coronary stenting simulator on one fluoro pedal
- Jan Studnicka / Pacemaker
- Shuen / Orbital Rendezvous
This is exactly what we hoped to see: learning through play. And remember, STEM Education comes with a special prize: a MathWorks Stainless Steel Coffee Mug! ☕
The category continues through Week 3, so keep the STEM games coming!
Week 2 Winners for other categories. Congratulations!
Visualization:
Humor:
Physics-Inspired
Game Design:
A one-button game where the hard part is deciding, not tapping.
Radioembolization treats liver tumours from the inside: millions of glass microspheres loaded with yttrium-90 are injected into the hepatic artery, and they stop wherever the blood takes them. There is no steering after the injection. The whole art is choosing where to inject: far enough downstream to spare healthy liver, but upstream of every branch that feeds the tumour. And sometimes the honest answer is: nowhere, do not treat.
That is a single decision made with a catheter tip that slides along an arterial tree, which felt like a natural fit for one button. I am a medical physicist working with X-ray imaging, and after my first entry (X-Ray Guided, coronary stenting) I wanted to try a game where the difficulty is clinical judgement rather than reflexes.
How to play
A shift is 6 patients, each with a different theme: a simple case, lesions in both lobes, a high lung shunt, a bulky tumour, cirrhosis with a poorly vascularised tumour, and a random mix. Anatomy, arteries and lesions are different every time.
- Angiography: the catheter tip runs back and forth along the hepatic arteries. Tap to mark an injection point (up to two), tap while the tip is in the aorta when you are done. Common or proper hepatic artery means the whole liver, a lobar trunk one lobe, a segmental branch only the part of the lobe it feeds. Each tumour is fed by the branch it grows on.
- MAA simulation: a scan shows what you really perfuse, in red. Is the whole tumour red? How much healthy liver? How much goes to the lungs? The activity is planned automatically and the bars show tumour, liver and lung doses against their limits. A menu cycles: approve, go back to the angio (new MAA, small penalty), or decline the patient.
- Report: the post-treatment Y-90 PET, then the 3-month follow-up: treated tumour gone, under-dosed or untreated tumour still there, harmed organs in red.
A complication, or declining a patient who could have been treated, costs a life. About one patient in six has no safe plan at all: spotting those is part of the game.

Real vs. playable
What I kept real
- The workflow: angiography, MAA simulation from the same catheter position, dosimetry, treatment, post-treatment imaging, follow-up.
- Dosimetry is the partition model used clinically: the activity in the perfused territory is shared between tumour and healthy liver in proportion to their masses and to the tumour-to-normal uptake ratio (T/N), and the lung gets the shunted fraction.
- Limits follow published recommendations for glass microspheres, simplified: tumour at least 205 Gy, lung at most 30 Gy, and a healthy-liver limit that depends on how much liver you irradiate (no limit for a small segmental treatment, 120 Gy for a lobe with enough liver spared, 70 Gy for most of the liver, lower with cirrhosis).
- The MAA is only a predictor: the T/N of the spheres can differ from the MAA, so the plan aims at 250 Gy to keep a margin.
- Clues are where they would be: a poorly vascularised tumour shows a faint blush on the angiogram, before the MAA confirms the low T/N.
What I changed for playability
- Synthetic anatomy: one projection, a liver cut into two lobes, 3 + 2 segmental branches, territories assigned to the nearest branch.
- At most two injection points. A tumour that would need three forces you upstream, at the cost of more healthy liver, which is exactly the trade-off I wanted to show.
- The catheter moves by itself, at constant speed: the tap is a choice, not a reflex test.
- The activity is computed for you, and the infusion itself is skipped: in real life the critical decision is the position, and that is what you play.
Three things I learned
1. A one-button game can be a game of decisions. If the game moves things by itself, when you tap becomes the input, and a cycling menu turns one button into any number of choices. Show what the tap does right now, and keep the cycle slow enough to read:
o = mod(floor((t-3)/1.5),3); % 0 approve, 1 back to angio, 2 decline
2. Hidden rules must become visible, or they feel unfair. My first versions had invisible random weights on the vascular territories and lesions placed anywhere: a tumour that clearly sat on one branch could end up 87 % covered, and nobody understood why. Now territories are simply “nearest branch”, every number that decides the outcome is on screen, and the report says why things went wrong. The game became harder to win and much easier to accept.
3. Vectorised geometry is cheap in characters. Territories, coverage and doses are a few array operations on a 256x256 grid, with no loops over pixels:
[~,i] = min(D,[],3); % D(:,:,k): distance from branch k
s.Tm = i==reshape(1:7,1,1,7) & s.v; % one logical map per territory
k = 49.67*A*(1-L)/(tn*s.q+s.w); % partition model: dose to healthy liver
What would you treat, and what would you decline? And if you work in interventional radiology or nuclear medicine: what did I oversimplify?
Magnetic Corridor is a game in which you guide a magnet that moves forward automatically through a winding corridor by reversing its top and bottom poles. A maglev railway line being developed in Japan will pass near the area where I live, which inspired the electromagnet theme.
There is only one button, but pressing it does not instantly reverse the vertical velocity. It changes the magnetic force, which then changes velocity and position. This delayed response makes looking ahead part of the controls. The game does not reproduce real maglev levitation or propulsion, or an exact electromagnetic field.

How to Play
- Press Space or click to start. During a run, each press swaps N/S on the top and bottom of the player together.
- Red walls are N, cyan walls are S, and white walls have no magnetic pole. White walls exert no magnetic force, but touching them still causes a collision.
- A collision displays the distance traveled, Lv, and changes in speed and width. Press to return to the start screen with a new course, then press again to start.
At startup, an approximately 1.5-second title display leads to the start screen. It does not repeat on retries. Close the window with the × button to quit. Input is only whether a press occurred, not how long it was held or where the click occurred.
1. Magnetic Force, Inertia, and Timing
The pole on the top of the player is represented by p: +1 for N and -1 for S. The bottom always has the opposite pole. A press reverses only this sign.
if tap
s.p = -s.p;
end
Position y and vertical velocity vy are not overwritten, so motion remains continuous immediately after the reversal. You need to consider the current direction of motion when choosing when to press for the next bend.
The magnetic force is calculated from the interaction between each wall and the nearest face of the player. bands.Tp and bands.Bt represent the wall poles: +1 for N, -1 for S, and 0 for no pole.
weightTop = 0.25 + 1.5*exp(-max(distanceTop, 0)/95);
weightBottom = 0.25 + 1.5*exp(-max(distanceBottom, 0)/95);
Tp = -260*s.p*bands.Tp*weightTop;
Bt = -260*s.p*bands.Bt*weightBottom;
mag = Tp + Bt;
This game model gives a nearer wall a larger weight. The bottom face has polarity -p, and the lower wall's interaction direction is opposite to the upper wall's, allowing both terms to use the same -p factor. mag is used as the vertical acceleration corresponding to magnetic force.
The motion update adds velocity-proportional drag. Each update is divided into substeps no larger than 1/240 of a second. Velocity is updated first, then position is advanced using that velocity.
h = min(remaining, 1/240);
mag = computeForce(s);
s.vy = s.vy + h*(mag-2.2*s.vy);
s.y = s.y + h*s.vy;
s.x = s.x + h*s.vx;
This is a semi-implicit Euler-style calculation. Drag opposes the current vertical velocity; reversing polarity does not also reverse drag. When neither wall has a pole, mag becomes 0, but velocity does not suddenly become 0. It gradually decays through drag. Actions taken before entering a section with no magnetic poles therefore affect the path through it.
The yellow arrow shows the magnetic component, with a cap on its displayed length. Comparing the arrow with the player's motion lets you observe that the direction of force is not necessarily the direction of travel.
2. Smooth Width Transitions
The Lv increases every 10 seconds of running time. Forward speed starts at 120, increases by 18 per level, and is capped at 300. Each level reduces the corridor width by 2% of its initial width, down to a minimum of 80%. Speed changes at the level boundary, while width changes smoothly over the following 1 second.
s.lv = 1 + floor((s.t+1e-10)/10);
s.vx = min(300, 120+18*(s.lv-1));
u = max(0, min(1, s.t-10*(s.lv-1)));
s.c.w = 1-.02*min(10, max(0, s.lv-2+u*u*(3-2*u)));
u*u*(3-2*u) is smoothstep, with a rate of change of 0 at both endpoints. At Lv2, width changes from 100% at 10 seconds to 98% at 11 seconds. At Lv11, it changes from 82% at 100 seconds to 80% at 101 seconds. The reduction is relative to the initial width, not repeated multiplication by a fixed factor.
The width scale factor c.w multiplies both the corridor half-width and its spatial derivative. Rendering, magnetic force, and collision detection share the same corridor calculation, so the visible and collision walls do not need separate narrowing logic. Collisions remain active during the transition; there is no invincibility period.

Percentages in the HUD and results are relative to the initial settings. SPEED +150% means 2.5 times the initial speed, and WIDTH -20% means 80% of the initial width.
3. Reusing Graphics and Transforming Coordinates
Graphics objects are created during initialization. Rendering updates the data of existing lines, semicircles, text, and arrows. Wall points are supplied as arrays to XData and YData. Points that do not match a given magnetic polarity are set to NaN to split the lines. This groups the walls into a few lines instead of creating an object for every point.
Motion is calculated in world coordinates, with the camera position subtracted for rendering. The vertical expression playerY = s.y - cameraY; follows the same idea. This is a 2D view transformation: the camera follows the corridor without any force pulling the player back to its center. The dark shell, support ribs, and slowly scrolling distant segments are decorative, not magnetic-field visualizations or collision objects.
The corridor combines 3 sine waves, with a random seed chosen initially and on retries. The same seed generates the same course, which also supports comparison tests. Collision detection approximates distance to the wall's local tangent and runs before integration and after each substep. It is not an exact closest-point calculation on the curve or continuous collision detection.
4. Development Takeaways
The game is a single game.m file and contains 9,602 characters using the official mtree → tree2str method. Removing detailed diagnostics, trajectory history, and numerous labels freed up room for the background, displays, and width interpolation.
The 10-second version passed the official validator in MATLAB R2026b with the official Toolkit 1.0.1. Generative AI assisted with design exploration, implementation, validation, and writing. The images in this article were captured with the earlier 18-second version.
To experiment, change just one of the drag coefficient, magnetic force strength, or wave amplitudes or wavelengths, and compare runs with the same seed. This makes the connection to the controls easier to follow. The game offers a way to explore how reversing polarity connects force, velocity, and position through play.
The code consists of excerpts from game.m; the snippets are not intended to run independently.
I submitted a game called Sticky 8 last week inspired by a puzzle from Quanta Magazine. The puzzle is about understanding entropy in a toy universe, whereas my game is just about letting a figure 8 remain unlit (in that puzzle's terminology, keeping the entropy from reaching its minimum). It is made with help from an AI agent (the free one showcased in this starter article). Since this game did not fit in any of the familiar game categories, the AI asked quite a few questions regarding what I meant by bars sticking on a 7-segment display, what was to be scored, what was to be penalized, what kind of timings I was after, etc? After answering those questions as best as I could and half a dozen iterations trying to fix the "timings" & "characters limit" issues, a more or less working version was ready. I tweaked this last version a lot myself to bring the character count down to "4999" as I ran out of agent's "free time" for the day! 😂
Anyway, two interesting things I learnt from the agent (the first was done by the agent on its own while the second was suggested by me):
- Input Guard: Retain a screen for a bit longer by ignoring accidental button/space presses like after a round's result is displayed. For this purpose set a state variable "S.gd=0.6;" (for 0.6s delay) as the result screen loads. Let that variable decrease by "dt" in the updateState() function: "S.gd=S.gd-dt;". And before the next round loads, check not just for "pressed" state but also "S.gd<=0". Bingo! Your game player is not frustated by their best score vanish right before their eyes.🥳
- Title Fly-out: This powerpoint-style transition effect was quite easily implemented (by the agent). Here's the problem description: the title on the title screen is to be animated from its prominent screen position to the top of the screen, while its fontsize decreases and its colour fades to white. The following code loops inside the "renderFrame()" function (with the initialization code setting "S.anT=s.t;" and "S.t" increasing with "dt" somewhere in the "updateState()" function):
p = min(max((S.t - S.anT)/.9, 0), 1); %0.9s is the time duration for the animation
pe = p^2 * (3 - 2*p); % smooth-step easing!?
set(G.titleH, Position=[2.5,3.5+.591*pe], FontSize=38-22*pe, Color=cg+([1 1 1]-cg)*pe);
%So the header title's Position(2) changes from 3.5 to 4.091; Fontsize changes
%from 38 to 16; Color changes from cg=[1 0 1] to [1 1 1]=w smoothly!

That's all for now. Enjoy!🎉
My One-Button Game Mini Hack entry, HOT AIR PILOT, is a hot-air balloon game with a single control. A tap fires the burner. The balloon rises while the air inside is hot, sinks as it cools, and drifts with whichever wind layer it is in. The goal is to land on a green field a couple of kilometers away.

The physics in a few lines
A balloon floats when the hot air inside it is lighter than the air outside. At the same pressure, density goes as one over absolute temperature, so the lift is
ri = r * To / T; % density of the hot air inside
lift = (r - ri) * V * 9.81; % upward force from the hot air
The game compares that lift with the weight of the envelope, basket and pilot, and applies drag. Heat leaks out with Newton's law of cooling, so the inside temperature relaxes toward the outside temperature. A burn adds 3 K. The result feels like holding a ball up with short pushes, because every burn fades away within a few seconds.Putting the lesson on the screen
Two gauges show the balance directly. A green arrow shows the lift and a red arrow shows the weight, and the text at the top reads RISING, FLOATING or SINKING depending on which is larger. On the right, a thermometer shows the inside temperature as a dot and the temperature needed to float as a yellow tick. Solving lift equals weight for the temperature gives the tick:
T = (288.15 - .0065*z) / (1 - M / (rho(z)*V));
As the balloon climbs the air gets thinner, so the tick moves up. Players learn to chase the tick with taps before anyone tells them why.
A forecast made from the same step function
The dotted line is the part players like most. It is the balloon's own update function run forward in 6-second steps with no more burns, until it touches the ground:
for k = 1:300
[x,z,vx,vz,T] = stp(S,x,z,vx,vz,T,6);
S.fx(k) = x; S.fz(k) = max(z,0);
if z <= 0, break; end
end
One function, stp, does both the real flight and the forecast, so the line is always consistent with the game. It bends where the wind changes and it slides sideways each time the player burns, which is wind shear and thermal lag drawn in one picture.
Moving clouds as a wind display
Wind layers need to be visible without a chart. Sixteen clouds are a single scatter object. Each cloud has its own altitude, and each frame its x position moves by the wind at that altitude:
S.cx = mod(S.cx + wnd(S,(S.cy-40)/.24)*12*dt + 50,900) - 50;
Because wnd accepts a vector, no loop is needed. Clouds in different layers slide in different directions, and a player sees the shear before reading a number.
Tuning with a script pilot
My first version let the balloon hover for many seconds after the last burn, and the landing point swung by hundreds of meters. I wrote a small pilot script that climbs, holds altitude and stops burning when the forecast reaches the field, and ran it over random flights. A shorter cooling time and smaller burns made the forecast steady enough to use. If your game has a skill a script can play, it is worth testing that the script can win at human reaction times.
Which wind layer did you end up using?
I made a one-button game that teaches particle swarm optimization (PSO, a search method in which a group of agents shares its best position). Each step, the game draws three colored arrows next to the player's bird. These arrows show the PSO rule: the next move is the sum of "keep going", "my best spot" and "flock's best spot". The other birds follow this rule exactly, and the whole flock sometimes gets stuck at a trap, which is a local maximum of the smell. The player can then leave the flock, search other places and lead it to the real food.
The 10,000-character limit restricts the design, but I still wanted the game to work for color-blind players. Red-green color blindness is the most common type, and it affects up to 1 in 12 men (8 %) and 1 in 200 women (0.5 %) [Wikipedia]. People with this type often confuse red, brown, green and yellow. In my first version, the green "PSO says" target and the orange "flock's best" arrow could therefore look alike.
I followed three simple ideas from the same article:
- Avoid red-green pairs. The arrows now use light gray, sky blue and orange, and the "PSO says" target is white.
- Do not use color alone. Each marker also has its own shape: a ring, a star or a diamond.
- Use brightness. On the smell map, a brighter spot always means a stronger smell.
The smell map is one line:
set(ax,'Colormap',(.55:.01:1)'.^[2 1 4],'CLim',[0 1]) % green -> white
These changes cost almost no characters, because they mostly replace color values. I would welcome feedback from color-blind players.

*How different people may see the game (approximate views, made with the color-blindness model of Machado et al., IEEE Transactions on Visualization and Computer Graphics, 2009).*
For the MATLAB One-Button Game Mini Hack, I created DECOY, an arcade survival game built around a simple idea:
What if the same button could help you escape and trick your enemies at the same time?
In DECOY, the player controls a glowing courier moving automatically around an elliptical circuit. Hostile drones attempt to intercept the courier, while a single button allows the player to reverse direction and leave behind a temporary holographic decoy.
The decoy attracts nearby drones, creating opportunities to escape or eliminate several pursuers with one well-timed move.
The game's motto is "DECEIVE TO SURVIVE."
The project was developed using OpenAI Codex with MATLAB MCP tools, allowing an AI coding agent to inspect the official contest project, implement the game, run MATLAB checks, and refine the code through several iterations.
Play DECOY — Deceive to Survive:

DECOY — A one-button arcade game featuring predictive drones, holographic distractions, and tactical survival.
Here are some of the most interesting technical and design lessons from the process.
1. Designing a Meaningful One-Button Mechanic
The first challenge was creating a game where pressing one button involves a genuine decision.
In DECOY, pressing SPACE or clicking performs two actions:
- Reverses the courier's direction.
- Creates a temporary hologram if an available charge remains.
The corresponding logic is compact:
if pressed
s.dir=-s.dir;
if s.charges>0
[~,k]=min(s.h(:,3));
s.h(k,:)=[p 2.8 0];
s.charges=s.charges-1;
end
end
The courier always reverses direction, even when no hologram charges are available.
Each hologram lasts 2.8 seconds. The player can hold a maximum of three charges, replenished by collecting packages along the circuit.
This creates an interesting tradeoff.
Using a hologram early may provide a safe escape, but waiting until several drones are nearby could produce a more valuable capture.
The goal was to make timing and positioning more important than rapid button pressing.
2. Moving Along an Elliptical Circuit
Rather than allowing free movement, DECOY keeps the courier on a fixed elliptical path.
The position is calculated from a single angle:
function p=position(a)
p=[400+270*cos(a),305+175*sin(a)];
end
The courier advances automatically by updating the angle:
s.theta=mod(s.theta+s.dir*.78*dt,2*pi);
Here, s.dir determines the direction of travel, while dt makes the movement dependent on elapsed time rather than the number of rendered frames.
This approach has several benefits.
First, the player's movement remains predictable. Second, the game only needs to manage one movement parameter. Finally, enemy drones can anticipate where the courier is likely to be in the near future.
The ellipse is also a useful visual design element. It creates a clearly defined arena without requiring complicated level geometry.
3. Giving Drones Predictive Pursuit Behavior
One of the main gameplay challenges was making the drones feel threatening without making their movement completely unpredictable.
The drones use a lightweight, rule-based steering system.
Instead of always chasing the courier's current position, they estimate a future position along the elliptical path.
The core calculation is:
target=position(s.theta+s.dir*.78*min(1.4,norm(p-q)/speed));
The estimated lead time depends on the distance between the drone and the courier, together with the drone's speed.
This produces a simple form of predictive interception.
A drone approaching from inside the ellipse can aim ahead of the courier instead of constantly following behind it.
The important distinction is that this behavior does not require a trained machine-learning model. It is implemented through geometry, prediction, and steering rules.
That was an important design choice for a game with a strict code-size limit.
4. Making Holograms Change Enemy Behavior
A hologram is more than a visual effect. It changes how the drones select their targets.
The game checks the distance from each drone to the active holograms:
dist=sum((s.h(:,1:2)-q).^2,2);
dist(s.h(:,3)<=0)=inf;
[near,h]=min(dist);
Expired holograms are excluded from consideration by assigning them an infinite distance.
The drone normally pursues the predicted courier position, but a nearby hologram takes priority:
if near<235^2, target=s.h(h,1:2); end
This is what makes the central mechanic work.
A carefully placed hologram can redirect several drones away from the courier. If a drone reaches an active hologram, it is eliminated and awards points.
The player is therefore not simply avoiding enemies. They are manipulating enemy behavior.
I found this much more interesting than implementing another conventional dodge mechanic.
5. Rewarding Clever Decoys
The scoring system encourages players to use holograms tactically.
A captured drone provides a base reward of 100 points. Additional drones caught by the same hologram increase the reward.
The implementation uses:
s.h(h,4)=s.h(h,4)+1;
s.score=s.score+100+25*(s.h(h,4)-1);
s.caught=s.caught+1;
This creates a bonus for multi-drone captures.
Packages provide another incentive to keep moving around the circuit. Collecting one restores a hologram charge, up to the maximum of three, and awards 30 points.
The player also receives points for survival time.
Together, these systems create several possible strategies: survive cautiously, collect packages consistently, or take greater risks to capture groups of drones.
The best score is retained between rounds while the current game session remains open.
6. Progressive Difficulty Without Traditional Levels
DECOY is designed as an endless survival game rather than a sequence of fixed levels.
As time passes, drones become faster and appear more frequently.
Their movement speed is calculated using:
speed=min(142,90+s.t*.48);
This gradually increases their speed while enforcing an upper limit.
The spawning interval also changes over time:
s.spawn=max(.85,2.5-.018*s.t)*(1+.12*sin(s.t*.7));
This gradually increases pressure while introducing some variation into the arrival rhythm.
The game uses a fixed pool of twelve drone objects rather than creating unlimited graphics objects.
The interface displays a sector indicator that advances with survival time, giving players a sense of progression even though the game uses one continuous arena.
This approach keeps the implementation compact while encouraging repeated attempts to beat the previous record.
7. Creating a Neon-Noir Visual Identity
I wanted DECOY to have a visual identity distinct from a typical arcade prototype.
The final design uses a dark violet background, gold circuit lines, orange drones, blue holograms, and a luminous courier.
The interface includes a central geometric relay, an elliptical arena with subtle markings, charge indicators, a score display, and a dedicated start screen.
The visual design was refined after the first playable version.
Initially, the central area felt too empty and the courier was not visually distinctive enough. Later iterations added more recognizable player geometry, environmental details, and clearer introductory instructions.
An important MATLAB technique was to create graphics objects only during initialization and update their properties afterward.
For example, the courier's orientation is calculated from the tangent to the elliptical path:
v=s.dir*[-270*sin(s.theta) 175*cos(s.theta)];
v=v/norm(v);
w=[-v(2) v(1)];
These vectors are then used to construct a directional shape.
This makes the courier visibly change orientation when the player reverses direction.
The holograms also display a circular arc representing their remaining lifetime, helping players understand when their decoy will disappear.
Visual feedback is especially important when the game is controlled with only one button.
8. Keeping MATLAB Animation Responsive
DECOY separates the simulation from the rendering logic using the contest's required init, update, and render functions.
The graphics objects are created in init, while render updates existing object properties.
The simulation also divides longer time steps into smaller increments:
n=ceil(dt/.01);
step=dt/n;
for j=1:n
s=advance(s,step);
if s.mode==2, break; end
end
This limits the internal simulation step to approximately 0.01 seconds.
Smaller steps help maintain more consistent movement and collision behavior when the rendering frame rate varies.
The game also reuses its drone, hologram, and visual-effect objects instead of creating new objects continuously.
These decisions helped keep the implementation manageable and supported smooth real-time gameplay in MATLAB.
9. Developing the Game with Codex and MATLAB MCP
One of the most interesting aspects of this project was the development workflow.
Unlike my previous Mini Hack projects, I used OpenAI Codex as the primary coding agent, connected to MATLAB through Model Context Protocol (MCP).
The workflow started with the official Mini Hack starter project.
Codex first inspected the project structure, read AGENTS.md, identified the contest restrictions, and checked which MATLAB tools were available.
Before implementation, it proposed three different game concepts. I reviewed the alternatives and selected DECOY because its combination of deception, movement, and enemy prediction seemed particularly suitable for one-button gameplay.
Codex then implemented the game directly in game.m.
Through the MATLAB MCP integration, it could execute MATLAB commands, inspect the implementation, run static analysis, and invoke the official contest validator.
The development process included:
- Initial implementation of the arena and pursuit mechanics.
- Validation against the contest rules.
- Programmatic checks of gameplay state transitions.
- Live gameplay checks in MATLAB.
- Visual refinements based on screenshots and manual playtesting.
- A final change to the start-screen slogan.
The AI handled much of the coding and technical verification. My role was to select the concept, assess the gameplay, evaluate the visual results, request improvements, and make the final design decisions.
This was a useful demonstration of how AI-assisted development can support an iterative workflow without removing the importance of human testing and judgment.
10. Lessons from the 10,000-Character Constraint
The contest's 10,000-character limit shaped many implementation decisions.
Rather than using a complicated pathfinding system, DECOY relies on geometric prediction and simple steering.
Instead of building multiple arenas, it creates increasing difficulty within a single circuit.
And rather than continuously creating new effects, it reuses a small collection of MATLAB graphics objects.
The official minihackContest.validate command was used during development to check compatibility with the contest requirements.
The main lesson was that technical constraints can encourage more focused game design.
A compact implementation does not necessarily mean a shallow game. The interaction between a moving courier, predictive drones, and temporary holograms can generate surprisingly varied situations.Final Thoughts
DECOY started as an experiment in designing a meaningful one-button mechanic.
The result is a small arcade game where success depends on understanding how enemies react to the player's actions.
A well-timed press can turn a dangerous pursuit into an opportunity to score points.
The project also demonstrated how OpenAI Codex and MATLAB MCP tools can be combined to develop, validate, and refine a complete game inside MATLAB.
My biggest takeaway is that interesting gameplay often comes from combining a few simple rules rather than adding more controls or features.
In DECOY, one button is enough to reverse direction, create a distraction, manipulate enemy behavior, and sometimes escape a seemingly impossible situation.
DECEIVE TO SURVIVE.
Thanks for reading, and I hope you enjoy playing DECOY!
In a cath lab, the most important button is a pedal: press it and you see, release it and the image freezes. Every second you press costs radiation dose. That felt like the perfect one-button game.
My entry, X-Ray Guided, simulates a coronary stenting procedure from the groin to the heart. I work on fluoroscopic image quality as a medical physicist, so I wanted the X-ray image and the dose to behave like the real thing, at least where it matters for the game.
How to play
You are on shift in the cath lab. Patients arrive one after another, each with two random traits (obese, tortuous iliacs, tachycardic, small vessel, renal failure, calcified vessel) that change how the case plays. Three complications end your shift.
Each patient has four steps, and the line at the bottom of the screen always tells you what the tap does right now:
- Wire: tap to start pushing the guidewire blind and watch the FEEL bar. When you meet resistance, you can keep pushing blind (risky) or tap to switch fluoroscopy on. With X-rays on, the wire tip rotates: tap when it lines up with the vessel, or wait and let it creep through slowly while the dose climbs.
- Angiography: tap to inject contrast, then tap again at peak opacification to save the reference image of the lesion.
- Stent: without contrast the vessel is invisible. The stent slides along the wire; use the reference image (top left) and the small contrast puffs at each end of its travel, then tap to deploy it on the lesion.
- Balloon: it inflates by itself, faster and faster. Tap inside the yellow box, at nominal pressure.
A full HARM bar, a full DOSE bar, a missed lesion or a wrong inflation is a complication. Score depends on lesion coverage and expansion, minus dose, vessel trauma and time; consecutive clean cases give a multiplier.

One pedal, many jobs
The contest gives you a single tap, with no hold and no release. That turned out to fit the cath lab surprisingly well, because a real procedure is also a sequence of single, well-timed decisions, and each phase asks a different one:
- Navigation: do I need to look? The wire goes up mostly by feel. The tap is the moment you decide that the resistance in your hand is worth some radiation to understand.
- Fluoroscopy on an obstacle: now, or wait? Tapping when the tip lines up is fast but risky; waiting lets the wire creep through safely, and the DOSE bar shows what that patience costs.
- Angiography: when is the vessel best filled? Saving the reference too early or too late leaves you with a poor map of the lesion for the next step.
- Stent: is it on the lesion? With the contrast gone, you deploy from memory of the reference image and from the short puffs, each of which costs extra dose.
- Balloon: when do I stop? Too little and the stent is under-expanded, too much and you overstretch or rupture the vessel.
So the tap always means “act now”, but what it acts on changes with the phase. Two things made this readable: the game moves things by itself (the tip rotates, the stent slides, the balloon inflates), so when you tap is the decision, and not tapping is a decision too; and a line at the bottom of the screen always says what the tap will do next.Real vs. playable
What I kept real
- Most of the wire’s journey is done without X-rays, by feel. Fluoroscopy is switched on when you need it.
- The image is built like a fluoroscopy frame: attenuation of anatomy, vessel and devices, quantum noise that grows with the signal, and a recursive temporal filter that reduces noise but leaves lag behind moving objects. Release the pedal and you are left with the last image hold.
- Cine costs much more than fluoroscopy. Here it is 5 times per second, so the contrast injection and each puff are visible jumps on the DOSE bar.
- Coronary arteries are invisible without contrast, while the stent’s marker bands are not. That is why a good reference image matters.
- An obese patient means a noisier image and more dose for the same procedure.
What I changed for playability
- Time is compressed: a procedure lasts a couple of minutes, so the DAP values on screen are game numbers, and the per-patient limit is a game rule, not a clinical threshold.
- The contrast puffs during stent positioning are automatic, at each end of the stent’s travel, instead of being a separate action.
- The stent and the balloon move by themselves, so that the single tap becomes a timing decision.
- One projection, simplified anatomy, and a vessel that bends only where the obstacles are.
On the code side, the whole X-ray monitor is a single 128x128 image whose CData is rebuilt every frame from an attenuation map, with noise and temporal filtering added in two lines. For fitting everything into the character limit, Ahmed’s post on how the validator counts reformatted code says it better than I could.
How long does your shift last? And if you work in a cath lab: what would you add?
What happens when you take a classic Pac-Man style maze game and limit the player to just one button?
That was the idea behind MAZE FRENZY, my entry for the MATLAB One Button Game Mini Hack.
The player moves automatically through a maze, collecting pellets while avoiding four pursuing ghosts. A single click changes direction at available turns. Power orbs temporarily reverse the chase, allowing players to capture ghosts and earn bonus points.
How to play
- Collect pellets for 10 points each.
- Collect power orbs for 50 points.
- Capture powered up ghosts for 200 points.
- Survive with three lives.
- Clear the maze to advance to faster levels.
Gameplay screenshot

Figure1. Maze gameplay showing the player, ghosts, pellets,
power orbs, and scoreboard.
Inside the MATLAB code
The game follows the init,update, and render architecture.
- init constructs the maze and initializes graphics.
- update handles movement, collisions, scoring, and ghost behavior.
- render updates the existing graphics objects.
The maze uses a logical matrix (true for walls and false for paths). MATLAB functions such as image, scatter, text, find, set, abs, and sprintf handle the graphics and game logic. Ghosts use Manhattan distance calculations to pursue the player and retreat when a power orb is active.
What I'd improve next
I would like to explore breadth first search for smarter ghost navigation, individual ghost personalities, procedural maze layouts, and smoother character animation.
The interesting challenge was making a familiar arcade game work with just one button. It turns movement into a strategic excercise in timing and anticipating the next junction.
How would you approach ghost AI in MATLAB for shortest path search or individual enemy behaviors?
If you had to catch up with a spacecraft ahead of you in the same orbit, what would you do?
The intuition is to speed up and catch the spacecraft ahead. In orbit, that’s wrong. To catch something ahead of you, you burn retrograde and slow down.
Why burning retrograde works
Slowing down drops you into a lower orbit. A lower orbit is shorter and faster, so you complete each revolution sooner and gain on the spacecraft ahead every lap.
At the lowest point of that new orbit you’re actually moving faster than your target. Speeding up does the opposite: you climb higher, your orbit takes longer, and you fall behind.
You start in the same 800 km circular orbit as a space station, trailing it by 25–55° with 400 m/s of Δv. One tap starts a burn and the next tap cuts the engine.
Burns alternate automatically: the first is retrograde, the second prograde, then retrograde again, and so on.
How to win
- Win: get within 200 km of the station with a relative speed below 50 m/s.
- Don’t burn up: if your orbit drops below 120 km altitude, you burn up in the atmosphere.
- Watch your fuel: you have 600 m/s of Δv.
- Beat the clock: you have 20 orbits to dock.

Key terms
- Prograde: thrusting along your direction of travel. Speeds you up and raises the opposite side of your orbit.
- Retrograde: thrusting against your direction of travel. Slows you down and lowers the opposite side of your orbit.
- Perigee: the lowest point of an orbit.
- Apogee: the highest point of an orbit.
What I learned building the game: realism vs. playability
I started out trying to make everything 1:1 with real orbital mechanics. It was physically accurate, but it was frustrating to play. Some trade-offs had to be made:
What I kept real
- The game simulates planar Keplerian dynamics. Burns are applied either along (prograde) or against (retrograde) your velocity vector.
- Orbital mechanics: to catch a station that’s ahead of you, you slow down. A retrograde burn reduces your semi-major axis a, and since the orbital period is T = 2π·sqrt(a³/μ), a smaller orbit has a shorter period. You gain on the station every revolution.
- The vis-viva equation v² = μ(2/r − 1/a), shows that speed is highest at periapsis and lowest at apoapsis. At the periapsis of your lower orbit you’re moving faster than the station, even though you got there by braking.
- To stop drifting, do a prograde burn back at the point where you first burned, which is now your apoapsis. Raising a back to the station’s radius recircularises your orbit and matches its period.
What I changed for playability
- Time warping. A real orbit at this altitude takes about 100 minutes. In the game it takes 8 seconds, roughly 750x real time.
- Burn in slow motion. Time runs 4x slower while the engine fires, so you can actually control how long a burn lasts with one button.
- A strong engine. Thrust is about 0.4 m/s², which is way higher than a normal spacecraft but it means a burn takes a few seconds instead of minutes.
- Exaggerated distance. In the game the distance from the station’s orbit is stretched 3x, otherwise the difference of the orbits wouldn't be visible.
- A generous docking gate. A realistic range (tens of km and relative velocity around 15 m/s) was nearly impossible to hit, so I widened it to 200 km and 50 m/s.
1. TRANSCRIPTION: Climb the Helix
You are RNA polymerase climbing a DNA double helix. Each rung is a base pair, and the next one is either up-left or up-right. An arrow swings back and forth above you, and a tap steps the way it points. Pick the wrong side and the polymerase stalls. Every step reads one template base and adds its partner to your growing mRNA (A to U, T to A, G to C, C to G), which trails behind you as colored tiles. Your NTP bar drains constantly and refills a little with each step. Each stage is one gene that starts with AUG and ends with a stop codon, and finishing one refills your NTPs for the next, longer gene.
The biology: RNA polymerase really does build RNA from four NTPs (ATP, GTP, CTP, UTP), which are both its building blocks and its energy, so running out stops the process. As it moves, the two DNA strands open into a small transcription bubble that closes again behind it, and you can watch that bubble travel up the helix with you. The game takes liberties: real polymerases don’t hop sideways, and real transcripts carry untranslated regions instead of ending at the stop codon.
2. IMMUNE HERO
You are a T cell travelling through a blood vessel. Pathogens drift in from the right, and a tap launches an attack with a short cooldown, so timing is everything. Every fifth wave brings a boss. Defeated pathogens drop XP, and on level-up you choose one of three upgrade cards: tap to light a card, tap again to move to the next, and stop tapping for two seconds to confirm. Upgrades stack, so every run grows into a different immune cell.
The biology: each upgrade borrows from the real immune response. Cytokines coordinate immune cells, so they speed up your attacks. Interferons warn neighbouring cells, so they hit everything nearby. The complement system punches holes in pathogen membranes, so it pierces. Memory cells make a second infection milder, so they give you a second life. In a real body antibodies come from B cells, not T cells, so think of this hero as the whole immune system squeezed into one cell.
Tips
Judge the tap against what the player saw. In TRANSCRIPTION, my first version moved the arrow before checking the tap, so a tap made while the arrow clearly pointed the right way could be judged against the next frame and count as a miss. Reading input before advancing any animation that decides the outcome removed every unfair fall.
Lock one-button menus for a moment. In IMMUNE HERO, players are usually mid-combo when they level up. Ignoring taps for the first half second after the menu opens stops their next tap from picking a card by accident.
And if you lose
Don’t worry too much. Right now, inside your own cells, real RNA polymerases are transcribing at dozens of nucleotides per second with only about one mistake in ten thousand or more, and your immune system is quietly stopping pathogens every day. You may lose the game, but your body is already winning it. Have fun!
The goal is simple: help MATLAMB escape through all 10 farms without getting caught!
But with farmers patrolling, dogs following your trail, and a new challenge in every farm, escaping won't be easy!
The Controls
You only need one button!
- Tap or press SPACE to start walking.
- Tap again to stop walking.
- Stop inside a bush to hide from farmers.
Watch Out for Farmers!
Each farm has a farmer patrolling back and forth. Farmers can only see in the direction they're facing, so pay attention to where they're looking!
If a farmer spots you, the ALERT meter starts filling up. Once it's full, you're caught! Farmers will also follow you once they've spotted you, so make sure you find a hiding spot before it's too late.
Beware of the Dogs!
Hiding from farmers is only half the battle! Each farm also has a dog that follows your trail.
If you stay hidden in a bush for too long, the dog can eventually catch up and sniff you out. Watch the DOG meter , if it fills completely, you're caught!
Ten Farms, Ten Challenges!
Each farm introduces something new:
- Field: Learn the basics of walking, stopping, and hiding.
- Watch: The farmer looks behind himself more frequently.
- Dogs: A faster dog makes camping in bushes more dangerous.
- Fog: The farmer has a shorter viewing distance.
- Light: The farmer's lantern allows him to see in both directions when illuminated.
- Chase: The farmer moves faster when chasing you.
- Mud: Muddy areas slow MATLAMB down.
- Wind: Changing winds can speed you up, slow you down, or even push you while you're stopped!
- Bark: Getting too close to the dog while walking can alert the farmer.
- Gate: Moving near the final gate rings a bell that alerts the farmer.
Checkpoints
Don't worry if you get caught! You'll unlock checkpoints after reaching Farms 4 and 7, meaning you won't always have to start from the beginning.
Tips for Escaping
- Watch which way the farmer is facing before moving.
- Don't stay in bushes too long—the dogs are always approaching!
- Keep an eye on your ALERT and DOG meters.
- Be extra careful in the Wind farm, since stopping doesn't always mean staying still.
- Sometimes it's better to keep moving than to risk hiding in the wrong spot.
Good luck helping MATLAMB escape!
Hello Everyone!
For the MATLAB One-Button Game Mini Hack, I created MATLAMB ESCAPE!, a side-scrolling stealth game where a sheep (inspired by the real MATLAMB!) tries to escape through ten farms while avoiding farmers and their dogs. The entire game is controlled using just one button: tap to start walking, and tap again to stop. Stopping inside a bush lets the sheep hide from farmers, but the dogs can still follow its trail, so you can't stay hidden forever! Each section also introduces its own unique challenge to keep things interesting. Keep reading to find out what awaits MATLAMB Escape!

(If you would like a tutorial on the game, make sure to check out my other Tips & Tricks post!)
The Idea
When I started brainstorming ideas, I knew I wanted to do something fun Mathworks related. After spending a few days brainstorming ideas and getting nowhere, I finally found my inspiration in this perfectly timed Mathworks Instagram Post! There is an actual sheep born in 2024 at Mass Audubon's Drumlin Farm in Massachusetts and named in honor of MathWorks. Apparently, some of the sheep escaped their barn, and MATLAMB was suspected of leading the charge! You literally cannot make up a better MATLAB game idea.
Designing around one button
My biggest design challenge was making a stealth game that still requires strategy without having separate movement and hiding controls.
I decided to make the sheep move automatically when walking is toggled on. Instead of controlling its direction, players have to observe the farmers movements and make tactical decisions on when to stop.
However, I quickly realized that players could just camp in bushes until the perfect opportunity to move, which took away much of the challenge. So, how did I fix this? Puppies! No, literally. I added dogs that follow the sheep's trail and sniff out its hiding spots, forcing players to keep moving instead of staying in one bush forever.
To prevent the game from feeling repetitive, I gave the ten sections, aka 'farms' different mechanics. These include a farmer with a lantern that detects movement in both directions, muddy terrain that reduces movement speed, and a windmill farm where changing wind directions can push the sheep even when the player stops.
Working with AI and the character limit
I used ChatGPT throughout development to help write, revise, and simplify the MATLAB code. I guided the game's design and continued adjusting the mechanics, enemy behavior, difficulty, and overall gameplay.
One of the hardest constraints was the 10,000-character limit. As I added more mechanics, I had to find ways to reduce the code size without removing the features that made the game interesting.
Some useful approaches included shortening internal variable names, representing multiple enemies with arrays, using shared functions for repeated graphics operations, and constructing scenery from reusable patterns.
My biggest takeaway was that the one-button restriction actually encouraged me to design more creative game mechanics.
I'd be interested to hear how other participants approached one-button game design in MATLAB!
Thank you for taking the time to read my post, best of luck to you all!
For the MATLAB One-Button Game Mini Hack, I created RESONANCE — Master the Frequency, a five-level educational game that transforms a simple physics simulation into an interactive challenge.

RESONANCE — An interactive mass–spring–damper experiment controlled with a single button.
The idea started with a question:
Can someone learn how oscillations work by controlling them with only one button?
Instead of directly moving a character, the player applies impulses to a mass–spring–damper system. Depending on the timing, an impulse can increase or decrease the oscillator's mechanical energy.
The challenge is not to press the button as fast as possible. It is to understand when to press it and why the timing matters.
1. Turning a Physics Equation into Gameplay
RESONANCE is based on the classical mass–spring–damper system.
Its equation of motion is:
m*x'' + c*x' + k*x = F(t)
where:
- m represents mass.
- c is the damping coefficient.
- k represents spring stiffness.
- x is displacement.
- F(t) is the externally applied force.
Between impulses, the game uses the normalized equation for unit mass:
x'' + 2*beta*x' + omega_0^2*x = 0
Here, beta controls damping and omega_0 represents the undamped natural angular frequency.
The simulation uses a compact numerical integration method:
s.v=s.v+(-s.w^2*s.x-2*s.beta*s.v)*dt;
s.x=s.x+s.v*dt;
These two lines update velocity and displacement using a semi-implicit Euler method.
One useful discovery was that changing just a few physical parameters could create very different gameplay challenges.
Increasing damping makes the oscillator lose energy faster. Increasing natural frequency makes the motion faster, forcing the player to adjust the timing of their impulses.
This allowed me to build several levels around the same physical model.
2. One Button, Two Different Energy Outcomes
The main mechanic is surprisingly simple: pressing SPACE applies an impulse toward the right.
The corresponding MATLAB code is:
s.delta=s.v*s.j+.5*s.j^2;
s.v=s.v+s.j;
The change in mechanical energy caused by an instantaneous velocity impulse, assuming unit mass, is:
Delta_E = v*J + 0.5*J^2
Here, v is the velocity before the impulse and J is the velocity increment.
This produces an interesting result:
- When the mass moves to the right, a rightward impulse increases its kinetic energy.
- When the mass moves sufficiently fast to the left, the same impulse reduces its kinetic energy.
- If the mass moves too slowly to the left, the impulse can reverse its direction and still increase its energy.
In other words, the same button can accelerate or brake the oscillator depending on its current motion.
The player gradually discovers this relationship through experimentation.
This became the foundation of the game's educational design.
3. Measuring Amplitude Through Energy
Another important challenge was determining whether the player had successfully controlled the oscillator.
Instead of checking only the mass's position, the game calculates an energy-based amplitude indicator:
s.A=sqrt(s.x^2+(s.v/s.w)^2);
For the corresponding undamped oscillator with unit mass, mechanical energy is:
E = 0.5*v^2 + 0.5*omega_0^2*x^2
From this expression, an equivalent amplitude can be calculated:
A = sqrt(x^2 + (v/omega_0)^2)
In the damped simulation, this serves as an instantaneous energy-based amplitude indicator rather than an exact prediction of the next displacement peak.
The player must maintain this indicator within a specified target range for a certain amount of time.
This creates an interesting challenge: reaching the correct amplitude is only part of the solution. The player must also prevent the system from gaining or losing too much energy.
4. Designing Five Educational Levels
I organized RESONANCE into five experiments, each introducing a different learning objective.
Level 1 — Energy Transfer
The player learns how properly timed impulses can increase the oscillator's energy and amplitude.
This first level introduces the basic relationship between motion, timing, and energy transfer.
Level 2 — Damping
The damping coefficient increases, causing the oscillator to lose energy more rapidly.
The player must compensate for that loss by applying impulses at appropriate moments.
The objective is to understand that maintaining an oscillation requires replacing the energy dissipated by damping.
Level 3 — Precision Control
The player must apply at least one impulse that reduces mechanical energy.
This level introduces active braking and demonstrates that applying more force is not always the correct solution.
Sometimes the best action is to remove energy.
Level 4 — Natural Frequency
The oscillator's natural frequency increases.
Its oscillations become faster, giving the player less time to react.
The challenge includes two phase-aligned impulses, encouraging the player to adapt to the system's changing dynamics.
Level 5 — Resonance Challenge
The final experiment requires three phase-aligned impulses followed by precise amplitude stabilization.
The game recognizes favorable impulses near the equilibrium position while the mass is moving toward the right:
if s.v>0 && abs(s.x)<40
s.sync=s.sync+1;
end
This demonstrates how the timing of repeated energy transfers influences the buildup of oscillations.
Classical resonance involves periodic excitation near a system's natural frequency. RESONANCE uses discrete impulses instead, providing a simplified, interactive analogy of phase-synchronized excitation rather than a complete simulation of sinusoidal resonance.
5. Making Physics Visible
I wanted RESONANCE to look like an interactive physics laboratory rather than a traditional arcade game.
The interface includes:
- An animated mass connected to a spring.
- An oscilloscope-style displacement trace.
- Highlighted target amplitude regions.
- A real-time amplitude indicator.
- A stability progress bar.
- Feedback about energy transfer and impulse timing.
One useful MATLAB technique was creating the graphics objects during initialization and updating their properties during gameplay.
For example, the spring animation uses:
s.coil.XData=linspace(161,p-20,32);
s.coil.YData=271+[0 repmat([10 -10],1,15) 0];
This changes the spring's geometry as the mass moves, creating the appearance of stretching and compression.
The oscilloscope provides another view of the same physical process, helping the player connect the moving mass with its displacement over time.
These visual elements are not merely decorative. They help communicate the behavior of the underlying system.
6. Learning Through Feedback
An important lesson during development was that a game does not automatically become educational just because it contains a physics simulation.
The player needs enough information to understand what is happening.
I therefore introduced contextual feedback during gameplay.
For example, when the amplitude is too low, the game suggests adding energy with a well-timed impulse. When the amplitude is too high, it encourages the player to consider braking.
The game also displays a short explanation after each completed experiment.
The player must press SPACE to continue, allowing time to read the explanation before starting the next challenge.
This creates a simple learning cycle:
Experiment → Observe → Adjust → Succeed → Understand
Rather than presenting equations as a separate lesson, the game connects the explanations to actions the player has already performed.
7. Working Within the 10,000-Character Limit
One of the biggest technical challenges was fitting the physics simulation, five levels, graphics, gameplay logic, and educational messages within the contest's 10,000-character limit.
To keep the implementation compact, I:
- Reused the same graphics objects across all levels.
- Stored level-specific parameters in arrays.
- Used small helper functions for drawing.
- Kept the physics calculations separate from rendering.
- Avoided unnecessary dependencies and additional game files.
The published version contains 9,305 characters according to the official MATLAB contest validator.
A useful lesson from this process was to rely on minihackContest.validate instead of estimating the character count from the source file, because the validator applies its own counting rules.
The character limit also encouraged me to focus on the mechanics that contributed most to gameplay and learning.
8. Development Process and Lessons Learned
AI assistance was used during concept development, MATLAB code generation, debugging, and iterative refinement.
I tested the game in MATLAB, evaluated the difficulty of each experiment, adjusted parameters, refined the educational messages, and validated the implementation using the official contest tools.
One challenge was balancing the difficulty progression.
During early testing, the damping experiment and the final synchronization challenge were particularly demanding. Adjusting the target ranges and stability requirements helped create a more gradual progression.
Another important decision was to distinguish between the physics being simulated directly and the concepts being demonstrated through simplified gameplay.
The main lessons I took from this project were:
- A differential equation can become the foundation of an engaging game mechanic.
- A single input can produce different physical outcomes depending on the system's state.
- Visualizing displacement and amplitude can make abstract concepts easier to understand.
- Increasing difficulty works best when each level builds on previously learned skills.
- Educational feedback is most meaningful when it explains something the player has just experienced.
Final Thoughts
RESONANCE is an experiment in combining simulation, game design, and STEM education within a very small MATLAB project.
The goal was not to create the most complicated physics simulator, but to make a few important concepts intuitive through interaction.
By the end of the five experiments, I hope players have developed a better intuition for energy transfer, damping, natural frequency, and the importance of impulse timing.
Sometimes, the best way to understand a physical system is to try controlling it.
Thanks for reading, and I hope you enjoy experimenting with RESONANCE!
I am unable to submit an entry for the One Button contest using the supplied minihackContest.submit function. I keep getting the error "Submission failed: HTTP 500 Something went wrong. Please try again in a moment.". It happens to me both in a MATLAB session as well as on a MATLAB Online session. No idea what I am doing wrong...
What a start! We’ve already seen almost 100 one-button games in Week 1, packed with creative ideas, clever mechanics, and plenty of surprises. Even better, participants have published 18 Tips & Tricks articles sharing how they designed and built their games, what they learned, and how they used agentic AI along the way.
Now for the difficult part: picking the winners. We planned to select 5 Week 1 winners.
We tried. We really did. We ended up picking 12. 😄
And honestly, even 12 doesn’t feel like enough to recognize all the great games we’ve seen.
Congratulations to our Week 1 winners!
Category: Art & Design
Category: Engineering
Category: Anxiety Raising
Category: Sports
Category: Score = 9999
Category: Simple but fun
Category: Humorous
Category: Retro Design
Special Category for Week 2 & Week 3: STEM Education
For Weeks 2 and 3, we’re introducing a special STEM Education category. Our challenge: Can you help someone learn while they’re having fun?
Your game could teach a MATLAB function or programming concept, demonstrate gravity or projectile motion, simulate a scientific experiment, or visualize an engineering concept.
The possibilities are wide open. Just remember: learning + playing = the goal.
And there’s a special prize too: STEM Education winners will receive a MathWorks Stainless Steel Coffee Mug! ☕

I thought I had the game in pretty good shape until I tried it in MATLAB Online. A launch that felt immediate on desktop could feel slower in the browser, which matters in a game where timing is the main control.
I built Slingshot Home: Escape Saturn for the MATLAB One-Button Game Mini Hack. The goal is to time your launches to travel between 15 of Saturn’s moons and return to Earth, with three shields and a clock counting down.
Getting the game to feel responsive took a few iterations, particularly when running it in MATLAB Online. Here are some of the approaches that worked well.
Reuse Graphics Objects
The game creates 21 graphics objects during initialization and reuses them throughout gameplay. Instead of recreating the scene, it updates properties such as position, color, and text.
I also check whether a property has changed before assigning it again. Static planets and labels do not need to be updated as frequently as the spacecraft.
For the Mini Hack, the game harness handles the window, input, and drawing loop. The game provides the init, update, and render functions.
Use Elapsed Time for Motion
The spacecraft moves around each moon using basic trigonometry:
theta = startAngle + angularSpeed*elapsedTime;
position = moonCenter + radius*[cos(theta), sin(theta)];
heading = [-sin(theta), cos(theta)];
Pressing the button launches the spacecraft along the tangent to its current orbit, so the gameplay is based on timing rather than steering.
Calculating the orbital angle from elapsed game time, rather than advancing it by a fixed amount per frame, also makes the motion less dependent on rendering speed.
Separate Trajectory Calculation from Rendering
I used ode45 to calculate each flight trajectory, then deval and interpolation to provide positions during playback. This avoids solving the trajectory again on every frame.
The physics is intentionally simplified. The moons remain in fixed positions, captures are assisted, and the escape gate represents leaving Saturn’s sphere of influence rather than calculating its actual boundary. These assumptions are documented in the code comments.
Generate Textures in MATLAB
The planet textures are generated directly in MATLAB, so there are no external image files to load:
MATLAB
x = linspace(-1,1,80);
z = max(0,1-x.^2-x'.^2);
brightness = max(.1,.8*sqrt(z)-.6*x);
This produces directional lighting while retaining some brightness on the night side. The textures are generated once during initialization.
Increasing the texture resolution helped smooth the edges, but adjusting the lighting had a larger effect on the overall appearance.
Test as You Go
I used Codex to help edit and refine the code. Through MATLAB MCP, it could run MATLAB code, inspect Code Analyzer results, and exercise states such as countdown, launch, and restart.
That was useful for finding issues, but running and playing the game was still important. Some things only became apparent during gameplay, such as a launch feeling delayed or an orbit being difficult to see. I also tested regularly in MATLAB Online rather than relying only on desktop behavior.
I used the Mini Hack validator to keep track of the character limit:
minihackContest.validate
The validator count differs from the raw file size. Comments are excluded, so I could document the physics and assumptions without using the executable-code budget.
Try It in MATLAB Online
One feature I liked about the final result is that there is very little setup required to try it.
Click “Play game,” then “Run this app,” and the game runs in the browser.
For me, the biggest improvements came from fairly small changes: reusing graphics objects, basing motion on elapsed time, calculating trajectories separately from rendering, and testing regularly in MATLAB Online.
FOLD: One Button, Two Worlds
For the MATLAB One-Button Game Mini Hack, I developed FOLD, a six-level puzzle-platformer built entirely in MATLAB.
Unlike traditional platformers, the player does not directly control the character. Instead, the character moves automatically, while a single button changes the geometry of the environment.
Each press rotates platforms, changes available paths, and activates or deactivates obstacles.
Play FOLD here:

FOLD — Rotating platforms and phase-based obstacles controlled with a single button.
1. Creating Rotating Platforms with Trigonometry
One of the main technical challenges was creating platforms that rotate around a fixed pivot.
Rather than recreating graphical objects every frame, I calculate the vertices of each platform using trigonometric functions.
For a platform with length L, thickness w, and rotation angle a:
dx=L*cos(a);
dy=-L*sin(a);
nx=w*sin(a);
ny=w*cos(a);
px=[x x+dx x+dx+nx x+nx];
py=[y y+dy y+dy+ny y+ny];
These coordinates define the four corners of the platform.
By updating the XData and YData properties of an existing patch, MATLAB can animate the platform without creating new graphics objects every frame.
This approach keeps the animation simple and efficient.
2. Making the Character Move with a Platform
Initially, the character would fall whenever a platform started rotating.
To solve this, I introduced a mechanism that temporarily attaches the character to the rotating platform.
The character's position is calculated relative to the platform's pivot:
s.x=170+s.dist*cos(a)-12;
s.y=440-s.dist*sin(a)-24;
Here, s.dist represents the distance along the platform, while a is the current rotation angle.
This allows the character to move together with the platform and reach elevated sections of the level.
3. Designing Gameplay Around a Single Button
The most interesting design challenge was creating meaningful gameplay with only one input.
FOLD uses two world states: A and B.
Pressing SPACE or clicking the mouse switches between these states. Multiple platforms respond simultaneously, while certain obstacles become active or inactive.
This creates situations where opening one path may close another.
Across six levels, players must learn to anticipate how their actions affect the environment.
The objective was to make the game progressively more strategic without introducing additional controls.
4. Optimizing MATLAB Code for the Character Limit
The competition limits submissions to 10,000 characters.
One important discovery was that the validator's character count could differ significantly from the raw source file length.
Removing whitespace alone was not sufficient.
I reduced code duplication, reused helper functions, represented level configurations using arrays, and simplified unnecessary graphical elements.
The final implementation successfully passed minihackContest.validate.
5. What I Learned
Developing FOLD helped me explore several useful MATLAB techniques:
- Updating existing graphical objects instead of recreating them.
- Applying trigonometry to interactive 2D geometry.
- Managing game states and frame-based updates.
- Designing multiple puzzles around a single input.
- Optimizing code under strict technical constraints.
AI assistance was used during prototyping, debugging, and code refinement. The gameplay was tested locally in MATLAB, and the final submission passed the official contest validator.
The main takeaway: limitations can encourage creativity. With a single button, basic trigonometry, and carefully designed state transitions, it is possible to build an interactive puzzle game with surprisingly varied gameplay.
My second entry, Event Horizon (entry 16546), puts you in orbit around a black hole. Tapping fires your engine and climbs, and the accretion disk's drag pulls you down. Lower orbits slow your clock, so your score is how many years into Earth's future you travel. Flares light up rings of the disk, and you have to get out of a red band before it turns white and burns.

Real frames from the game. In the top left, the ship (cyan, marked YOU) is behind the hole, and gravity bends its light into an arc over the top.
The picture isn't drawn by hand. It comes from tracing light through the Schwarzschild metric, the spacetime around a non-spinning black hole. Here is what I learned building it, again with help from an AI coding assistant (Claude Code), testing each change in MATLAB.
1. Trace the light once, then shade the map every frame
My first prototype traced one light ray per pixel every frame. With rays bending around the hole, that took about 240 ms per frame at 160 by 120 pixels, far over the 33 ms a 30 fps frame allows.
The fix was to notice that the camera never moves. Each pixel's ray always lands in the same place, so I trace every ray once in init and store where it crosses the plane of the disk. In these units, with the Schwarzschild radius set to 1, a light ray's path follows a simple force law, which I step for all 19,200 rays at once:
h2 = sum(cross(P,V).^2); % each ray's angular momentum squared
for k = 1:150
d = min(.07*vecnorm(P),1); % smaller steps near the hole
Q = P+V.*d;
V = V-1.5*h2.*Q./vecnorm(Q).^5.*d;
% ...record where each ray crosses z = 0, drop rays that escape or fall in
end
Each ray keeps its first two crossings of the disk plane. The first is the direct view. The second is light that went around the back of the hole, which is why you can see the far side of the disk both above and below the shadow.

The trace takes about 160 ms at startup on my PC. After that, each frame only shades the stored points, and the game's whole frame work is about 6 ms.

The 240 ms comes from an early prototype with a slightly different camera, so treat the ratio as approximate.2. Paint the game into the disk, and gravity bends it for free
Because the map stores a disk position for every pixel, anything I draw in disk coordinates gets lensed automatically. The ship is just a glow centered on its position in the disk, and the flares are rings of disk radius:
zs = s.r*exp(1i*s.ph); % ship position as x + iy
S(L.i) = S(L.i)+exp(-abs(L.c-zs).^2/.2); % L.c: disk point of each pixel
b = max(0,1-((L.r-s.fc)./s.fw).^2); % flare rings by radius
When the ship passes behind the hole, its image smears into arcs above and below the shadow. No extra code does that. The engine exhaust from each tap is drawn the same way, so it bends too.
Storing disk points as complex numbers kept the distance check to one short line.
3. Real physics needed a real gauge
The orbit uses the Schwarzschild radial equation, so the innermost stable orbit at r = 3 is real: below it, no orbit is stable and the ship slides inward. Time dilation sets the score. A circular orbit's clock runs at sqrt(1 - 1.5/r) of a distant clock, so Earth gains the rest:
s.vr = s.vr+(-.5/s.r^2+s.L^2/s.r^3-1.5*s.L^2/s.r^4-.04*s.vr)*T;
s.yrs = s.yrs+10*h*s.m*(1-sqrt(max(0,1-1.5/s.r)));
The physics made two first designs fail:
- Head-on debris didn't work. Moving up or down is slower than going around the hole, so you met debris before a burn could lift you clear. Climbing one unit took about 3 s even tapping 5 times a second. I replaced debris with flares that warn for 3.5 s, and I sped up game time 1.6 times.
- A beautiful view isn't a readable one. In my first playtest, I couldn't tell what a tap did, because the lensed ship jumps around the screen. A simple height gauge on the left fixed that. Tapping moves your bar up, red bands are flares, and green bands are bonuses. The black hole is the show, and the gauge is the controller.
After that came the parts that made it fun: a combo multiplier for staying deep, stages every 100 years with faster and drifting flares, and a close-call bonus for clearing a flare by a hair.4. Small tricks that saved characters
The final file counts 9,993 of 10,000 characters. The counter reformats your code first, so comments are free but spaces and indentation count, as I described in my first post. These helped:
- Divide by zero to hide things. 0/0 is NaN, and graphics skip NaN points, so one expression both positions and hides a marker:G.gs.YData = [1 1]*(100+60*(s.r-1))+0/(s.mode == 1);
- Make several texts in one call. text takes vectors and a cell array of strings:text(ax,[103 108 50 50],[220 280 88 502],{'ISCO','COMBO','HORIZON','HEIGHT'},f{:});
- Store end times, not countdowns. A message that shows until s.t < s.got needs no line to count it down each frame.
- Write constants out when they're fixed. My camera never moves, so its right and up vectors became constants instead of cross products.
One trim I had to undo: dropping a normalization in the star placement put stars inside the black hole's shadow. Look at the frames after every trim.Play it
If MATLAB Online is slow for you, run it in desktop MATLAB: download the starter project, copy the entry's code into game.m, and run minihackContest.play.
How many years into the future can you get?
A huge thank you to everyone who participated in the MATLAB STEM Showcase!
What makes these contributions especially meaningful is that their impact doesn’t end with the contest. Your work can continue to help students, educators, engineers, scientists, and curious learners explore STEM concepts for years to come.
And now, it’s time to celebrate our winners!
🥇 STEM Domain Awards
Congratulations to our STEM Domain Award winners. Each of you will receive a $50 Amazon gift card.
AI & Data Science:
@Yiheng for Inside the VAE
Physics:
Mathematics:
Engineering:
Life Sciences:
Earth & Climate Science:
🎁 Weekly Prize Winners
Congratulations as well to all of our Weekly Prize winners! You will receive a MathWorks T-shirt or a pair of socks.
@Anshika, @Jan Studnicka, @Michelle, @Abhishek, @Dr. Mishaal A. AbdulKareem, @Harshad, @KARUPPASAMYPANDIYAN M, @Umar, @Heze Chen, @Jamil Kasan, @Jorge Paloschi, @Pauli Huusari, @Rodolfo
Congratulations to all our winners, and thank you again to everyone who participated!
We hope you’ll continue creating, exploring, and sharing interactive STEM experiences with the MATLAB community.