AWS Builder Center
My Halloween Game Was a Python File. Now It’s on CloudFront.

My Halloween Game Was a Python File. Now It’s on CloudFront.

A 1,909-line pygame shooter, five changed lines and one CloudFormation template. Deploy it to your own AWS account in five minutes, no server needed.

Cloud Architect
Spookies main menu with six Halloween characters The Spookies menu. Every character, the moon and the haunted house are drawn by code, not loaded from image files.
I had a Halloween game. Pumpkins, ghosts, zombies and a vampire running around a dark arena, shooting each other with shotguns and a pumpkin launcher. It ran beautifully on my laptop.
Then I wanted to send it to friends, and I hit the oldest problem in software: "First install Python, then run  pip install pygame , then…" Nobody does that two days before Halloween.
So the goal was simple. Turn one Python file into one link. Keep the game as it is, run it in any browser, host it on AWS, and pay nothing for it.
TL;DR
  • 1,909 lines of Python, zero asset files. Every sprite and every sound effect is generated in code.
  • 5 lines changed to run it in a browser. Four of them exist because of one rule: the browser does not let your loop run forever.
  • The packaged game is 22 KB. The Python runtime the browser downloads is ⟦X MB⟧, and that is what decides your first load time.
  • Hosting: a private S3 bucket behind CloudFront with Origin Access Control. HTTPS, global caching, no public bucket.
  • Cost: inside CloudFront's always-free tier of 1 TB and 10 million requests per month.
  • Deploy it to your own account with one CloudFormation template and one command. Remove it with another.

The game

Spookies is an arena shooter for one or two players on the same keyboard, filled up with CPU monsters to six characters in total. You grab weapons (pistol, shotgun, SMG, pumpkin launcher), hide behind tombstones and race to the kill limit before the clock runs out.
I built it with an AI coding assistant, and that shaped one detail that turned out to matter a lot later: there are no image or sound files at all. Characters are drawn at three times their size and scaled down for smooth edges, and every sound is synthesized from waveforms when the game starts. One file is the whole game.
Spookies gameplay in a graveyard arena A round in progress: six characters, tombstones, candles and a kill feed in the corner.

Top-down view of a dark graveyard arena with cobblestone paths, tombstones and glowing jack-o’-lante


Why not a server?

My first instinct as a cloud architect was the wrong one: "Where does it run?" An EC2 instance streaming the game window to a browser would work, and it would cost money every hour, add latency to every keypress and need someone to patch it.
A game loop does not need a server. It needs a CPU near the player, and every player already has one. The only real question was how to get Python into the browser.

Option
What it means
Why not
EC2 + screen streaming
Run the desktop game, stream the window
Pay per hour, input lag, a server to patch
Rewrite in JavaScript
Port 1,909 lines to Phaser or plain canvas
Days of work two days before Halloween
Python in WebAssembly
Run the same file in the browser
Chosen
The tool that makes the third option possible is pygbag. It packages your game and pairs it with CPython and pygame-ce compiled to WebAssembly, so the browser runs the real Python interpreter and your real code. Nothing is translated into JavaScript.

The freeze

The first browser build loaded, showed the menu for a moment and then froze the whole tab.
Every pygame game has the same heart:
while True:
handle_input()
update()
draw()

On a desktop, this loop owns the process. It runs forever and the operating system handles everything else in parallel.
A browser tab works differently. It has one main thread, and that thread also has to paint the screen, read the keyboard and play audio. If your code never lets go of it, nothing else ever happens. Your game is technically running at full speed, and the player sees a frozen picture.
The fix is to let go once per frame:
async def main(): # was: def main()
...
while True:
...
pygame.display.flip()
await asyncio.sleep(0) # hand the frame back to the browser

asyncio.run(main()) # was: main()
 asyncio.sleep(0)  does not wait. It tells the browser "your turn", the browser paints the frame and reads the keys, and the loop continues. The pygbag documentation calls this line "very important" and asks you to keep the value at zero.
That is the lesson I took away from this project:
The browser doesn't run your game loop. It lends you one frame at a time.
The fifth changed line was smaller. In the menu, ESC called  sys.exit() , which makes sense on a desktop and means nothing in a browser tab. It now only quits when the game is not running on WebAssembly:
elif k == pygame.K_ESCAPE and sys.platform != "emscripten":


The architecture


Architecture diagram in three lanes. Reader lane: AWS CloudShell builds main.py with pygbag. Step 1

Spookies architecture on AWS Five steps from a Python file to a playable link. The S3 bucket stays private; only CloudFront can read it.
Follow the numbers in the diagram:
  1. In AWS CloudShell,  deploy.sh  builds the game with pygbag and deploys a CloudFormation stack.
  1. The same script uploads the build (an  index.html  and the 22 KB game package) to the bucket with  aws s3 sync .
  1. A player opens the CloudFront URL and the browser downloads the page and the game over HTTPS.
  1. On a cache miss, CloudFront fetches the files from S3 with a signed request.
  1. The browser loads the Python and pygame runtime and starts the game. From here on, everything runs on the player's machine.
The build produces a small static website, and static files on AWS have a well-known home:
  • Amazon S3 stores the files in a bucket that is not public. Block Public Access stays on.
  • Amazon CloudFront serves them over HTTPS from edge locations close to the player, compressed and cached.
  • Origin Access Control (OAC) lets CloudFront sign its requests to S3. The bucket policy allows reads from exactly one principal: this one distribution.
There is no "make bucket public" step anywhere. If someone finds the bucket name, they get access denied. The only way to the game is through CloudFront.

