programming course. I. SOFT .... in classes, which are documented in Flash help [16] (on. 5.02.2011) plus .... around all three coordinate edges) and Adobe has.
A Game Programming Course J. Henno* , H. Jaakkola ** and P. Linna** * Tallinn University of Technology, Tallinn, Estonia ** Tampere University of Technology, Pori, Finland Abstract – Game programming is the easiest way for students to start their own independent business. Game Programming requires besides programming skills also lot of math and physics. Balls and bullets fly, collide with other game objects, cars race and skid on street corners (often surpassing the real world laws), rockets are fired, lot of explosions (the more the merrier!) – all this is described in the game program using math and physics laws, vectors and matrices. More and more of game content is created procedurally. And everything should look cool on screen, appear quickly. In a game program there is no place e.g. to start solving differential equations, therefore in games are often used approximate methods which differ from traditional ones. This all should be taught in a game programming course.
I. SOFT INTRODUCTION TO HARD SCIENCE Game programming is attractive for students, here the threshold to start your own independent business is very low - many students earn money as indie game developers. Digital distribution allows independent (indie) game developers self-publish, and this has created a new wave of independence and creativity in the industry. Lately there have appeared several sites ([ 1] 140 million active users, 40000 publishers; [ ],[3],[4] etc) which publish games from independent (indie) developers, thus they can manage without financial support from video game publishers. Many programmers like to create games on their free time, even if they work for hire. They see programming a game in the same way as an artist sees painting or a musician thinks of music – it is not a job, but something inside them that needs to be expressed. But in order to be successful in this very competitive area one should know the technology: how to make objects move, bounce, rotate, how to create 2D/2.5D/ 3D projection of your virtual game world on screen, how to handle memory, network etc. Some of the best games fro m recent years (Spore, Spelunki [ 5], Minecraft [ 6], Canabalt [7] etc) are procedurally generated [8],[9],[ 10], not hand-coded. Behind colors and beautiful images of games is a hard machinery, which directs the whole apparatus, and this machinery is based on math and physics – the same math and physics, which students learned already in secondary school, but what they have mostly forgotten, since math and physics is usually presented in a very academic way, separated from applications, and such "science per se" is quickly forgotten. Many want-to-be game creators are confused when asked a simple question, which requires elementary deductive reasoning (and understanding arithmetic progressions [11]):
Figure 1. Mario jumps with upwards speed component 10 ppf (pixels per frame) and horizontal speed component 4 ppf; gravity is 0 5 ppf – can he jump over the St. Olaf church and how far will he land?
In school movements and forces are often explained using a (non-animated) schema showing (non-elastic) ball or box rolling/sliding down a hill (it may be that a picture of Newton is also showed to make the event more vivid).
Figure 2. On halfway down the speed of ball has increased from initial 1 ppf to 2 ppf. What will be ball's (linear) speed on horizontal plane?
If this schema is shown to beginning game creators the answer usually is "3 ppf - the same as at the end of the hill!". But if they now are asked to perform a mental experiment – increase gradually the angle until it becomes 90°, then most of the become rather confused. Only after several such examples are beginning game creators ready to accept, that creating games is not only play and fun, but requires also lot of hard work, math and physics. But game creation is still fun. Game programming is a challenge to programmers' creativity and problem-solving skills, wh ich are the hallmarks of human intelligence. And solving all kind of puzzles wh ich appear in game creation process is great fun. "Programming games is much better than playing them!" – a statement from a student in Game Programming course. Co mputer (console, mobile phone, iPad) games are programs and created using a programming environ ment. For beginners low-level languages – C, C++, C# etc are waste of time, with them they can't create their own game (the main course requirement, another was a game review) in a one-semester course. The programming environment should be a tool, support game creation, there should be many ready modules for creating s tandard game structures - sprite-object system, event system with many different
types of events, system for creating game levels/rooms, scripting language. The Gamemaker system [12] satisfyes these requirements and is an excellent system for getting acquainted with games basic structure – objects, their sprites, events, actions. But Gamemaker is based on bitmap graphics, thus not suited for WWW, bitmap graphics is on www slow. There are some attempts to create web player (browser plug-in) for Gamemaker games [ 13],[ 14 ], but these work only fro m their o wn server. For WWW-games the most developed system is currently Flash. Flash is also very popular for web site development, what makes it also important for students , who often earn money as web site developers, thus our main development environments were Flash and the free AS3 programming environ ment FlashDevelop [15] . II. THE HARD SCIENCE – DATA ST RUCTURES IN FLASH The Flash programming language AS3 has 3080 builtin classes, which are documented in Flash help [16] (on 5.02.2011) p lus several non-documented classes, e.g. World, Joint, PffLib – the physics engine, what Flash developers are impatiently waiting. Fortunately beginning game developers do not have to study them all, for describing object's dynamics the most important are classes Math, Point, Vector3D, Matrix3D, Transform3D. A. The class Math Here are the common algebraic and transcendental functions: abs, ceil, floor, exp, log (this is natural logarithm ln, there is no functions for logarithms to base 10 or 2), pow (power), sqrt (square root, no function for other roots), max, min, random etc. For transcendental functions are called corresponding functions from Operating System, thus they are much slower than algebraic functions and results may d iffer under different Operating Systems (Windows, Mac). So me functions and constants seem even excessive, e.g. atan (with one argument) returns angle (in radians) between -π/2..π/2, atan2 (two arguments) returns angle between –π..π. B. The class Point A class Point object represents a point in twodimensional (2D) coordinate system, where x is the horizontal (fro m left to right) and y - the vertical axis (fro m up to down). This class does not have any visual representation for its objects and has properties and methods, where point object is considered as a vector fro m the origin of the coordinate system, e.g. if p, p1 are points (objects of the class Point), then p.length is the length of vector, p.add(p1), p.subtract(p1) are the sum and difference of vectors etc. Several useful properties and methods are missing, e.g. Point.polar(length,angle) constructs a new point/vector using the polar angle and length, but point/vector's polar angle cannot be directly accessed (only with the Math.atan2 function), there are no methods for calculating the dot and vector products etc. Some methods do not return value, e.g. p1 = p.normalize(1);
creates error: "… Imp licit coercion of a value of type void to an unrelated type flash.geom:Po int", correct would be: p.normalize(1); p1 = p; C. The class Vector3D The class Vector3D represents a point/vector in the three-dimensional (3D) space using the Cartesian coordinates x, y, and z; the depth axis z is directed away fro m screen (viewer's eye). Ob jects of this class can have also an optional fourth coordinate, which can represent rotation angle of the object, wh ich is indicated by a Vector3D object. This class has usual addition/subtraction methods and methods to calculate dot- and vector products , but the selection methods, their argument- and return types does not help beginning Flash programmer to remember everything. While in the class Point the method normalize had an argument, which allowed to create a collinear vector of any length, then in class Vector3D the method normalize does not have arguments (i.e. it behaves like normalize(1) in class Point). As in class Point the method normalize and several others do not return value, so a similar to the one presented above problem occurs: v2 = v1 negate(); creates error, correct would be a two-step assignment: v1.negate(); v2 = v1; III. OUR EXTENSIONS Because of the above discussed confusing problems we designed some new classes, which made Flash AS3 programming simpler and quicker. A. Class Vector2D The class Vector2D is an extension of the built-in class Point. These classes should not be confused with the builtin class Vector, wh ich is actually a tight arrow of objects of same type. Class Vector2D adds to class Point objects new property p.a – the polar angle of point/vector p and severl new methods: p.dot(p1) – the dot product of points/vectors p,p1, p.cross(p1) – cross (vector) product of vectors p,p1 (useful for deciding collinearity), p.angleTo(p1) – angle (in radians) from the polar angle of p to (clockwise – the y-axis is directed down) to p1, p.project(p1) – projection of vector p on vector p1. For students it is always a bit confusing to deal with geometric objects, which do not have visual representation on screen. Therefore in class Vector2D are also methods for creating v isual representations: p.drawp(r) draws a dot with radius r in screen point p; p.drawv(p1) draws vector p (as a line) from screen point p1 (the length is in pixels). Both methods allow formatting, i.e. changing color and line thickness.
With the method p.project(p1) and the visual aids fro m class Vector2D it is easy to create an animated exp lanation of the ball rolling down problem discussed above. It allows changing the angle and presents the speed vector in the mo ment of collision with horizontal surface as the sum of its horizontal and vertical components.
IV. GAMELET S The main method used in course was creating and analyzing gamelets – small game-like animations, which helped to explain some particular aspect of animation, converting coordinates from local (object coordinate space) to global (stage or parent coordinate space), where to add animation – to object or to parent/stage etc. Understanding the Flash principle of many simultaneous independent timelines (animations) and accepting the relativity of coordinates and animation requires just this kind of s mall exercises (gamelets). For instance a pendulum may be set to rotation from the upper/parent class – if pendulum is draw so that the origin is in its tip.
Figure 3. Explanation to ball speed on horizontal line
B. Classes for geometric figures For most geometric figues (triangles, circles) AS3 does not have separate class. A separate class is only for rectangles (defined by their upper-left corner coordinates, width and height), which are extensively used in methods fro m several classes. All other geometric figures are drawn in the class flash.display.Graphics using turtlegraphics approach. For instance, to draw a triangle with vertices in (x1,y 1),(x2,y2),(x3,y3) one has to define a new object e.g. myTriaangle, which would be either Shape, Sprite or MovieClip, determine the color and line parameters and then issue commands: myTriangle.graphics.moveTo(x1,y1); myTriangle.graphics.lineTo(x2,y2); myTriangle.graphics.lineTo(x3,y3); mtTriangle.graphics.lineTo(x11,y1); Issuing commands to draw simple figures makes AS3 drawing very slow and tedious; therefore we created several classes for quick drawing of geometric figures. For line segments were created several classes : a line between two points, from a point with given polar angle and length. Class Polygon(points:Array) creates a figure consisting of line sequences with given vertices; class RegPolygon draws regular n-gones using center, one vertice and the number of vertices. These classes were extensively used for visual debugging. The only method for debugging in Flash is command trace, which outputs some numeric values. For geometric problems (which objects collide, what happens next) these numbers are difficult to understand, much more helpful are visual cues – additional lines and points (dots), which show calculated lines and points.
Figure 4. Visual debugging aids – the collision line, collision point and balls speed vectors appear automatically in collision
Figure 5. T he origin of pendulum is in top (small cross), thus it can be set to oscillate from its parent class changing the value of its rota tion property
Students often tend to create "flat" applications with lot of spaghetti code in Timeline level. It takes time until they adopt Object-Oriented (OO) style of thinking and design, e.g. that bullets can fly and destroy targets "on their own", i.e. their speed and direction is determined in bullet's class (not in the main class), in this class are also methods to check weather a bullet has hit a target – if only bullets "know" about targets, i.e. array/vector of targets is passed to the class on initialization. V. CUTTING CORNERS In games is very essential speed – if player should wait until computer computes in which direction the ball will fly next then the game is not fun. This is why the built-in method for collision detection in Flash uses object's bounding rectangles – rectangles overlapping can be found only with four comparisons. But this makes Flash collision detection for vector objects very imprecise.
Figure 6. T wo frames showing ball moving towards a line – in the second frame (right) there is already collision (line is thick), although the ball is still far away
Therefore the Flash collision detection for vector objects is often useless and one has to invent some quick approximat ions. The above situation with a small object moving towards a skewed line occurs e.g. when windshield wiper brushes snow fro m windshield, trying to create some visibility; this was often very difficult in this winter, several Santas disappeared.
easy to create e.g. 3D version of well-known Breakout game:
Figure 10. 3D Breakout - ball, bouncing in 3D space
Figure 7. Windshield wiper removed a snowflake when the slope of line from snowflake to wiper's tip become close to wiper's slope.
Deciding snow particle collision with wiper line requires solving a system on linear equations, which is too slow with thick snowfall. Therefore an appro ximate method was used – if the slope of the line fro m a particle to the upper end of wiper blade (small red dot on picture) becomes close to the slope of the wiper the particle should disappear. VI.
U SING BIT MAPDATA
Flash is based on vector graphics – vector (formu la) representation takes much less bits than bitmap representation and thus is more suitable on network. But several problems are with bitmaps simpler, therefore in the last version of AS3 were introduced classes BitmapData and Bitmap. Bitmap is an envelope for the BitmapData, where is stored the content of an image as an array of pixel color values.
Figure 8. Bitmapdata array which describes a small letter "H" (in the upper-right corner)
With bitmapdata detecting collision of non-convex figures becomes very simple. For instance, in "Tower Defence" –type game a tower (round figure) should not have collision with road (kinky line). Road is usually nonconvex, with many h ills and hollows and checking exact collision with vector methods is rather complex. But for corresponding bitmapdata the check requires only a few lines, even when the road is rotated around the X-axis to create a more 3D-imp ression.
Figure 9.
Also in the final exam (for those, who were late with their individual projects – a game assessment and original game) selection of the gamelet to imp lement was presented as a 3D shooting task (its physics is similar to popular game "Angry Birds"):
Collision test with figure (road), rotated by -30 degrees – the left frame – no collision, right frame - collision
VII.
3D GAMELET S
Flash has been purely "flat", two-dimensional animat ion package, but the latest version has added also some three-dimensional (3D) features (e.g. rotations around all three coordinate edges) and Adobe has promised much better 3D support in the next release, thus to introduce elements of 3D thinking were considered also (already existing) 3D features of Flash. It is comparatively
Figure 11. To get a ticket (task), student has to shoot down in 3D space the rotating target.
VIII. CONLUSION Game programming is for students a very excit ing topic, but they often do not expect it to require skills in many areas – math, physics, sound editing etc. Above are presented some issues which we had and described Math and graphics topics, which we considered in the Flash AS3 programming environment in our Game Programming course. REFERENCES . [1] [2] [3] [4] [5] [6] [7] [8]
1
https://www.mochimedia.com/ http://www.newgrounds.com/ 3 http://www.mindjolt.com/ 4 http://www.xgamesflashx.com/ 5 http://www.spelunkyworld.com/ 6 http://www.minecraft.net/ 7 http://www.canabalt.com/ 8 http://www. wired.com/gaming/gamingreviews/magazine/1608/pl_games [9] 9 http://en.wikipedia.org/wiki/Procedural_generation [10] 10 http://roguelikedeveloper.blogspot.com/2008/01/death-of-leveldesigner-procedural.html [11] 11http://mathworld.wolfram.com/ArithmeticProgression.html [12] 12 http://www.yoyogames.com/gamemaker [13] 13 http://gmbed.com/ [14] 14 http://www.yoyogames.com/browse [15] 15 http://www.flashdevelop.org/ [16] 16 http://help.adobe.com/en_US/FlashPlatform/reference/ actionscript/3/class-summary.html 2