juno.game¶
Capture and drive a pygame game window from Juno.
pygame draws into a real, full-screen game window. This module is the small amount of glue around it that a notebook, a script or the interactive prompt actually wants:
snapshot()puts the current picture into your output, so a game leaves something behind after the window closes.canvas()is awithblock that always shuts the window down and leaves a picture, even when the code inside it raises.run()is a minimal game loop for the common case — draw a frame, handle events, repeat.is_active()answers whether the window is still on screen.controls()picks which on-screen controls the window shows — a direction pad and SPACE, the pad on its own, a full gamepad, or none at all.orientation()opens the window the way round the game is played, landscape or portrait, without opening it twice to get there.full_bleed()hands the picture the whole screen, hardware and all, andsafe_area()says how far the hardware reaches in, so the score and the buttons stay clear of it.
Only one game window is open at a time, and pygame.display is how
you draw into it: set_mode() opens it and flip() updates it.
Typical usage:
import pygame
from juno import game
with game.canvas():
screen = pygame.display.set_mode((320, 240))
pygame.draw.circle(screen, "tomato", (160, 120), 60)
pygame.display.flip()
In a notebook, snapshot() renders inline in the cell’s output. In a
script or at the prompt it opens the preview, the same way images and
plots do.
- exception juno.game.GameError¶
Bases:
ExceptionRaised when there is nothing to capture, or it cannot be encoded.
- exception juno.game.GameWindowClosed¶
Bases:
SystemExitRaised when the game window was closed and the loop kept drawing.
Catch it to end a loop cleanly. It is deliberately not an
Exceptionsubclass, so theexcept Exceptionin a tutorial loop does not swallow the very thing that is trying to stop it, whiletry/finallyblocks andwithstatements still run their cleanup.
- juno.game.canvas(capture=True)¶
Run a game inside a
withblock that always cleans up after it.Whatever happens inside — a clean finish, an error, or the window being closed — the block captures the last frame into the output and shuts pygame down on the way out. Without it, a cell that raises part-way through a game leaves a window on screen and no record of what it drew.
Closing the window is treated as a normal ending rather than an error, so a loop that keeps drawing after the window is gone still leaves the block cleanly, with its last frame captured.
Typical usage:
import pygame from juno import game with game.canvas(): screen = pygame.display.set_mode((320, 240)) screen.fill("navy") pygame.display.flip()
- Parameters:
capture (bool) – Whether to capture a picture on the way out. Pass
Falsefor a game that already callssnapshot()itself.- Yields:
None. The block is used for its cleanup, not for a value.
- Raises:
GameError – If the block finished normally but the closing picture could not be taken. A block that ends any other way — an error inside it, or the window being closed — keeps its own ending and stays quiet about the picture.
- juno.game.controls(layout=_UNSET)¶
Choose which on-screen controls the game window shows.
Four answers are available:
"arrows"— a direction pad and a SPACE key. This is what a window shows unless a program asks for something else."dpad"— the direction pad alone, with nothing beside it. For a program that reads the arrow keys and nothing else, where the key beside the pad is a button that does nothing when pressed."gamepad"— a direction pad, round B and A buttons, and SELECT, START and MENU: the shape an 8-bit console game is played with, plus a MENU key for a game that has a menu of its own to open — an emulator’s ROM picker, a pause screen."none"— no controls at all, and the whole window for the picture. For a game played by touching what is on screen, where a pad would cover the board without being any use.
"none"takes away the controls a game is played with: the direction pad and the keys beside it. It never touches the window’s own buttons along the top — closing the window, its sound, and the button that shows the controls again are always there — and if the layout has a MENU key it leaves that too, since it is a way back to a game’s own menu rather than part of the pad.MENU is always there in
"gamepad", and a game that does not readpygame.K_MENUis not disturbed by it: pressing it sends a key nothing is listening for, and nothing happens. No game binds that key by tradition, so it never collides with the controls a game already uses.With no argument it answers what the window is showing. With a name it chooses: called before
pygame.display.set_mode()the choice is remembered and used when the window opens — which is where a touch-only game asks for"none", so its window never shows a pad at all — and called while your own window is on screen it takes effect immediately, so a program that runs several games can pick what each one needs. Naming a layout brings back controls your program put away with"none".The person playing has the last word, and it is final: once they have used the button at the top of the window, the controls stay as they left them for the rest of that game, whatever a program asks for afterwards. So they can always bring the controls back — and a program cannot take away controls they asked to see. While the controls are off screen, for any reason,
controls()answers"none".The choice belongs to one window. The next one starts from
"arrows"again unless it asks too.Every control sends the key a keyboard would, so a game reads them with
pygame.keyand nothing else: the pad sends the arrow keys, SPACE sends space, B, A, SELECT and START send Z, X, right shift and return — the keys emulators are traditionally played with — and MENU sends the menu key (pygame.K_MENU).Typical usage:
from juno import game game.controls("gamepad")
- Parameters:
layout (str) – What to show —
"arrows","dpad","gamepad"or"none". Leave it out to ask what is showing.- Returns:
What the window is showing, when called with no argument;
Nonewhen called to choose.- Raises:
TypeError – If
layoutis not a string. Leave the argument out to ask the question — passingNoneis not how to ask it, and it is not the same as the string"none".ValueError – If
layoutis not one of the four names.
- Return type:
str | None
- juno.game.full_bleed(enabled=_UNSET)¶
Give the picture the whole screen, hardware and all.
A phone’s screen has parts of the phone itself in it — the camera housing across the top, the rounded corners, the bar along the bottom the home gesture uses. Normally the canvas stops short of all of them, so everything a game draws is somewhere it can be seen and touched.
Ask for full bleed and the canvas covers the screen instead, corner to corner, with the housing and the bar sitting over the picture. That is what a sky, a landscape or a photograph wants — a band of background down each edge is exactly what gives a game away as a small picture on a big screen. Then ask
safe_area()how far in the hardware reaches, and keep the score, the buttons and anything else meant to be read or pressed inside what it leaves.Ask before
pygame.display.set_mode(), so the window opens with the bigger canvas rather than growing into it.Typical usage:
from juno import game game.full_bleed(True) screen = pygame.display.set_mode((0, 0))
The choice belongs to one window. The next one starts without full bleed again unless it asks too.
- Parameters:
enabled (bool) –
Truefor the whole screen,Falsefor a canvas that stays clear of the hardware. Leave it out to ask which has been asked for.- Returns:
Whether full bleed is asked for, when called with no argument;
Nonewhen called to choose.- Raises:
TypeError – If
enabledis notTrueorFalse. Leave the argument out to ask the question.- Return type:
bool | None
- juno.game.is_active()¶
Whether this session’s game window is open and on screen.
Returns
Falsebefore the firstpygame.display.set_mode(), and after the window has been closed — including when it was closed with the Close button while a loop was still drawing. Useful as a loop condition when you would rather end quietly than handleGameWindowClosed.- Returns:
True while this session’s window is showing, False otherwise.
- Return type:
- juno.game.orientation(value=_UNSET)¶
Choose which way round the next game window opens.
Three answers are available:
"landscape"— the window opens the wide way round, however the phone is being held. For a game that needs the width: a card table, a racing track, a side-scroller."portrait"— the window opens the tall way round, for a game that needs the height."any"— whichever way the phone is already being held, which is what a window does unless a program asks for something else. If the program asksset_mode()for a canvas of a particular shape, the window opens the way round that shape fits best.
Ask before
pygame.display.set_mode()and the window opens that way round, with a canvas already that shape — so a game that wants the width never has to open its window, measure it, and open it a second time with the numbers the other way round.Typical usage:
from juno import game game.orientation("landscape") screen = pygame.display.set_mode((0, 0))
On an iPad this makes no difference: the window there follows the way the iPad is held, whatever a program asks for.
The choice belongs to one window. The next one starts from
"any"again unless it asks too.- Parameters:
value (str) – Which way round to open —
"landscape","portrait"or"any". Leave it out to ask what has been asked for.- Returns:
What is currently asked for, when called with no argument —
"any"when nothing is;Nonewhen called to choose.- Raises:
TypeError – If
valueis not a string. Leave the argument out to ask the question — passingNoneis not how to ask it.ValueError – If
valueis not one of the three names.
- Return type:
str | None
- juno.game.run(surface, update_fn, frames=None, events=None)¶
Drive a simple game loop and return when it ends.
Each pass reads the pending input, calls
update_fnto draw one frame, shows it, and waits for the next frame. The loop ends when the window is closed, whenupdate_fnreturnsFalse, or whenframesframes have been drawn.This is deliberately the simple case. Anything with its own timing, fixed time steps or multiple scenes wants a hand-written
while running:loop — this exists so a first program does not have to start with one.- Parameters:
surface (Any) – The surface to draw into — normally what
pygame.display.set_mode()returned.update_fn (Callable[[Any], Any]) – Called once per frame as
update_fn(surface)to draw the frame. ReturnFalseto end the loop; any other return value (includingNone) continues it.frames (int | None) – Stop after this many frames.
None(the default) runs until the window is closed orupdate_fnreturnsFalse.events (Callable[[Any], Any] | None) – Optional callback invoked as
events(event)for each pending input event, before the frame is drawn. A window-close event always ends the loop, whether or not this is supplied.
- Returns:
The number of frames drawn.
- Raises:
TypeError – If
update_fnoreventsis not callable.ImportError – If pygame is not installed.
- Return type:
- juno.game.safe_area()¶
How far the screen’s own hardware reaches into the canvas.
Four numbers — left, top, right, bottom — in the canvas’s own pixels, the ones
set_mode()handed back, measuring the strip along each edge that the camera housing, the rounded corners and the home bar can cover. A canvas of your own size is scaled onto the screen, and these numbers come back in the canvas’s scale rather than the screen’s: on a phone whose housing is 177 screen pixels deep, a 393 × 852 canvas is told 59. Lay the score and the buttons out inside what they leave and nothing a player has to read or press ends up behind the phone; the sky, the ground and the rest of the picture can carry on underneath, which is the whole point offull_bleed().Without full bleed the canvas already stops clear of the top and the sides, so the only edge with anything to declare is the bottom one, where the home bar sits over the picture.
Typical usage:
from juno import game left, top, right, bottom = game.safe_area() screen.blit(score, (left + 16, top + 16))
Ask once the window is open, and lay the words out from what it says. The numbers describe this canvas, and this canvas keeps the size it opened with: turning the phone does not resize it, and a game that wants a different one asks
set_mode()for it. Where there is no Juno window to measure — the same program run on a desktop — every edge is 0.The answer is PROVISIONAL until the window is really up. Asked before there is one it is a best guess — the window does not exist yet, and on a phone that is about to turn, the strip along the bottom edge is measured the way the screen is being held now — and the window does not appear the instant the first frame is drawn either: it is put up for you a moment later. So a program that reads early should read AGAIN once it is drawing, and lay its words out from that; a loop that asks every few seconds costs nothing and always has the measurement.
Examples/Games/Flappyre-reads on a timer for exactly this reason.
- juno.game.snapshot(surface=None)¶
Show what a surface currently contains.
In a notebook the picture appears inline in the cell’s output; in a script or at the prompt it opens in the preview. Call it whenever you want a game to leave a visible result behind — after the last frame, or from inside a loop to capture a particular moment.
- Parameters:
surface (Any | None) – The surface to capture. Defaults to this notebook’s own game window surface (what its
pygame.display.set_mode()returned), which is what a game draws into.- Raises:
GameError – If this notebook has no game window to capture (it has not called
pygame.display.set_mode(), and no surface was passed), or if the picture could not be encoded.ImportError – If pygame is not installed.
- Return type:
None