Embedded Swift

Flappy Swift

Building a working arcade clone in under 500 lines of Swift, with one accelerometer and a 128×64 OLED.

[ Gameplay clip ]

The Swift bird is twenty-four pixels by twenty-four pixels. It flies sideways across a monochrome OLED display, which is the entire game. Vertical bars scroll in from the right with random gaps. Tilt the board left or right and the bird drifts up or down. Hit a bar and the screen goes black.

The whole thing is around 450 lines of Swift on top of the wrappers I had already written for the previous project. It runs at 30 frames per second on a chip that costs less than lunch.

"Pong came together in an evening. Flappy took two. The hard part was not the game. The hard part was the law of exclusivity, which I had never thought about before."

The compromise that surprised me

The natural way to update a list of obstacles is to call a method that takes one obstacle by inout. Swift's law of exclusivity says: while you are inside that method, you have exclusive access to the obstacle. Fine.

Embedded Swift uses tuples instead of arrays. When you call a mutating method on the struct and pass &obstacles.0, you are mutating self twice at the same time. The compiler rejects it. Which is correct. I just had not seen it phrased that way before, because on iOS you almost never index a tuple in a hot loop.

The fix is to either copy the value, mutate the copy, write it back, or to make the method a free function that does not touch self at all. Both are clean. I picked the second one because it read better.

What the chip can actually do

The frame rate held steady at 30 FPS for the whole game. The framebuffer push over I²C is the slowest thing in the loop, and it takes about ten milliseconds. The accelerometer read takes under one millisecond. The game logic takes less than one millisecond. There was room to do much more.

Which is mostly the point of this post. The chip is more capable than you expect. The constraints are real and they reshape how you write code, but they do not stop you from building real things.

Hardware

  • XIAO ESP32-C6 (Seeed Studio)
  • Grove Base for XIAO
  • Grove OLED 0.96" (SSD1315)
  • Grove 6-Axis Accelerometer & Gyroscope (LSM6DS3)

Code

[Repository link will be added on publish.]