Upload
richard-donkin
View
53.031
Download
3
Embed Size (px)
DESCRIPTION
A short walkthrough of some of the code from an impressive 500 line Python game - a simple version of Minecraft, using the Pyglet 3D library. Links to resources for Pyglet and Python gaming generally.
Citation preview
Minecraft in 500 lines of Python
Richard Donkin@rdonkin
cloudfindhq.com
github.com/fogleman/MinecraftEarly version:
http://xkcd.com/353/
Why Python?Easy to write
Great community
Fast enough Can use compilers (Cython etc) or JIT (PyPy)Or use a spare GPU …
Libraries, broad usage
Raspberry Pi to scientific computing to cloud apps
http://xkcd.com/353/
Pyglet3D gaming library - pyglet.org
Simple to learnDoesn’t mandate program structureWraps OpenGLCan use py2exe / py2app
This is a quick Minecraft code walkthrough, not a tutorial
Tutorial based on Asteroids: steveasleep.com
Minecraft Essentials
Objects are blocks, in 3D grid
OperationsMove: W, S, A, D – and Tab to flyMouse to look (or fly)Mouse to add or remove blocks
Textures
OverviewWindow class
Subclass of Pyglet window classUser interaction, movement, rendering
Model classModels the world as blocks in 3D grid
Dictionary world[position]
where position is tuple (x, y, z)Contains texture such as
Window & Startup Code
Model
Look around
X axis is horizontal (look left/right)
Y axis is vertical (look up/down) – max ±90°
Only motion matters, not absolute position
Python tuple assignment
Building stuff
Mouse locking, sight vector
Hit testing, block add/remove
Adding a Block
Remove any existing block at (x, y, z) position from the ‘world dictionary’
Set texture for this block at position
Create or update sector (16x16 2D grid) in which this block resides – enables speedup by only rendering some sectors
Show the block, and check if any neighbours now visible
Highlighting ‘target block’
Hit-test from player position to target block
Draw line around visible edges of block, using Pyglet
1100 commits later…
github.com/boskee/Minecraft
Major fork
8,000 lines
19 contributors
Multi-player
Optionally, compile to C via Cython
Pyglet and More2D game toolkits:
Cocos2D: http://cocos2d.org/ - uses PygletFife: http://www.fifengine.net/ - esp. RTSs and RPGs
Add-on libraries that can work with Pyglet:Rabbyt – sprites: http://arcticpaint.com/projects/rabbyt/ Pymunk – physics: http://pymunk.org
Alternative frameworks:Pygame – larger community, more game-specific, open source book at http://inventwithpython.com/
Summary
Concise, elegant code
Choose the right framework
Small games to get started
Write your own!Try pyweek.org challenges
Thank YouRichard Donkin
@rdonkin cloudfindhq.com
Sect0rization
Technique used to speed up rendering of world – only render nearby sectors
Sector = 16x16 2D region of world In Model, dictionary sectors[sector] maps from sector to list of positions in that sectorTrack player position in sectorIf player moves between sectors, determine which adjacent sectors to show – see change_sectors()