Production Exercises
Production work is full of small calculations and checks that are easy to get subtly wrong. Each exercise below is one of them, as a pure function with the tests already written. Run the starter first: it prints wrong answers (None, zeros), which shows what the tests expect. Complete the code marked TODO until the output matches the expected output, then compare with the solution.
Exercise 1: Texture memory with mipmaps
Topics: UVs & Texture Memory
Return the bytes a texture uses with a full mip chain: add the size of each level (width × height × bytes per pixel), halving width and height (minimum 1) until the 1×1 level is included.
def texture_bytes(width, height, bytes_per_pixel):
# TODO: sum every mip level down to 1x1
return 0
print(texture_bytes(4, 4, 4)) # 64 + 16 + 4
print(texture_bytes(8, 2, 1)) # 16 + 4 + 2 + 1
print(round(texture_bytes(1024, 1024, 1) / 1024 / 1024, 3))0
0
0.0
Expected output:
84
23
1.333Show solution
def texture_bytes(width, height, bytes_per_pixel):
total = 0
while True:
total += width * height * bytes_per_pixel
if width == 1 and height == 1:
return total
width, height = max(width // 2, 1), max(height // 2, 1)Exercise 2: Bump a version
Topics: Version & Build Numbers
Write bump(version, part) for MAJOR.MINOR.PATCH versions, where part is "major", "minor" or "patch". Bumping a part resets the parts to its right to zero, and any pre-release suffix (-beta.2) is dropped.
def bump(version, part):
# TODO: split off any "-..." suffix, bump the part, reset the lower parts
return None
print(bump("1.4.2", "patch"))
print(bump("1.4.2", "minor"))
print(bump("1.4.2", "major"))
print(bump("2.0.0-beta.3", "patch"))None
None
None
None
Expected output:
1.4.3
1.5.0
2.0.0
2.0.1Show solution
def bump(version, part):
major, minor, patch = map(int, version.split("-")[0].split("."))
if part == "major":
return f"{major + 1}.0.0"
if part == "minor":
return f"{major}.{minor + 1}.0"
return f"{major}.{minor}.{patch + 1}"(Semver itself would turn 2.0.0-beta.3 into 2.0.0 on release; here a patch bump is asked for explicitly.)
Exercise 3: Crash signatures
Topics: Crash Reporting
Write signature(trace) that returns "<ExceptionType>|<frame>|<frame>" using the exception type (text before the first : on the first line) and the first two frames of game code: lines starting with at , method name only (the text up to the first space or (), skipping frames that start with UnityEngine. or System..
def signature(trace):
# TODO
return None
a = """NullReferenceException: Object reference not set
at System.Linq.Enumerable.First (IEnumerable source)
at Inventory.Equip (Item item) in Inventory.cs:212
at InventoryUI.OnSlotClicked (int slot) in InventoryUI.cs:88
at UnityEngine.Events.InvokableCall.Invoke ()"""
b = """NullReferenceException: Object reference not set
at Inventory.Equip (Item item) in Inventory.cs:219
at InventoryUI.OnSlotClicked (int slot) in InventoryUI.cs:90"""
print(signature(a))
print(signature(a) == signature(b))None
True
Expected output:
NullReferenceException|Inventory.Equip|InventoryUI.OnSlotClicked
TrueShow solution
import re
def signature(trace):
lines = trace.strip().splitlines()
exc = lines[0].split(":")[0]
frames = []
for line in lines[1:]:
line = line.strip()
if not line.startswith("at "):
continue
method = re.split(r"[ (]", line[3:], maxsplit=1)[0]
if not method.startswith(("UnityEngine.", "System.")):
frames.append(method)
return "|".join([exc] + frames[:2])Exercise 4: Subtitle display time
Topics: Accessibility Basics
Return how long a subtitle must stay on screen: the text length divided by the maximum characters per second, but never less than min_seconds. Round to one decimal.
def display_time(text, max_cps=17, min_seconds=1.5):
# TODO
return 0.0
print(display_time("Run!"))
print(display_time("Stay close. The bridge won't hold both of us."))
print(display_time("x" * 85, max_cps=20))0.0
0.0
0.0
Expected output:
1.5
2.6
4.2Show solution
def display_time(text, max_cps=17, min_seconds=1.5):
return round(max(len(text) / max_cps, min_seconds), 1)(85 / 20 = 4.25, and Python's round uses round-half-to-even on the exact binary value, which gives 4.2 here.)
Exercise 5: Which files miss the LFS rules?
Topics: Git LFS & .gitattributes
Given LFS patterns that are only file extensions (*.png) and a list of paths, return the paths whose extension is a binary type (from binary_exts) but which no pattern matches. Matching is case-sensitive, as on Linux.
def missing_lfs(patterns, binary_exts, paths):
# TODO
return []
patterns = ["*.png", "*.wav", "*.fbx"]
binary_exts = {".png", ".wav", ".fbx", ".psd", ".ogg"}
paths = ["Art/hero.png", "Art/Hero.PNG", "Audio/jump.wav", "Art/key_art.psd",
"Audio/music.ogg", "src/player.cs", "Models/tree.fbx"]
print(missing_lfs(patterns, binary_exts, paths))[]
Expected output:
['Art/Hero.PNG', 'Art/key_art.psd', 'Audio/music.ogg']Show solution
def missing_lfs(patterns, binary_exts, paths):
tracked = {p[1:] for p in patterns} # "*.png" -> ".png"
result = []
for path in paths:
ext = path[path.rfind("."):]
if ext.lower() in binary_exts and ext not in tracked:
result.append(path)
return resultHero.PNG is a binary type (checked case-insensitively) but escapes the case-sensitive LFS rule.
Exercise 6: Pick a GIF frame rate
Topics: Screenshots, GIFs & Trailers
GIF delays are whole hundredths of a second, and delays of 0 or 1 are shown as 10 by most browsers. Return the highest frame rate not above max_fps that a GIF can play exactly (100 divided by a whole delay of at least 2).
def best_gif_fps(max_fps):
# TODO: try delays 2, 3, 4, ... and return 100 / delay for the first exact fit
return None
for target in (60, 30, 24, 12):
print(target, "->", best_gif_fps(target))60 -> None
30 -> None
24 -> None
12 -> None
Expected output:
60 -> 50
30 -> 25
24 -> 20
12 -> 10Show solution
def best_gif_fps(max_fps):
delay = 2
while True:
fps = 100 / delay
if fps <= max_fps and 100 % delay == 0:
return int(fps)
delay += 1Only delays that divide 100 give a whole frame rate: 2 (50 fps), 4 (25), 5 (20), 10 (10)…
Test yourself
Why are most production checks written as pure functions over data (manifests, logs, listings)?
- Python requires it
- They can be tested anywhere, including CI, without the engine, Blender or a store
- They run faster on GPUs
- Stores provide them
In Exercise 5, why does Art/Hero.PNG escape the *.png rule?
- PNG isn't binary
- Pattern matching is case-sensitive on Linux, so
*.pngdoesn't match.PNG - It's in the wrong folder
- LFS ignores uppercase