Deploy it to your own AWS account

You do not have to take my word for any of this. The whole setup is one CloudFormation template, and the code is on GitHub: ⟦GitHub repo URL⟧
Open AWS CloudShell in the console (the  >_  icon in the top bar), pick any Region, and run:

git clone https://github.com/romanceresnak/spookies-aws spookies && cd spookies
./deploy.sh

The script does four things: builds the browser version with pygbag, deploys the CloudFormation stack, uploads the game to the bucket and refreshes the CloudFront cache. At the end it prints  Play here: https://xxxx.cloudfront.net . The first run takes about five minutes, most of it CloudFront going live worldwide. Nothing has to be installed on your laptop.
This is the template it deploys. Four resources, no Lambda, no EC2:
AWSTemplateFormatVersion: "2010-09-09"
Description: Spookies - pygame in the browser. Private S3 + CloudFront with OAC.

Resources:
GameBucket: # private: Block Public Access ON
Type: AWS::S3::Bucket
Properties:
PublicAccessBlockConfiguration:
BlockPublicAcls: true
BlockPublicPolicy: true
IgnorePublicAcls: true
RestrictPublicBuckets: true
OwnershipControls:
Rules:
- ObjectOwnership: BucketOwnerEnforced
BucketEncryption:
ServerSideEncryptionConfiguration:
- ServerSideEncryptionByDefault:
SSEAlgorithm: AES256

OriginAccessControl: # CloudFront signs every request to S3
Type: AWS::CloudFront::OriginAccessControl
Properties:
OriginAccessControlConfig:
Name: !Sub "${AWS::StackName}-oac"
OriginAccessControlOriginType: s3
SigningBehavior: always
SigningProtocol: sigv4

Distribution:
Type: AWS::CloudFront::Distribution
Properties:
DistributionConfig:
Enabled: true
DefaultRootObject: index.html
HttpVersion: http2and3
PriceClass: PriceClass_100
Origins:
- Id: GameBucketOrigin
DomainName: !GetAtt GameBucket.RegionalDomainName
OriginAccessControlId: !GetAtt OriginAccessControl.Id
S3OriginConfig:
OriginAccessIdentity: ""
DefaultCacheBehavior:
TargetOriginId: GameBucketOrigin
ViewerProtocolPolicy: redirect-to-https
CachePolicyId: 658327ea-f89d-4fab-a63d-7e88639e58f6 # managed CachingOptimized
Compress: true
AllowedMethods: [GET, HEAD]

GameBucketPolicy: # only this one distribution may read
Type: AWS::S3::BucketPolicy
Properties:
Bucket: !Ref GameBucket
PolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal: { Service: cloudfront.amazonaws.com }
Action: s3:GetObject
Resource: !Sub "${GameBucket.Arn}/*"
Condition:
StringEquals:
AWS:SourceArn: !Sub "arn:${AWS::Partition}:cloudfront::${AWS::AccountId}:distribution/${Distribution}"

Outputs:
BucketName: { Value: !Ref GameBucket }
DistributionId: { Value: !Ref Distribution }
GameUrl: { Value: !Sub "https://${Distribution.DomainName}" }

The line worth a second look is the  Condition  at the end. The bucket does not trust "CloudFront" in general. It trusts one distribution ARN in your account. Another distribution, even yours, gets access denied.
Why are the files uploaded by a script and not by CloudFormation? Because CloudFormation describes infrastructure, not content. The stack creates the empty house,  aws s3 sync  moves the furniture in, and you can redeploy a new version of the game in seconds without touching the stack.
When you are done:
./teardown.sh

The surprising number is the first one in the middle. My game is 22 KB. The first visit downloads ⟦X⟧ times more than that, because the browser needs the Python interpreter and pygame before it can run a single line of my code. The game itself is a rounding error. If you want a faster first load, the runtime is the thing to optimize, not your code.

What I would tell you before you try this

The runtime comes from a third party. By default the page loads the Python runtime from pygame-web's CDN on GitHub Pages, not from my bucket. For a Halloween game that is fine. For anything serious I would copy the runtime files into the same bucket so the whole page depends only on my own CloudFront distribution.
WebAssembly is slower than native. My game draws a frame in about 5 ms on the desktop, so it has headroom. A game that already struggles at 60 FPS on your laptop will struggle more in a browser.
Sound needs a click. Browsers block audio until the player interacts with the page, so the game starts after the first click on the page. That is a browser rule, not a bug.
Keyboards only. Two players share one keyboard. On a phone there is nothing to press, and I did not build touch controls.

What it costs

S3 stores a few hundred kilobytes, which costs fractions of a cent per month. CloudFront's always-free tier includes 1 TB of data transfer out and 10 million HTTPS requests every month. Even if every visitor downloads the whole runtime, that covers a lot of Halloween parties.

The one thing to remember

Moving a Python game to the web did not need a server, a rewrite or a framework. It needed one change in how I thought about the loop.
The browser doesn't run your game loop. It lends you one frame at a time.
Deploy it, play a round with the pumpkin launcher, and tell me in the comments: what old Python script is sitting on your laptop that deserves a URL?

Sources

  1. pygbag – Python WebAssembly for everyone (PyPI):  https://pypi.org/project/pygbag/ 
  1. pygbag source and documentation:  https://github.com/pygame-web/pygbag 
  1. Amazon CloudFront – Restricting access to an Amazon S3 origin (Origin Access Control):  https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-restricting-access-to-s3.html 
  1. Amazon CloudFront pricing – always free tier:  https://aws.amazon.com/cloudfront/pricing/pay-as-you-go 
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article