Download - lucu.googlecode.com

Document Sample
Download - lucu.googlecode.com Powered By Docstoc
					                          ...the smart can give you solutions...
                     ...the intelligent can give you answers...
         ...but, alas, the wise can only give you questions...




The lucu guide for creating videogames                   Page 2 of 87
   Welcome to the lucu guide! I hope you will find here the information you need to
   start your journey on making your own videogames.

   Creating games is a challenge, but maybe with a little help from this guide it will
   be as fun as playing games.

   In Indonesian (bahasa) language "lucu" means "fun". And that's the "key" word in
   this guide. No matter what kind of game (table game, board games, computer
   game) you are trying to create, your "ultimate goal" is to allow people to have
   fun.

   Happy gaming!




The lucu guide for creating videogames                                      Page 3 of 87
   License
   Creative Commons
   Attribution-Noncommercial-No Derivative Works 3.0 Unported

                          http://creativecommons.org/licenses/by-nc-nd/3.0/deed.en_US




   ( In plain simple words: you are free to copy and share this document as long as you always say
   who the original author is and as long as you do not use it for commercial purposes. )




The lucu guide for creating videogames                                                    Page 4 of 87
   About the author
   Taksan Tong is a software architect, who, as part of his job has used different computer
   technologies (not all of them voluntarily) in different software development projects.

   When he is not creating software for a bank or an enterprise he is creating (mostly playing actually)
   video games or learning what real games are made of from his 3-year-old daughter Dharma.


   He can be contacted at: taksantong@yahoo.com




The lucu guide for creating videogames                                                      Page 5 of 87
   Acknowledgments

   Thanks to my dad for buying me a Commodore64 computer when I was a kid. (Even though his
   intention was not for me to program games on it!)

   Thanks to Adolfo for the "extra hardware" for game developing and testing. It really came in handy!

   Thanks to Marvin Fröhlich (from the Xith3D forum) for helping me understand how the Xith3D
   engine works.

   Thanks to any friend not included in this page but that understands my crazy mind sometimes flies
   away too much and I may forget to put a name here.




The lucu guide for creating videogames                                                     Page 6 of 87
   The source code

   You can find the source code of the examples presented in this guide here:

   http://code.google.com/p/lucu




The lucu guide for creating videogames                                          Page 7 of 87
     Table of Contents
Chapter I: Theory ............................................................................................................................................ 9
What is a game?..............................................................................................................................................10
So what are video games then? .......................................................................................................................10
How a videogame is created ............................................................................................................................11
The most important component to include in your video game: FUN! .................................................................16
Chapter 2: Decision time ...............................................................................................................................17
What programming language should I use for my game? ..................................................................................18
Game engines .................................................................................................................................................19
DirectX (Direct3D) versus OpenGL...................................................................................................................22
Final recommendations....................................................................................................................................23
My (very) own personal decision ......................................................................................................................23
Chapter 3: Making a 2D game........................................................................................................................25
Computer game flow........................................................................................................................................26
Setting up the development environment ..........................................................................................................27
Making a puzzle game with GTGE....................................................................................................................27
Chapter 4: Making a 2D multiplayer game.....................................................................................................34
Networking basics............................................................................................................................................35
Game server....................................................................................................................................................37
Puzzle game - multiplayer version ....................................................................................................................37
Chapter 5: 3D games .....................................................................................................................................41
3D basics ........................................................................................................................................................42
Chapter 6: Making a 3D game........................................................................................................................46
Step 1: Prepare an empty screen .....................................................................................................................48
Step 2: Loading a map .....................................................................................................................................49
Step 3: Moving around the map........................................................................................................................49
Step 4: Checking collisions...............................................................................................................................50
Step 5: Adding the apple ..................................................................................................................................50
Step 6: Game Loop..........................................................................................................................................51
Step 7: Final version of the game .....................................................................................................................52
Chapter 7: Making a 2D multiplayer game - version 2...................................................................................55
A better network library ....................................................................................................................................56
Why UDP?.......................................................................................................................................................56
Adding the ummi network library to the puzzle game.........................................................................................57
Chapter 8: Making a 3D multiplayer game.....................................................................................................60
Apple Chase - multiplayer design .....................................................................................................................61
Making some improvements to our 3D game ....................................................................................................61
Adding server-side game logic..........................................................................................................................62
Updating the game client..................................................................................................................................62
Appendix A: Extra Resources .......................................................................................................................67
Library .............................................................................................................................................................67
Resources .......................................................................................................................................................70
Appendix B: How to setup Slick framework with Eclipse .............................................................................72
Appendix B: How to setup Slick framework with Eclipse .............................................................................72
Appendix C: How to setup GTGE inside Eclipse IDE....................................................................................79
Appendix D: How to setup Xith3D inside Eclipse IDE...................................................................................83
Installing the support libraries ...........................................................................................................................83
Adding Xith3D's own files .................................................................................................................................84
Adding the native libraries ................................................................................................................................85
Making sure Xith3D is installed correctly...........................................................................................................87
Appendix E: Xith3D scenegraph....................................................................................................................88




The lucu guide for creating videogames                                                                                                               Page 8 of 87
Chapter I: Theory
What is a game?

   Games have been created and played for thousands of years. Take for example this very old board
   game: Senet ( http://en.wikipedia.org/wiki/Senet )

   One can almost say that games exist because there is life, because not only humans play, animals
   do too. So, what is a game? One very basic definition is that a game is a "fun activity", but that's
   not enough because then we need to ask "why we want to have fun"?

   My own theory is: because we are, by nature, social and curious beings. We have a natural instinct
   for it. As babies we play a lot and have fun a lot, and that happens not just because babies are
   playful, but also because they need to learn about their environment (objects and humans around)
   and guess what is the best way to learn?... playing of course! Having fun while learning something
   new is the best way to ensure we learn for good. And this applies during all our life, no matter how
   young or old we are.

   Now, if you add some rules while playing (even if it is a simple rule like "my turn first, then yours")
   and put a name on it (even if is as simple as "guess-a-number") then you have a game!

So what are video games then?

   If done right they are just games in a digital platform: cellphones, computers, game consoles, .etc.
   If done wrong they are just products in a store waiting for someone to buy them.

   But since they are matter of our study, they deserve a more glorious definition:

   video games are a form of entertainment, alone or in a group, through digital and/or electronic
   platforms.

   With this definition we can cover from a single person playing tetris in his cellphone all the way up
   to a group of people enjoying a multi-player game at once while they are physically in different
   parts of the world. The word "entertainment" has a whole background just by itself. With this word
   we can even compare the video games and movies, they are both a form of entertainment and they
   are both lucrative also, in fact, the video game industry may very well in the future be as big (and
   maybe bigger) than the movie industry.

   And entertainment can also involve magic, fantasy, illusion, fun, music, and interesting challenges!
   and to combine all them requires not only technique, but also art. To create a video game you will
   also need assets like images, videos, sounds, and stories.

   This document attempts to guide you in your first steps on creating a video game. But one single
   guide cannot cover all these aspects so be sure to check the appendix "Library" later in this guide
   for a light on other topics related to video game creation.

   One more advice: Try to play as many games as you can. From different platforms (xbox, ps2, ps3,
   PC, Wii, GameBoy... )... try different types (action, rpg, sports....)... this will give you a lot of
   experience and ideas on what works and what does not. Plus it will be fun! And you do not have to
   waste money on this, you can just try the demos. Even if you can not try the demos, look at videos
   of trials, intros, or other people playing, there are some websites that let you do that, like
   GameSpot or GameTrailers ( GameSpot.com, GameTrailers.com )




The lucu guide for creating videogames                                                       Page 10 of 87
How a videogame is created

   We start with the idea of a video game ("I want a game about a spaceship that can transform into a
   robot and then...") and based on it we start to develop the rules, the graphical and audio resources,
   and then we package them together and produce software, which is our game. This high level
   overview is described in the following diagram:




                                         video game production pipeline



   Be sure to notice one important point: the "flow" of the production process does not just goes from
   "top to bottom", but it can actually go back again to the design level and between processes also,
   this is because:

            Your game design may require to put the main character of the game in a fight with 10
             dragons, but once you reach programming time you realize your technical skills/resources
             can allow you display only one dragon at a time on the screen. (just like any software
             development process)


The lucu guide for creating videogames                                                     Page 11 of 87
              Testings and prototypes can show a flaw or aspect of the game that needs to be re-
               designed. It is always a good practice to test your game with (digital or not) prototypes. (
               Here is when your beta testers help )
              It could also happen that you create a wonderful 2D image that requires just a little 3D
               touch to make it more realistic. This is a good example of how an asset can move from "2D
               process" to "3D process".

   All this is great! Just as if we were creating a digital interactive movie.

   Now we go for more detail about this process:

   2D graphic design: Not all games have to be "3D". And, even "3D" games need some 2D
   graphics (like textures) to support them. Some games may not even have graphics (like text-based
   games). So it is always good to know how to manage 2D graphics. Be aware that some "3D"
   games are just 2D with "perspective" (AKA isometric games). Here are some popular examples of
   2D tools you can use:

       Tools                                        License         Notes

       Adobe Photoshop                              Commercial      Probably the most popular in this
                                                                    category
       http://www.adobe.com/products/photoshop

       Adobe Illustrator                            Commercial      Vector graphics manipulation

       http://www.adobe.com/products/illustrator

       Inkscape                                     Free            Vector graphics manipulation

       http://www.inkscape.org

       GIMP                                         Free

       http://www.gimp.org

       Adobe Flash                                  Commercial      Not just a 2D graphics tool, but a
                                                                    complete environment for 2D
       http://www.adobe.com/products/flash                          applications. New versions are starting
                                                                    to have some basic 3D capabilities

       Corel Draw                                   Commercial      Can handle vector and bitmap

       http://www.corel.com



        Tips      To help you decide which tool to use you can also see on-line tutorials of each one and
                 download the software (or trial editions).
                  Do not try to "master" any particular tool, you may discover later that you need to know
                  a little of each one.
                  In general, people that have a "designer" background prefer Adobe software because
                  its interface is more easy to use by designers (and in general they used Adobe
                  software while they had their design-classes at school)
                  In general, people that have a more "technical/programming" background (like me) tend
                  to prefer software that is easy to customize and to extend with plugins (or lets you
                  create/program your own plugins) and that is why this kind of people may choose
                  Inkscape, GIMP or Corel Draw.
                  Don't forget to learn a Vector tool AND a BITMAP tool, both will be handy.


The lucu guide for creating videogames                                                             Page 12 of 87
   There are some "extra" 2D tools you may or not need depending on the kind of game you want to
   create, here is a list of some of them in case you need one:

       Tools                                    License          Notes

       GraphicsGale                             Commercial       Great for doing sprites/animations

       http://www.humanbalance.net/gale/us/

       MTPaint                                  Free             Bitmap/Sprite image manipulation

       http://mtpaint.sourceforge.net/

       Particle Illusion                        Commercial       Create wonderful effects!

       http://www.wondertouch.com/

       Tile Studio                              Free             Image editor for game resources, can
                                                                 also create map (tiles) for your game
       http://tilestudio.sourceforge.net/                        levels



   3D graphic design: 3D modeling and rendering helps to add realism and great visual effects to
   our games. Keep in mind that doing 3D graphics for movies, architecture, animations or games are
   different topics so some 3D tools are better in one area than another. One very important feature
   you need to consider when selecting a 3D tools is the import/export capabilities it has, there is no
   point in creating a fantastic 3D figure if you can not export it in an appropriate file format that your
   game can use. Here are some popular examples of 3D tools you can use:

       Tools                                    License        Notes

       Autodesk Maya                            Commercial     Excellent for animations (like the ones you
                                                               have seen in animated movies)
       http://www.autodesk.com
                                                               Special comment here: Please do not
                                                               think that just because you buy Maya you
                                                               can now create an animated movie like
                                                               the ones created by Pixar. Anything good
                                                               requires patience and training (regardless
                                                               of the tool), and sometimes, the right
                                                               plugin (which can be an extra cost aside
                                                               from the software)

       Autodesk 3ds Max                         Commercial     Best all-around general-purpose
                                                               commercial 3D tool. This is the best
       http://www.autodesk.com                                 choice if you don't know what 3D tool to
                                                               use (and if you can pay the price)

       Blender                                  Free           Best free-3D general-purpose tool. It is
                                                               interesting to note that it includes the
       http://www.blender.org                                  "Blender Game Engine" which is a tool for
                                                               creating 3D games.

                                                               Very important note: many people
                                                               consider Blender to have a "not-friendly-
                                                               easy" user interface and give up on using
                                                               it... but starting with version 2.5 this
                                                               software comes with a TOTALLY NEW
                                                               user interface so I highly recommend you


The lucu guide for creating videogames                                                          Page 13 of 87
                                                              give it a try.

       Truescape                                Free          Very good 3D tool that used to be
                                                              commercial. It has one minor issue: it is
       http://www.caligari.com                                unclear if new version will be released.

       GMAX                                     Free          It is old but it is good to keep around for its
                                                              import/export capabilities
       http://www.turbosquid.com/gmax

       AC3D                                     Commercial

       http://www.inivis.com/

       Milkshape                                Commercial    This tool offers an interesting list of
                                                              import/export features used by many
       http://chumbalum.swissquake.ch/                        video games, some people have a
                                                              "primary" 3d software for the main work
                                                              and "secondary" tools like this one just for
                                                              importing/exporting from/to multiple file
                                                              types.

       Modo 401                                 Commercial

       http://www.luxology.com/

       Cinema 4D                                Commercial

       http://www.maxxon.net


   Choosing a 3D tool is usually not easy because of the great amount of "features" and "options"
   each package has to offer and beginning game developers usually do not know 3d terminology like
   "nurbs", "zbuffers", "shaders", etc. So here are some tips to help you on your selection:

             The most popular in the gaming industry are: 3ds Max and Maya.
             3ds max is best as an "overall 3d tool" (it can to many things) while Maya is best used
              when you already know your basics and want to specialize in character animation.
             If you go with the "free" option, then Blender is probably your best choice
             Here is one interesting link that compares some 3d tools: second life's mini guide to 3d
              tools ( http://wiki.secondlife.com/wiki/Sculpted_Prims:_3d_Software_Guide ).

   Audio design: One important advice for sound in video games is: keep it small. This is because
   audio is just another resource and it is used often (example: in a typical game one sound effect
   may be repeated every time you press a button), so it is not enough to know about audio, but also
   to know about audio compression techniques (mp3/ogg) and to understand that sometimes a
   music background can be just a simple instrumental music (MIDI format) and not necessarily a full
   recorded song (like mp3 format).

   Here are some popular examples of audio tools you can use:

      Tools                                    License                                  Notes

      Adobe Audition                           Commercial

      http://www.adobe.com/products/audition

      Audacity                                 Free



The lucu guide for creating videogames                                                           Page 14 of 87
      http://audacity.sourceforge.net/


   So many tools and so little time!

   Nobody has the luxury/time to learn all the tools, at some point you need to decide one tool over
   the other as a "favorite" or preferred tool. And if you are going to pay for the tool, the decision
   becomes even harder. So here are some general tips for choosing a tool:

            There is no "best tool of all", try different options and find the one that works for you, not
             the one that works for company X or guy Z.
            Do not think that just because a software is free it is of lower quality than a commercial
             tool.
            Free software usually gets updated more often (more new versions and upgrades per year)
             and of course you can them easily.
            Inside one category, try to learn one tool and at least know the basics of the others. (or at
             the very-least know the features available in the other tools).
            Commercial software usually has more books/manuals and tutorials/videos available. And I
             mean good professional documentation, not just some "amateur tutorial of tool X created
             by a crazy guy that names his website "lucu" :)
            One good guide to choose a tool is to verify how many books about that tool are available
             in bookstores like Amazon.com, that gives an idea of how popular the tool is.
            Commercial software offers the best options for certification, this is useful if you later on
             plan to use your skills to apply for a job.
            Read some video games magazines (look at the "Resources" appendix later in this guide)
             and check out what are the popular tools used in the video game industry.
            Ask and solve these questions for the tool: what plugins are available? cost of the plugins?
             Can I create my own plugin?

   Game programming: Here is where you join and mix all ideas, designs and graphical resources
   and produce software. At this one the beginner game programming is tempted to code his first
   game with the programming language he knows best. My advice is to explore other programming
   languages first, here are some options:

      Language         Notes

      Actionscript     Pros
                                Create games that can be easily embedded in a web page. You may have already
                                 noticed that the Internet is "flooded" with mini-games you can play on-line. We can
                                 easily say 99% of those games were created with Flash.
                                Flash player (the run-time the game needs to play) is installed in more than 90%
                                 internet browsers and if not installed it is very easy to install by the final user (the
                                 player).
                                Lots of books available for creating games with ActionScript/Flash
                       Cons
                                Limited 3D capabilities.
                                Programming tool (Flash IDE) has it's focus into art design, not into code
                                 programming.
                                Limited multiplayer capabilities. You can use TCP, but UDP is not available (yet)
                                 as an option. This means you can create a multiplayer game for approx 5 to 20
                                 users, but scalability is uncertain.

      Python           Pros
                                Very easy high-level language to learn.
                                Very good sites for creating games with Python, for example: PyGame (
                                 www.pygame.org ), Panda3D ( www.panda3d.org ), Blender Game Engine (
                                 www.blender.org )



The lucu guide for creating videogames                                                                     Page 15 of 87
                       Cons
                                Programming syntax is a little bit awkward, you either like it or not.
                                Programming IDEs are abundant, but they are not very user friendly. Recent
                                 version of Netbeans and Eclipse PyDev plugins are changing this though.

        C++            Pros
                                Offers features and power to create very complex games with high level of
                                 graphical detail and fast performance. Top commercial games are usually created
                                 in C++.
                                Huge amount of books and documentation about C++ and game creation with
                                 C++.

                       Cons
                                Learning curve is high. If you are beginning to create video games I recommend
                                 you stay away from C++, unless you are already familiar with the language. If you
                                 insist in using the language then I recommend buying a commercial game engine
                                 like GameStudio ( www.conitec.com ) to help you in the process.

        Java           Pros
                                Easy to learn language
                                Lots of books available for creating games with Java
                                Many tools for developing (IDEs), profiling, testing, editing, compiling, etc.
                                Many sites with info on how to create games with java, for example: LWJGL (
                                 http://lwjgl.org ) , Slick (http://slick.cokeandcode.com ) , JPCT ( http://www.jpct.net
                                 ), jMonkeyEngine ( http://www.jmonkeyengine.com )

                       Cons
                                Lots of options and libraries sometimes create confusion on beginners that do not
                                 understand where to start. This is applies not just to game development but to java
                                 development in general. This guide will focus on java development in later
                                 chapters so more detail about java game development will be covered then.



The most important component to include in your video game: FUN!

   No matter what technology you use to create your video game, without the "fun" element it will not
   be a good game. So, it is important to understand what "fun" is.

   The best definition of "fun" can be found in the book "Theory of fun" (see the library section of this
   guide for details). It is a must-read for anybody trying to make a video game. I'll try to give a little
   definition of what "fun" (applied to games) is:

   A fun game is the one that offers an interesting challenge to the player and makes him want
   to play the game until the challenge is conquered. But, the trick is to make the challenge not
   too hard (it will cause frustration) or too easy (it will cause boredom), so that the player can
   keep on playing.

   Try to make funny games, and the same time, have fun while doing them!

   Here are some tips to help you better understand the concept of "fun":

         Remember the games you played when you were a kid. (Better yet, find some kids and play
          with them!).
         Play games that require social interaction between people (like board games or Dungeons
          and Dragons or Role Playing games) and look what works and what does not work in them.




The lucu guide for creating videogames                                                                    Page 16 of 87
Chapter 2: Decision
time




The lucu guide for creating videogames   Page 17 of 87
What programming language should I use for my game?

   This is usually the first question a beginner makes and sadly, is the wrong question to start with.

   Just like when we develop any other kind of software, programming languages are tools, not
   objectives. And as such we need to first think and design what kind of game we will create, then
   find the best programming language for the job.

   One way to solve this starting dilemma, and at the same time prepare a foundation for the design
   of the game, is to think about the features our game requires to run and to be available for our
   intended target of players. We can think of it like a "Platform" for our game.

   So here are some common "Game Platforms", try to select the best fit to support your game.

      Gaming              Notes                                     Recommended language to use
      Platform

      The mobile          AKA: the player is "always connected,     If you aim at "classic" cellphones you can use
      platform            anywhere". The best example of this       Java J2ME to create games that work on many
                          platform is games for cellphones.         cellphones. Be aware that programming for
                                                                    different devices can sometimes be a pain due
                          Gamers: almost everybody has or will      to different hardware implementations. Also be
                          have a cellphone. And more and            aware that cellphones are "evolving" into smart
                          more people will start to get advanced    phones (iPhone/Android powered phones)
                          smart phones and leave behind             where J2ME is no longer the best option.
                          "classic" phones. Gamers are mostly
                          casual gamers that want to play           In the specific case of iPhone, you almost have
                          simple 10 dollar-games                    one option only: the objective-C programming
                                                                    language.

                                                                    Forgetting the technical details for a moment,
                                                                    this platform has a very promising future as a
                                                                    market. Trend reports that in the future more
                                                                    and more people will play on their phones.

                                                                    Using the C/C++ language you will probably get
                                                                    the most of the limited hardware of this devices.

                                                                    Be aware that, you can use Flash on some
                                                                    mobile devices, but that of course will limit the
                                                                    features and performance you can get for your
                                                                    games.

      The console         XBOX, Playstation, Nintendo Wii           Microsoft's C# is the recommended option for
      platform                                                      XBOX.
                          Gamers: this is a though market,
                          usually people that owns a game           For the other consoles C/++ is a safe bet since
                          console has higher expectations, after    you will usually want performance and
                          all they will be paying 50+ dollars per   portability.
                          game and want to make the best use
                          of their consoles.                        Java, Python and Flash are not recommended
                                                                    (not even valid in some cases) options.

      The PC              Computer PC                               For casual quick web games that you can
      platform                                                      embed in almost any website: Flash. This will
                          Gamers: wide range! from teenagers        immediate access to many people to your
                          looking for the greatest action game      game. But, there is a technical limit on what
                          to housewives or business men             kind of games you can create with Flash.
                          looking for casual games.



The lucu guide for creating videogames                                                                  Page 18 of 87
                            One interesting point to notice is that,      To quickly start making 2D or 3D games: java or
                            PC games are expected to have                 python
                            higher levels of complexity than other
                            platforms, basically because a PC             To go deeply and seriously about high
                            has more features (mouse, keyboard,           performance games that use the latest and
                            and joystick) and also because                greatest graphics and hardware: C / C++. But
                            people that use a PC usually do it for        this also means you have the time and
                            hours, so there is more room for              resources to invest in making a game with C or
                            details in a game.                            C++.


Game engines

   Just like any other software development, when creating video games you should always try to re-
   use components instead of creating everything from zero. This is a good software practice, that is
   why we have libraries, frameworks, and in the case of video games, we have "Game Engines" that
   are software components that already provide functionality for video games and we can just re-use
   and concentrate more on our game logic.

   We will explore what are these common functionalities most video games have, but here is a brief
   list:

            Graphics components for displaying 2D/3D graphics.
            Networking functions (for multi-player games)
            Audio functions
            Physics modules
            Animation frameworks
            Maps management (for multi-level games)

   Using a game engine is recommended since it will help you create games faster and easier since
   many of the functionalities described above will be ready for you to use.

   Be aware that sometimes game engines support a "primary" programming language and
   "secondary" programming languages, often referred as "scripting" options. This is because some
   engines offer core functionality with a lower level (and more powerful) programming language and
   delegate some task management or game logic management to a higher (and more easy to use)
   programming language. The reasoning behind this is: provide power features for your game and at
   the same time an easy to use language to control it. A very good example of this situation is the
   Panda3d engine: it uses C++ for its core high-performance demanding features, but can be easily
   controlled with the Python language.

   Here is a list of some popular game engines available:

      Game Engine                     License       Language           Comments

      Java Monkey Engine              Free          Java               (+) Great for 3D games
      http://www.jmonkeyengine.com/
                                                                       (+) Very complete game engine (version 2, version
                                                                       3 is still in beta as of October 2010)
                                                                       (+) Very active development
                                                                       (+) Supports a variety of 3d model formats


                                                                       (-) Documentation is not easy to follow
                                                                       (-) Big engine with lots of features, but not so easy
                                                                       to start for beginners

      Blender Game Engine             Free          Python             (+) Very easy to use, you can even create games
                                                                       without programming


The lucu guide for creating videogames                                                                        Page 19 of 87
      http://wiki.blender.org/index.php                               (+) Create 3D games easily
      /Game_Engine

                                                                      (-) It is not clear how to program advanced
                                                                      features like: networking

      Irrlitch                            Free         C++            (+) Great features/options (like world editor)
      http://irrlitch.sourceforge.net

      Panda3D                             Free         Python         (+) Great for 3D games
      http://www.panda3d.org/
                                                                      (+) Very complete game engine
                                                                      (+) Very active development
                                                                      (+) Very good documentation
                                                                      (+) Cool feature: the latest version allows you to
                                                                      deploy web games (like flash)

      Away3D                              Free         ActionScript   (+) Great for doing 3D games in Flash
      http://away3d.com/                                              (-) 3D performance is not very good in Flash. Don't
                                                                      expect to create a "DOOM" close with Flash 3D

      PyGame                              Free         Python         (+) Great for 2D games
      http://www.pygame.org                                           (+) Very good documentation

      GameStudio                          Commercial   C++            (+) Great for commercial games
      http://www.conitec.com
                                                                      (+) Great introductory price
                                                                      (+) Has a "lite" version free and easy to use for
                                                                      beginners

      Microsoft XNA                       Commercial   C#             (+) Excellent option if you plan to make DirectX
      http://www.microsoft.com
                                                                      games for PC and or XBOX
                                                                      (+) Very easy to learn for beginners. LOTs of
                                                                      documentation and tutorials available.
                                                                      (+) Can create 2D and 3D games.

      LWJGL                               Free         Java           (+) Great for 2D games
      http://lwjgl.org/                                               (+) Can be used for 3D games also because it is
                                                                      an implementation of OpenGL, but hard to use
                                                                      since it only provides plain OpenGL, with no
                                                                      scenegraph or extra functionality.


                                                                      (-) Lacks documentation
                                                                      (-) Not easy support for 2D animations (animations
                                                                      like animated GIFs for example)

      JPCT                                Free         Java           (+) Great for 3D games
      http://www.jpct.net/

      3DzzD                               Free         Java           (+) Great for quick 3D web games
      http://dzzd.net/
                                                                      (-) Lack of documentation
                                                                      (-) Does not support 3D animations (models like
                                                                      MD2 for example) easily

      Slick                               Free         Java           (+) Great for 2D games




The lucu guide for creating videogames                                                                       Page 20 of 87
      http://slick.cokeandcode.com/                                  (+) Supports 2D animations
                                                                     (+) Does not hide OpenGL from the developer
                                                                     (-) Documentation is work in progress

      Java FX                             Free         Java          (+) Great for 2D games
      http://javafx.com/                                             (-) Still in early versions, but very promising for the
                                                                     future

      GTGE                                Free         Java          (+) Good for 2D games
                                                                     (+) Supports 2D animations
      http://goldenstudios.or.id/produc                              (+) Does not hide OpenGL from the developer
      ts/GTGE/

                                                                     (-) Initially you create basic games that use
                                                                     AWT/Swing technology (which does not take
                                                                     advantage of hardware acceleration) but after you
                                                                     study the engine you can later add OpenGL or
                                                                     LWJGL or JOGL (with add-ons) to improve your
                                                                     visuals.

      Game maker                          Commercial   Propietary    (+) Great for 2D games
                                          (with free   language
                                          option)                    (+) Can be enhanced with custom DLLs
      http://www.yoyogames.                                          (+) Good documentation available
      com/gamemaker/

      Unity 3D                            Commercial   JavaScript    (+) Great for 2D games
                                          (with free
                                          option)      C#            (+) Can be deployed as a web game
      http://unity3d.com/                              Python-like   (+) Good documentation available
                                                       script
                                                                     (+) Can be used for iPhone and Android
                                                                     development also (with a paid optional module)

      Xith3D                              Free         Java          (+) Great for 3D games
                                                                     (+) Easy to extend/build games upon the base
                                                                     components.
      http://Xith3D.org
                                                                     (+) Good documentation available inside the
                                                                     framework download.
                                                                     (+) Lots of examples provided with the framework
                                                                     download.
                                                                     (+) Supports a variety of 3d model formats.
                                                                     (+) Integrated physics engine.
                                                                     (+) Input system.
                                                                     (+) HUD support.
                                                                     (+) Can be used for 2D games also (I have not
                                                                     tested this feature myself yet, but will do when I get
                                                                     a chance)


                                                                     (-) New versions are not released frequently, but
                                                                     you can always download directly from the source
                                                                     repository.


   An extensive list of game engines can be found at: Devmaster game engine database (
   http://www.devmaster.net/engines )

The lucu guide for creating videogames                                                                        Page 21 of 87
DirectX (Direct3D) versus OpenGL

   Some people might say this is the classic "Microsoft versus the world" debate, but this topic is more
   than just that. Preferences and bands aside, let us concentrate on the facts: sooner or later you, as
   a game developer, will be faced with the choice of using DirectX or OpenGL for your game. Those
   two are software libraries that help you create your games. Usually some engines are just
   interfaces between your game code and the graphics library supported by your hardware (DirectX
   or OpenGL).

   Nowadays almost all modern hardware (that is, graphics video cards, CPUs, processors,
   mainboards) supports both libraries very well. And, technically speaking, both libraries are great to
   use and offer a wide arrange of features.

   In most cases, you do not need to worry about this topic. It is better to worry about choosing the
   right game engine for you and let the engine handle whatever graphics library it needs. There are
   even some engines that can handle both (like Irrlicht game engine).

   So why we need to worry about this?

   Both libraries are good and you can find a huge amount of info about them (including comparisons)
   on google and using one over the other does not guarantee your game will be better. But it is
   important that you know about them as a reference. Here are some things you need to consider
   about them:


            DirectX usually offers more "eye candy" features before OpenGL does. For example:
             DirectX version 10 (current version as of Nov2009) is out there and the games that use it
             (not a lot do) show impressive graphics and realistic effects. Google for "directx10 games"
             to get a list. But sometimes this just means that many famous/commercial games use
             DirectX and more known/popular.
            To use DirectX10 you need at least Windows Vista and very modern graphics card.
             (Remember I'm writing this in 2009, things might change in the future) so your
             development options must be focused on that.
            OpenGL on the other hand, is supported by many platforms. Again, later versions of
             OpenGL of course are only supported on modern graphics cards, but is available for many
             platforms.
            One can rush and say that "OpenGL then is better because it is multi-platform", but that
             sentence can easily be countered with a simple question: how big is the market for gamers
             in platforms other than Windows? You will get of course different answers depending on
             who you ask, but regardless how much you love (or hate) Windows, you need to focus on
             what gaming market you want to address (and possibly specialize into).
            There are some that say that OpenGL is better because it can be used by many different
             languages. A good example about this is that the NEHE web page (
             http://nehe.gamedev.net/ ) offers different ways to use OpenGL with different languages.
             But Microsoft can surely say the same thing about DirectX because the .NET framework
             and the Visual Studio tools can support a long list of programming languages, including
             ones that are not "Visual Studio classics" like Visual Basic and C++, but also others like
             Python.
            Beginner game developers tend to think that they need to learn DirectX or OpenGL to
             make games. There are even some books available with titles such as "How to do games
             with DirectX/OpenGL". My advice for beginners is, again, to better concentrate on choosing
             a good game engine.

   I recommend you first start with a good game engine/framework and worry about directX versus
   OpenGL later, but don't forget that you will eventually have to deal with DirectX/OpenGL libraries


The lucu guide for creating videogames                                                     Page 22 of 87
   as you advance in your game developer path, usually when you want more performance, extra
   features or custom functionality.


Final recommendations

      If you wan to create games as fast as possible           Try GameMaker
      without programming:                                     Try Blender Game Engine
                                                               Try any "authoring software" (let's you build
                                                               applications without coding)
      If you wan to create games as fast as possible           Try GameMaker
      (and are not afraid to program a little):                Try Flash
                                                               Try PyGame
      You want to be in the "cutting edge" of gaming           Don't make games, stop making software, try to be a
      and use the very latest technology possible :            poet or artist instead (or create the art for a game) :)
                                                               Seriously: stop thinking like that if you want to create
                                                               software (good software that is).
      You want to do a web that most people can see            Try Flash
      and/or play.                                             Try the Unity 3D game engine
      This is a very good option, specially if you are         Try any game engine that lets users play your game
      new in the business and what to gain some fame           "inside a browser"
      or "make a name" in the gaming world                     Try making games for iPhone/Android/whatever mobile
                                                               device is popular.
      You want to make games but are also interested           Try Java, C#, XNA or C++
      in study, research and apply game-related
      topics, like "virtual worlds", "social interaction",     If you want to go deeper into the gaming world, you
      "multiplayer", "artificial intelligence", etc and want   need to find tools, libraries, books on different gaming
      to go beyond "simple mini-games"... and                  topics and you MUST learn to program. You will find
      probably make games as a career or long-term             that C++, XNA, C# and Java have an incredible
      proyect.                                                 amount of information about gaming topics so you can
                                                               choose any of them.


My (very) own personal decision

   In this section I will put a little story of how I took my decision on what tool to use for my games.
   You still need to make your own decision, but I'm putting this here just as a reference with the
   hope that it may be useful information for someone trying to do the same, so here it goes:

   It all started in 1984 when I got a Commodore 64 home computer and programmed a game in
   Basic language... and....

   (...ok... let's move the story a little forward...)

   I know java so as a natural option that was my first choice, but decided to explore other languages
   first.
   I don't want to make "simple mini-games", I want to be able to do medium/big games. (of course I
   will make little games at the beginning).
   Flash/Action script was my first topic to review. I was able to create games quickly and easily. I am
   basically a tech guy (not an artist guy) so I had a hard time with the Flash IDE.
   I then tried another ActionScript IDE (FlashDevelop) and also tried another actionscript frameworks
   (Flixel, Away3D) with very good results. I was happy.
   Then dropped action script when I realized that multiplayer capabilities are very limited. TCP is
   available but I needed UDP connections. I found some Flash multiplayer games on internet, but
   they had very low performance when more than 5 users where connected at the same time.
   I want to create a multiplayer game, that is a very important goal for me, it is more important than
   showing very nice/high detailed graphics.
   So then I tried python.



The lucu guide for creating videogames                                                                    Page 23 of 87
   The Blender game engine got my attention, but currently (August 2010) the whole engine is being
   re-designed. Maybe I will have to wait for the new version to be available. I don't want to make my
   game with any "beta or alpha" tool.
   My next option was Panda3D game engine. I did some experiments and got good results. Very
   nice game engine and tutorials available. But I was never able to find a good Python IDE. Since I
   am a tech guy I don't need just a basic IDE for "writing code and compile", I demand a very high-
   quality IDE with many features like "debugging, profiling, .etc". As a programmer I have been
   spoiled with IDEs like Visual Studio and Eclipse and I wanted something at least "close" to them.
   I found some commercial Python IDEs that were very good, but were out of my budget :(
   I then discovered IronPython, which lets you code Python inside Visual Studio!.... but then found
   that Panda3D is not compatible with IronPython :(
   Also found out that Python lacks (or have but are limited for my goals) some "extra" tools I need,
   like: obfuscators, more profiling tools, installer generators.
   So I then turned to Unity 3D.
   Unity 3D is a very good game engine. But I discarded it because in order to run a multiplayer game
   you need a server component that runs a Windows server (or Mono over linux). My game project
   only has a plain linux (without mono) server so I had to discard this option.
   So, I returned to java.
   I was NOT going to code a game from ZERO, I had to choose an engine or framework.
   My first option was to use the Java Monkey Engine. But I found the documentation hard to
   understand and I believed it's better if I do some little game first... but... the Monkey Engine is for
   3D games... so I decided to start with something "more easy and just 2D".
   I then looked at GameMaker. Very good/easy/little framework for small 2D games. Liked it from the
   beginning... but discarded later because the multiplayer options would need to be coded as an
   extra DLL in C, Delphi or C++ ..... I know those languages but not much as to write a network
   communications module with them.
   Returning to java... I found two very nice 2D game engines: Slick and GTGE. I tried both and did
   some little games with them.... they are both good but finally I decided for GTGE because I liked it
   more (easier documentation for me, more examples available). I don't think one is better than the
   other, it's just that GTGE works best for me.
   So, for 2D games, I will go with GTGE.
   Now, for 3D games I found the Xith3D framework, which has easy documentation, lots of examples
   and I tried it a little bit and the demos work fine on my computer. I will make a 3D with this one in
   the future and expand this guide.

   So, the rest of this book is about how to make a small 2D game with java and later, how to make a
   3D one.

   One more thing: while I was doing all of this, I was looking at every
   book/review/magazine/conference about gaming I could find... if you look at Appendix A of this
   document you will find some of them.




The lucu guide for creating videogames                                                       Page 24 of 87
Chapter 3: Making a
2D game




The lucu guide for creating videogames   Page 25 of 87
Computer game flow

   Before we start to get our hands into actual code, there is one more piece of theory you need: the
   computer game flow.

   Whenever you play a game in a computer, this is basically what happens:


                                          START




                               Load resources into memory
                                 (sounds, images, maps,
                                      libraries, .etc)



                                Show initial menu/options.
                                        Example:
                                           -Start
                                         -Options
                                         -Credits
                                            -Exit




                                Render objects/graphics in
                                        screen.


                                Receive INPUT from user
                                (keybard, mouse, joystick,
                                          .etc)
                                    (User is playing!)


                                 Do internal game logic (if
                                 player is hit with a bullet
                               reduce life by 5 points...etc).
                               Decide what sounds/images
    Repeat until game           to take/put/move from the
    ends or user exits          screen based on logic and
          from game                        input.



                                  Re-paint objects, play
                                  sounds. Redraw game
                                        scenario.




                                           END




   You need to keep this in mind while developing a game; it is important to make a good design and
   will also let you know important topics like:




The lucu guide for creating videogames                                                   Page 26 of 87
            Loading resources (images, sounds, .etc) takes time and memory, so try to do it only
             ONCE at the beginning of the game.
            The complete game is re-drawn and re-displayed many times per second in the screen.
             After your game logic was executed, so try to make your game logic small and efficient to
             guarantee your game will run smooth and easy on the hardware. This is one of the reasons
             why many high-quality games (with very nice 3D graphics) are usually done in languages
             like C or C++ because they are very fast. But, at the same time hardware is getting faster
             and faster everyday (and other programming languages too)
            And most importantly: no game (or software) can be saved from a bad programmer :)



Setting up the development environment

   We will be using JAVA, the Eclipse IDE and the GTGE framework.

   If you want to use the SLICK framework I left in Appendix B (slick+eclipse) of this document a little
   help on how to set it up.

   This document can't teach you how to program in java, there are already many books available for
   that. If you do not know java stop reading this book, go learn java first (at least the basic steps),
   then come back.

   This document can't teach you how to use Eclipse IDE, there are already many books/tutorials
   available for that but even if you never used Eclipse before continue reading because it is very
   easy to learn.

   So, go to Appendix C (gtge+eclipse) of this document and prepare your PC.



Making a puzzle game with GTGE

   By now I assume you already have your development environment ready and you read the GTGE
   basic tutorial and ran an example game that comes with it.

   And be sure to have the GTGE API DOC near and handy, you will need it as a reference.

   In this section, I will guide you though the steps of making a small puzzle game with GTGE. You
   will not become a master in GTGE (or in gaming), but it will give you a guide so then you can
   create your own games.

   The program for this game is a single java file. But we will go "step by step" so I will present you
   many versions of the same program, from the bare basics up to the full game. If you are in a hurry
   rush and read the last version of the program... if you want to learn read it each version one by
   one.

   You can find each version (java program) of the puzzle where you got this document from, along
   with the graphics.

   Before we start, create a "source folder" called "puzzle" (if you have not done so already).

   Puzzle version 0: Why a puzzle? Design a puzzle.

   First, why a puzzle as a first example?. Well, because it is easy to code, it has no moving parts
   (animations) and requires few resources (any graphic will do)



The lucu guide for creating videogames                                                      Page 27 of 87
    About the design, we also have an advantage here: anybody knows how a puzzle works (you have
    a lot of pieces, now try to put them together to form a full image) so there is not thinking here left to
    do.
    We will be creating a puzzle of 8 x 8 (64 pieces). The player just needs to put each piece in the
    correct place to form the final picture.

    Puzzle version 1: just display a background

    Inside the "puzzle" folder, create a program called "PuzzleGame" inside a "puzzle" package and
    put the graphics inside a "resource" folder. Something like this:




    Copy "version 1" of the puzzle and run it, you should see a background on the screen:




    The 8 rows by 8 columns grid to the left will help the player understand where the final position of
    the pieces will be. Notice that this is a complete image, the grid is not "generated" by the code. Use
    any imaging software to create a background and add the grid on it.

    Notice also that the background has the same resolution (600x500 pixels) as the declared window
    for the game, in this line:

game.setup(new PuzzleGame(), new Dimension(600, 500), false);

    Also notice that we have the basic game flow in place already, we have a initial place to load
    resources here (and it will be executed ONLY ONCE by the computer):

public void initResources()
{
background = new ImageBackground(getImage("resource/background_forest.jpg"));
}

    We have a place for your game logic here:


The lucu guide for creating videogames                                                          Page 28 of 87
public void update(long elapsedTime) (...


   And a place were everything is re-displayed (rendered on screen) again:

public void render(Graphics2D g) (...

   So far nothing great is happening in our game, we are just displaying the background image... and
   displaying it again... and again... and again... many times per second. The GTGE engine takes
   care of that.

   Puzzle version 2: let's put the puzzle pieces on the screen

   Now put version 2 in the project and run it, you will see the pieces now:




   What we are doing is reading an image that has the complete image (completedPuzzle.jpg) then
   cutting that image into pieces (64 pieces) with the splitImages() method:

BufferedImage[] biarray = ImageUtil.splitImages(bi, 8, 8);

   That generates an array of BufferedImage objects (which are just images created from the original
   image)

   Then we create a sprite with each image and also put them like a deck/stack to the right of the
   screen with this code:

                   for (int i = 0; i < biarray.length; i++)
                   {
                         puzzlePieces[i] = new Sprite(biarray[i]);
                         puzzlePieces[i].setBackground(background);
                         puzzlePieces[i].setLocation(initX, initY);

   We create a sprite with each image because then it will be easier to manage (do operations like
   show, hide, move, rotate, .etc).




The lucu guide for creating videogames                                                  Page 29 of 87
   Also notice that we added in the render() and update() methods the necessary code so that the
   sprites get displayed and updated on the screen.

   Puzzle version 3: adding mouse functionality

   Now put version 3 on the project and run it... you will notice now that you can pick a puzzle piece
   and move it around. If you click again the mouse pointer will drop the piece and you can now pick
   another piece and mouse it around, it will just "follow" your mouse.

   How to accomplish this? Here is how:

   First, we need to let the program know that we want to listen to mouse events (clicking and moving)
   by implementing a listener:

public class PuzzleGame extends Game implements MouseListener

   Adding the necessary methods to capture the events:

public void mouseClicked(MouseEvent arg0)...
public void mouseMoved(MouseEvent arg0)...

   You only need to implement the methods for the events you are interested in. You will notice that in
   this game we only care when the player clicked a mouse button... so.... only the "mouseClicked"
   event has code inside.

   Then, you need to "register" the program as a valid one for listening to events, here is the code to
   do that:

public void initResources()
{
// do this to listen for mouse events
((AWTInput) bsInput).getComponent().addMouseListener(this);

   Very important note: the GTGE engine already has some methods you can re-use for listening for
   keyboard and/or mouse events. You can just re-use them instead, but, I am showing you this
   alternate method because it has one advantage: your game can respond to a mouse click
   ANYTIME. By that I mean that the method "mouseClicked()" will be executed any time the user
   clicks a button while the game is running so your game can immediately react to that and you as a
   programmer can have better control of your game and your game flow/design will go smoothly
   because the other alternative is to constantly ask the computer if a button was clicked (not very
   useful)... by using this method we go the other way: the computer will let us know when a button
   was clicked.

   The next important piece of code in this version you need to notice is the one that checks what
   piece (sprite) was clicked (if any). To do that we use the function checkPosMouse() whenever we
   click the mouse:

public void mouseClicked(MouseEvent arg0)
{
      if (selectedPiece >= 0)
      {
            selectedPiece = -1;
            return;
      }
// else, check if the mouse was clicked over one of the pieces
      for (int i = 0; i < puzzlePieces.length; i++)
      {
      if (checkPosMouse(puzzlePieces[i], false))


The lucu guide for creating videogames                                                    Page 30 of 87
                   {
                   selectedPiece = i;

   And... on the "game logic" section of the code, we make sure that selected piece is displayed
   where the mouse is. We use two functions (getMouseX/getMouseY) provided by GTGE to know
   the current mouse position for that:

public void update(long elapsedTime)
{
...
if (selectedPiece >= 0)
   puzzlePieces[selectedPiece].setLocation(getMouseX(), getMouseY());

   And that's how we can pick/drop/more the pieces around. But it is missing two little details that we
   will check on versions 4 and 5 coming next. I call them "human touches" because they make the
   game more "human friendly" (and when you do games this is a very important goal to achieve).

   Puzzle version 4: adding a little "human" touch

   Our little puzzle example here already has the functionality of a basic puzzle (move pieces around
   to try to form the complete figure), but you may have already noticed that is not easy to "aim" the
   pieces on the grid. It would be great if the pieces just "snap" into the grid, right? like in "real life
   puzzles", right?, well, with a little math and a little code added you have that functionality in version
   4 of the puzzle.

   Copy it to the project and run it, you will now notice two things:

        1. The piece follows the mouse, but it is not "centered" to the cursor (simulates your real life
           hand grabbing a real life piece)
        2. When you drop a piece it "snaps" to the closest cell (simulates a real life piece when it
           "snaps" to the rest of the puzzle)

   Isn't that nice? here are the two pieces of code that was enhanced from version 3 to accomplish
   this:

puzzlePieces[selectedPiece].setLocation(getMouseX() - 25, getMouseY() - 25);

   The "-25" offset just moves the piece to the center (because the pieces is 50x50 pixels)

   public void mouseClicked(MouseEvent arg0)
        {
                int theSelectedPiece;
                if (selectedPiece >= 0)
                {
                          theSelectedPiece = selectedPiece;
                          // if a piece is already selected, just unselect and return
                          selectedPiece = -1;

                      // before we drop the piece, we will auto-move it a little more
                      // just so it "snaps" into one of the cells of the grid
                      if (getMouseX() >= 3 && getMouseX() <= 403 && getMouseY() >= 3 &&
   getMouseY() <= 403)

   In this section of code, we just ask if the mouse is inside the grid boundaries, then search for the
   nearest cell and position the "recently dropped piece" there.

   One thing to notice is that we are using an extra variable here called "theSelectedPiece". You may
   consider it unnecessary since the variable "selectedPiece" already has that value and you can be

The lucu guide for creating videogames                                                         Page 31 of 87
   right, but I placed it for one reason: safety. You need to remember that the method "mouseClicked"
   can be executed and ANY time so I recommend you "free" the variable "selectedPiece" as soon as
   possible and just use a "copy" of it during the rest of the logic. When your game gets more complex
   you may have for example another method that rotates the selected piece when a key was pressed
   and you can bet that other method can also be executed at ANY time.

   Puzzle version 5: adding a button

   Our puzzle game needs one more extra feature before we can call it complete (for a "basic" game
   that is).

   Every puzzle (in real life puzzles that is) comes with a complete picture (in the box where the
   pieces came in) that shows you how the completed puzzle looks like. We will add that feature to
   your little java puzzle game.

   We will add a button that displays an image with the completed picture.

   Before we continue, download the "GUI add on" for GTGE and run the example it comes with to
   get familiar with that plugin for GTGE. You can just put the add on source next to the GTGE code,
   they have different package names so they will not mix with one another. If you get an error like
   "file not found" or "image or resource not found" when you run the GUI add on you may be missing
   the icon files, just put them here:




   So, copy version 5 into the project and run... you will notice now there is a button that when
   pressed, shows the complete figure. If you click anywhere on the screen you return to the puzzle
   window and can continue playing.

   Here is the code to make it happen:

   Code to add a new sprite (the complete picture) and notice that later on we do not display it
   immediately, but only the a flag is turned on:

                   fullPicture = new Sprite(getImage("img/full.jpg"));
                   fullPicture.setBackground(background);
                   fullPicture.setLocation(0, 0);

   Code to add a button to the screen:

TButton button1 = new TButton("show picture", 440, 280, 100, 40)

The lucu guide for creating videogames                                                   Page 32 of 87
{
public void doAction()
      {
      showFullPicture = true;
      }
};
frame = new FrameWork(bsInput, getWidth(), getHeight());
frame.add(button1);

   Notice that it just turns on (true) the flag to display the full picture, later on the "render()" method will
   take care of actually displaying it on screen.

   And the render part is here (we show the fullPicture sprite if the flag is on, we do not render
   anything else on screen otherwise and just "return"):

         public void render(Graphics2D g)
         {
               background.render(g);

                   if (showFullPicture)
                   {
                         fullPicture.render(g);
                         return;
                   }




The lucu guide for creating videogames                                                            Page 33 of 87
Chapter 4: Making a
2D multiplayer
game




The lucu guide for creating videogames   Page 34 of 87
   Some games can be played by more than one person at the same time and this creates a
   multiplayer game where many people compete (or collaborate) inside it. In this chapter we will
   explore the basics of how to achieve this.

   Multiplayer games are harder to create but if done well it is possible to create virtual worlds or
   massively multiplayer online games (MMO) were thousands of players can share a wonderful
   experience playing together.

        Tip       And don't forget that games are fun, but multiplayer games are even more fun!

       
Networking basics

   A network is a group of computers interconnected together in a way they can share resources (like
   printers, spaces, files). For our case they will share a common application: a game.

   When trying to achieve a multiplayer game there are different ways to connect these computers,
   but the two more popular are:

   Client/server method: This is probably the most used connection type for multiplayer games and
   is basically one (or many) computers working as "servers" and the players (clients) connect to one
   or many servers. One key thing to notice is: all information related to the game is controlled by one
   or more servers. If a player wants to send information to another player it must go though the
   server.




                                client-server connections



   Peer-to-peer method (also known as P2P): In this type of connection may or not have one or
   more servers, but the difference here is that players can connect to other players without the need
   of a server. Sharing software like kazaa, emule, napter made this type of connection very popular.




The lucu guide for creating videogames                                                      Page 35 of 87
                                  peer to peer connections

   Connection type comparison: to understand them better and decide which one to use for your
   game, let's compare them both.



                  Client-Server                                            P2P
                  Easier to secure because the server can                  Hard to secure because players are free to share data
  Security        manage/control all data traffic between players.         without "server supervision".

                  Slower because data MUST travel through the              Faster because direct "point to point" connections can
   Speed          server first before reaching the final destination.      be established.
                  Allows a better distribution of the game because
                                                                           Complexity grows as the numbers of players increases.
                  many central pieces of the game can just remain
Deployment        in the server and player only get "client" pieces of
                                                                           Game logic needs to be managed in all places the
                                                                           game is installed.
                  the game.

   As a recommendation it is a good idea to start with client-server games and only if you really need
   to use P2P then go for it. Many game design books even consider P2P as "evil" and that should
   never be used, but don't go to extremes and keep your mind open, it's good to know the tools in
   case you need them, for example here is a good use of P2P: imagine a multiplayer game where
   some players need to exchange data frequently and that data is not relevant for the game logic, for
   example they need to talk (exchange audio) to each other while they play, in this case the game
   could be client-server but may open a direct communication between some players for them to talk
   freely.

   Protocols: TCP or UDP The next decision to make is to use TCP or UDP as a protocol to transfer
   the information. TCP is slower but reliable (data is guaranteed to arrive at destination) while UDP is
   faster but unreliable (data may be lost). A quick look may discard UDP immediately but again it is
   important to know both options and use each one when needed. Here is a comparison to
   understand them:

                  TCP communication protocol                               UDP communication protocol
                                                                           Faster, but unreliable. This is useful to send data that is
                                                                           not very critical for the game and that changes very
                                                                           frequently. Example: chat between players.
                  Slower, but reliable. Useful to send critical data for
   Speed          the game like events and game logic data.                Also useful to send big amounts of data where a little
                                                                           loss of data is harmless. The best example of this is
                                                                           video. If there is one or two frames missing in the video
                                                                           transmission are not a big deal.




The lucu guide for creating videogames                                                                                Page 36 of 87
Game server

   The next step is to create a game server, which is the game logic that will control the game data
   traffic. Remember we discussed about game engines before? Many game engines offer
   networking/multiplayer capabilities out of the box so you don't have to worry about them. In this
   guide what we will do is use an existing networking software library called MINA to help us build a
   game server.

   So go ahead and download MINA ( http://mina.apache.org ) and install it and run the example
   called "chat server" which is perfect as an example of a basic client/server application, then read its
   documentation to get familiar with the technology used by MINA.


Puzzle game - multiplayer version

   Now let's re-design our puzzle game and turn it into a multiplayer puzzle. Here are the design
   considerations:

            The game will allow the player to type his name so that other player will know who entered
             the game session.
            The game will enforce collaboration, so, all players will work together to complete the
             puzzle. For this to happen, every time a player puts a piece on the board the game will
             notify other players about this event an update the screen to reflect the change.
            The final effect is as if all players are looking at the same table where a puzzle is being
             assembled (like in real life).

   Using the MINA libraries I created the multiplayer version of our little puzzle game we did before.
   The result is in the project "puzzle_multi", import it into Eclipse IDE and you should see something
   like this:




The lucu guide for creating videogames                                                       Page 37 of 87
   The server-network-logic of the game is inside the package "server".
   The client-network-logic of the game is inside the package "client".
   And the "puzzle" package contains our usual game, but is an enhanced version that uses the MINA
   libraries to communicate with the server.

   The programs used to handle communication logic have been taken from the "chat" example that
   comes with MINA, we just re-used them to allow our game logic to "chat" its logic. What this means
   in practice is that our puzzle game now has these features:

            Connect to a central server.
            Send information about the player (name and pieces moved)
            Receive information about other players (sent by other players and broadcasted by the
             game server)
            Communication will be done using standard sockets and TCP.

   Puzzle - Connection to a central server: This is achieved by using the MINA library to connect to a
   client. This logic is encapsulated inside the NetworkClient.java class, so from our game
   (PuzzleGame.java) we just establish the connection here:

// try to connect to the network
try
{
networkClient = new NetworkClient();
connectedToNetwork = networkClient.connect((Callback) PuzzleGame.this, "localhost:4444",
userName);
} catch (Exception e)
{
messageReceived("*network connection to server not available*");
networkClient = null;


The lucu guide for creating videogames                                                   Page 38 of 87
e.printStackTrace();
}

   We send the IP and port (socket) of the server we want to connect to (in this example the game
   server is in our local computer and the port is 4444).
   Notice that if for some reason there is no connection, we just log the error and allow the player to
   continue playing the game in "single-mode".

   The connectedToNetwork flag is very important because it will become "true" only if we are
   connected and we use it every time we place a piece on the board (method mouseClicked()) in
   this logic:

if (connectedToNetwork)
{
// also, notify any other players (in the network) that we
// placed
// one piece into the grid
StringBuffer sb = new StringBuffer();
sb.append("moved_a_piece").append(",").append(theSelectedPiece).append(",");
sb.append("to x").append(",").append(myPositionX).append(",");
sb.append("to y").append(",").append(myPositionY);
networkClient.broadcast(sb.toString());
}

   What we are doing in the previous piece of code is:

   When a user drops a piece on the grid...
   ...capture the piece number (id) and it's position (x and y coordinates).... and...
   ...send them to the server using the "broadcast" option... this means that we want to send this
   information to all players connected to the game.

   The server logic for this scenario is very simple: just receive this information and re-send
   (broadcast) it to all other players.

   In our game (PuzzleGame.java) class you will notice an new method that will listen for incoming
   network messages, it's job is to receive information from other players and update the screen
   putting the piece in the coordinates sent by other player(s):

public void messageReceived(String message)
        {
        // in this game, when we receive a message it could be that another user
        // is playing and we receive the information of the
        // piece he/she moved
// verify if it is a piece movement
if (message.indexOf("moved_a_piece") >= 0)
{
// another user moved a piece, let's move that piece in our own grid
// also
String[] data = convertLineIntoArray(message, ",");
puzzlePieces[Integer.parseInt(data[1])].setX(Integer.parseInt(data[3]));
puzzlePieces[Integer.parseInt(data[1])].setY(Integer.parseInt(data[5]));
}

   To make this game a simple example, the message that players exchange is just a simple String.
   You will notice that when a network message is related to a player move it contains the text
   "moved_a_piece". It is important to notice this because there are other network messages as well
   with different information (example: player connected, player disconnected, number of players
   connected, .etc) so your game logic needs to understand them and do some logic based on them.
   For our humble puzzle game we just display any network message in a textbox at the bottom of the
   screen.

   After this overview, go ahead and run the multiplayer version of the puzzle. First run the game
   server (server.Main.java) then two or more clients and see it in action. Make sure you use the


The lucu guide for creating videogames                                                    Page 39 of 87
   same port in both the server and the client and that you put the correct server IP address in the
   client code. Here is a screenshot of the game running in multiplayer mode:




The lucu guide for creating videogames                                                  Page 40 of 87
Chapter 5: 3D
games




The lucu guide for creating videogames   Page 41 of 87
   Making a 3D game adds extra an extra dimension to our game creation process, not just in the
   sense of coordinates in space but in extra considerations and designs to apply. Here is a
   comparison of topics you need to think about:


                   Making a 2D game                                   Making a 3D game
                                                                      Always consider performance as a constraint. And
                                                                      keep in mind that not everybody will have enough
                                                                      hardware to display the pretty 3D graphics you
                   No need to worry much, just maybe the quantity
                                                                      created.
Performance        of sprites on the screen, but today's hardware
                   can handle pretty complex designs.
                                                                      Usually the best 3D games are created using more
                                                                      "lower" level languages like C++ to gain extra
                                                                      performance.
   Visual                                                             Harder to create great visual effects but when done
                   You can create great visual effects "easily"
                                                                      right the result can create impressive virtual 3D
   effects         (compared to 3D).
                                                                      worlds/games.
                                                                      For 3D you will need 3D graphical resources that are
                                                                      more complex to create and require 3D software like
                                                                      3ds max or Blender.
                   2D graphical resources are vector or bitmap
   Assets          images like .jpg, .svg, .png...
                                                                      The scenarios, maps or "levels" of your games may
                                                                      also need to be created with special 3D software or 3D
                                                                      terrain software.


        Tip       If you are new to 3D creation (games or in general) It is strongly recommended that
                  you first use a 3D engine like Unity or DX studio or Blender Game Engine to help you
                 in the process and avoid programming. This is because you first need to understand
                  and "think in 3D" before you can "program in 3D". This means you need to first get
                  comfortable with topics like: 3D coordinates, Vectors, Spaces, Volumes, .etc.

   In this chapter we will create a 3D game with the help of the Xith3D engine, so first please go to
   Appendix D to learn how to setup Xith3D in your development environment and make sure you run
   the examples that come with the engine and look at the code to get familiar with it.

3D basics

   Before we do our game we need to get familiar with some 3D concepts first.

   3D objects: This can be any resource created by special 3D software (like 3ds max/Blender) and
   usually have the extensions: 3ds, max, obj, etc. They can represent game characters and in those
   cases they are often animated and have the extension: md2, dae, etc.

   The "obj" 3d file format is very popular and almost all 3D software is able to read/write it.




                                         Example of 3D objects you can use in your game




The lucu guide for creating videogames                                                                       Page 42 of 87
   The "md2" file format is very popular for animated characters. The game Quake made it very
   popular and you can find many websites that allow you to download md2 files for fun/free. But keep
   in mind that this format is old and the animation it provides is "keyframed/predefined" animations
   and not "skeletal animation" so it is a good format to start but I recommend you study more
   advanced formats like md3 or .X format for game characters.




          Example of an MD2 game character. Notice the list of "pre-defined" animations on the right. You can "activate"
                         any of them during the game depending on what you want the character to do.



   Skeletal animation and why you should care: We will use md2 (keyframe animation) files in this
   guide because they are easy to find and use, but, as soon as you can try to learn about 3d game
   character formats that support "skeletal" animations (like collada DAE, .X format, etc) because they
   are better and allow you to move independent movement of the game character parts (arms, legs,
   head, etc) and help to create more realistic in-game animations.

   3D levels: The scenario your game will work on can be "just" another 3d object like .obj or .dae or
   .3ds, but there are special tools for building more complex scenarios and create "levels" like Quake
   map (.bsp files) or "terrain files" like the ones created with L3DT ( http://www.bundysoft.com/L3DT
   ).

   Scenegraph: To manage and display all the 3d objects of your game, the engine will provide us a
   scenegraph, which basically is the "stage" or "3d space" where we will put our objects. These
   objects do not "float freely" around but will follow a hierarchy for easier management and also
   because some objects actually depend on other objects, just like in real life 3d. Here is an example
   to illustrate this:

   A car has wheels. Wheels are objects that belong to a "parent" object called car. If your game has
   a car and you move it around it is expected that the wheels will be moved as wheel to a new



The lucu guide for creating videogames                                                                       Page 43 of 87
   position accordingly. When the car is moving forward the wheels need to rotate, but always in a
   position relative to the car.

   Please look at appendix E (Xith3D Scenegraph) later in this document for a diagram of Xith3D's
   scenegraph.

   3d objects (also called "3d shapes") are in the lower part of the chain. They can be grouped
   together. In the previous example the car may be composed of four "3d shapes" (the wheels) and a
   big "3d shape" (the car itself).

   This grouping affects not just "position" of objects but also to other attributes like: rotation, light, etc.
   So objects belonging to the same group (also called "Transformation group") are affected by the
   same attributes.

   All objects (grouped or not) are then attached to a RendererPass who keeps and manages a sub
   graph, which is processed and rendered by the Renderer. It also implicitly defines the rendering
   order. This is important because on 3d games you don't just render all objects in the screen, the
   engine must first calculate which objects are visible to the player and only render those. There are
   some tricky mathematics involved to calculate this but luckily the engine (in our case Xith3D) will
   take care of those details.

   There is a special object called "view" which represents what the player can see or view according
   to his/her position in the 3d world of the game. This "view" object has its own coordinates (x,y,z)
   and a direction represented by a vector in the 3d world. Also, the "view" needs a third vector to be
   fully defined, the up vector, plus a screen scale, which is better known as the vertical field of view
   (FOV).

   Usually the "player view" is also used as a holder for the "HUD" (heads up display) which is nothing
   but a semi-transparent 2d window that shows useful information to the player during the game.
   Data like "points of life" and "game score" are common to be displayed in the HUD.

   Now we are going to put all these concepts together in an actual game so you can better
   understand how they are applied, look at the following in-game screenshot:




The lucu guide for creating videogames                                                            Page 44 of 87
In-game screenshot showing a 3d object (MD2 file) attached to a bigger 3d object (the BSP map) rendered all together in a Xith3D environment that also has a player view object
attached, and everything nicely managed by the Xith3D engine:
Chapter 6: Making a
3D game
   The previous chapter was an introduction to 3D and Xith3D, now we will start to code our 3d game.
   The design is going to be simple because our main objective here is to learn about games, not
   creating a new hit.

   Design of the game: The player is inside a 3D maze and needs to find apples. To "motivate" the
   player to do this there will be a timer (player's energy) that will decrease with time. To "stay alive"
   the player must find apples and "eat" them. To "eat" and apple the player needs to find one in the
   maze and click on it. The name of the game is "Apple Chase".

        Tip       When designing your game always put a little "challenge" for the player, that creates fun and emotion.
        

   Go ahead and play the game, it's the program AppleChase.java inside the "apple_chase" java
   project. Play it a couple of time to get the feel of what we will build. Here is an screenshot of the
   game:




          In-game screenshot of the finished version of "Apple Chase", the game we will be learning to do in this chapter.
                               Notice the apple "floating" around and crosshair "trying to catch it".

   So, let's get started. We will cover the process step by step (step ZERO was of course the design).
   The final version of the java code is included by default in the package, so after you are done
   playing with the finished version, erase the code and replace it with the source code that is inside
   the folders "appe_steps/step_x", depending on the step described next. In each step I will show
   you the key java code you need to add to the previous step to build your game. At any time you
   can use any software to compare any step with the previous step to get the full detail of what was
   changed.

        Tip       Use any software tool to compare source code, like Araxis, WinDiff, KDiff, etc.
        

   WARNING BEFORE WE BEGIN: Don't forget to read the previous chapter and also Xith3D's own
   documentation before going forward. I will assume you already did that.




The lucu guide for creating videogames                                                                          Page 47 of 87
Step 1: Prepare an empty screen

   Our main java class "AppleChase.java" is born! The basic configuration topics you need to create a
   game with Xith3D are:

            Our game is a simple example, so for now make it extend InputAdapterRenderLoop, this
             will provide you access to a rendering framework and access to the input (keyboard)
             system plus other engine internals. But on a later chapter of this guide we will see that for
             real games you should actually make your game extend from RenderLoop only.
            The main method is "main()" and it just creates and instance of the game and calls the very
             important method begin():

         public static void main(String[] args)
         {
                    try
                    {
                              // Read parameters from configuration file
                              float maxFramesPerSecond = Parameters.getInstance().getMaxFPS();

                             // Load and Initialize the game
                             AppleChase game = new AppleChase(maxFramesPerSecond);

                             // Start the game!
                             game.begin();

            The begin() method of course starts the game and also the very important "game render
             loop" where your game needs to do its logic and decide what to show/hide or do
             (remember the "computer game flow" from chapter 3?)
            You will notice that we setup video modes/resolution and register the program to listen for
             keyboard and mouse events in the constructor method:
   public AppleChase(float framesPerSecond) throws Exception
          {
                  super(framesPerSecond);

                   int wx, wy;
                   // setup visual 3D environment
                   Xith3D3DEnvironment env = new Xith3D3DEnvironment(this);
   ...

   ...
                             canvas = Canvas3DFactory.createWindowed(wx, wy, "Apple Chase");
   ...
                   // register the game in the Input System to be able
                   // to responde to keyboard events
                   InputSystem.getInstance().registerNewKeyboardAndMouse(canvas.getPeer());

            Our game will listen to keyboard and mouse events. The very first event we need to
             capture is that if the user presses "ESC" the game will end:

         public void onKeyPressed(KeyPressedEvent e, Key key)
         {
                    switch (key.getKeyID())
                    {
                    case ESCAPE:
                              this.end();

            You will notice there is a game_config.properties file. It is an optional (but nice) thing to
             have because players like to choose screen modes/resolutions (among other things) so it
             is a little extra thing I added for your consideration. The "Parameters.java" class already
             takes care of reading that file and providing the parameters to our game logic.
            If you execute this code you will just get an empty screen that does nothing. And you can
             close it by pressing "ESC".


The lucu guide for creating videogames                                                           Page 48 of 87
Step 2: Loading a map

            Now replace the code with the one from the folder "step_2". The new feature here is that
             we now have a "level" or "map" or "3d scenario", however you want to call it. In 3d games
             usually maps are created with a 3d software (3ds max, Blender, terrain generators, etc)
             and in our game we just reuse an existing "bsp" map used in games like quake.
            You can easily find many "bsp" map files on the internet. You will also find tutorials and
             software on how to create them.
            Xith3D provides a "BSP loader" so we just invoke it to load our map:
         private void loadLevel(SceneGraph sceneGraph) throws Exception
         {
                    Model scene = ModelLoader.getInstance().loadModel(resLoc.getResource("map/tall/tallrazz.bsp"));

            Notice that it is important to also set the initial "point of view" for the player in space, you do
             this with two values, one for the point of view itself and another to define the vector
             (direction to look at):
         // set the view position and focus
         env.getView().lookAlong(-13.3f, 3.5f, -2f, 1f, 0f, 0f);

   One nice detail about BSP map files is that you can set up "starting places" where the player can
   start, in our case we will just start in position "2", but feel free to experiment other positions:
sceneGraph.getView().getTransform().set( scene.getSpawnTransform( 2 ) );



            Run the code so far and you should see something like this:




                                                  BSP 3d map file loaded into our game.



Step 3: Moving around the map

            Xith3D provides a helper class to easily create a "first person view" experience:
FirstPersonInputHandler    firstPersonHandler     =    new    FirstPersonInputHandler(    env.getView(),   canvas,     1.0f,   1.0f,
mouseYInverted, 1.0f );

            Notice that every time we add a new feature (the map, this firstpersonhandler object...) to
             our game we "attach it" to the environment object "env".
            The default keys to move around are "WSAD", run the code and "move around" the map.
             The mouse has been also activated so you can change direction with the mouse. This is a
             good time to realize how easy is to travel inside a 3d virtual world if you use an engine like
             Xith3D, it is not a good idea to "start from ZERO" to make a game.
            You will notice that you can "walk through" walls. That's because we have not yet added
             any validation about collisions.



The lucu guide for creating videogames                                                                               Page 49 of 87
Step 4: Checking collisions

              To handle collisions we need a physics engine. Xith3D comes with the JOODE for that:
                     // now activate collisions. We need a physics engine to manage that.
                     PhysicsEngine physEngine = new JoodePhysicsEngine();
                     env.setPhysicsEngine(physEngine);
                     collEngine = physEngine.getCollisionEngine();

              Don't forget to notice the gravity applied as a force pulling the player down (negative Y
               axis):
world.setGravity(0f, -9.81f, 0f); // gRAVITy is a negative for in the Y axis

              The "3d map" we loaded is converted into a group of "collideable" objects, then the
               firstPersonHandler object will check if it is "touching" any of those objects:
    //activate collisions of player versus the world
    //notice how the MAP is transformed into a group of objects we can collide with (collideableGroup)
    CollideableGroup levelCollGroup = ( clusterManager != null ) ? clusterManager.getCollideableGroup() :
    null;firstPersonHandler.getPhysicsObject().setSlidingColliderCheckCallback(                physEngine.getCollisionEngine(),
    levelCollGroup );

              Run the game now, and you will notice you no longer can walk through walls.

Step 5: Adding the apple

              Now we will add a 3d object into the scenery. It is a ".obj" 3d object that you can create
               with any 3d software (3ds max, Blender, etc...) or you can buy it. The ".obj" format was
               chosen because Xith3D provides a loader for it and also because that format is very
               popular and is supported by almost any 3d software.
              This is the relevant code for this:
                     Model apple = ModelLoader.getInstance().loadModel(resLoc.getResource("apple2.obj"));

              Now, we need to add the apple to the MAP, we do not add it to the scene/environment.
               This is because, during rendering, the apple needs to be "inside" the map, not "outside" of
               it.
              Notice also that we use a helper class called "Transform". This is very important because
               that will allow us to move, rotate or resize the apple later on in the game:
                     Transform appleT = new Transform();
                     appleT.addChild(apple);
                     appleT.addScale(0.9f); // re-size the apple.
                     appleT.addChild(new AmbientLight(Colorf.WHITE));// attach a light on the
                     StaticTransform.translate(appleT, 0f, 60f, 0f);
    ...
                     scene.addChild(appleT);

              We are following Xith3D's scenegraph laws here: we attach a 3d object to a Transform,
               then we attach the "Transform" (appleT) to another 3d object (the map) then that map is
               attached to the "main" scenery, which is the Xith3D environment.
              If you run the code you will just see an apple added to the map:




The lucu guide for creating videogames                                                                           Page 50 of 87
                                              3d object (apple) added to the scene.


            Important note: In the previous section of code we used the StaticTransform class in an
             incorrect way because we are using two classes (Transform and StaticTransform) when
             only one should be used. We did this just for testing purposes. You will notice that the final
             version of the game only uses Transform to manage rotations, position and scale.

Step 6: Game Loop

            We will now start to make things more interesting. We will make the apple move around
             the map by using the very important "game loop" Xith3D provides.
            The goal is this: change the position of the apple in time, by changing its position in space
             (x,y,z).
            To achieve this, we override the method "prepareNextFrame()" in our game. This method
             is constantly being called inside the "game loop" so it is a valid place to place "game logic"
             or prepare 3d objects just before they will be rendered on screen.
            In our case, what we do is re-calculate the position of the apple every 5000 microseconds,
             this will give the appearance that the apple is "moving" (basic animation procedure).
            Here is the important piece of code for this:
   @Override
       protected void prepareNextFrame(long gameTime, long frameTime, TimingMode timingMode)
       {
                 super.prepareNextFrame(gameTime, frameTime, timingMode);

                   micros = timingMode.getMicroSeconds(gameTime);

                   // change the animation every 5000 microseconds
                   if ((micros - animTime) >= 5000L)
                   {
                               animTime = micros;

                             // let's rotate the apple
                             // appleT.addRotationY(0.01f);
                             appleT.addRotationZ(0.04f);

                             // let's make it move across the map
                             appleY = appleY + 0.03f;
                             if (appleY >= 60f)
                                         appleY = 0f;
                             appleX = FastMath.sin(appleY) * 10 + 7;
                             appleT.setPosition(appleX, appleY, 0f);
                   }
         }

            The "FastMath.sin()" function is used to make the apple move doing "curves". Review your
             basic trigonometry books to understand this.




The lucu guide for creating videogames                                                         Page 51 of 87
        Tip      Making a game (specially a 3d game) requires skills beyond just "programming" so make sure
                you learn your basic physics, trigonometry, modeling, arts, and pretty much a little bit of
                 everything you can to get your mind better prepared for the challenge.

                 Now, to help you a little with the "sin()" function used in this game, here is a graphic what will
                 "remind" you (because you already knew this from high school, right?) what happens when you
                 "draw" a line in 2D using the sin() function:




             Notice that we rotate and move the "Transform" class, which has the apple object inside.
             Run the program and you will see the apple moving doing "curves" in space and traveling
              from the bottom of the map all the way to the top.
             Another feature we added in this step is a "HUD" with just a crosshair (which is a JPG):
         // add a HUD with a crosshair
                   HUD hud = new HUD(canvas, 800f);
                   hud.setCrosshair("CrosshairWhite.png");
                   env.addHUD(hud);

             If you are wondering how I came up with the values: "0.03f" or "0.04f" or 5000
              microseconds to move and rotate the apple, the answer is: pure experimentation and fun! I
              just tested/played the game with different settings until I found one that is "playable" (not
              too easy + not too hard = fun!).


        Tip       Another option to manage your game logic(instead of overriding the prepareNestFrame method)
                  is to implement the Updatable interface. This is more useful as your game gets bigger and you
                 need to add more code.


Step 7: Final version of the game

             Now we will add details to make this more like a real game. We will add these features:

                      Use intervals to do game logic every "x" seconds.
                      Add the feature to "pick" objects in 3D space (needed to "pick" the apples)
                      Add info to the HUD: apple count and energy (as per the game design)
                      Make the apples "harder to catch" by tweaking the way the move in the map (to
                       make the game more "challenging")

             To review the final version of the game, just restore the code that came originally in the
              "apple_chase" project folder.


The lucu guide for creating videogames                                                               Page 52 of 87
             First, you will notice that the prepareNextFrame() is gone. This is just to show you another
              way of making your game do things every "x" time (intervals). But don't forget the
              prepareNextFrame() method because it is another tool for you available to use.
             To work with intervals, we add the IntervalListener interface. We will be adding "Picks" to
              the game so we also add the interface PickListener:
public class AppleChase extends InputAdapterRenderLoop implements PickListener, IntervalListener

             Two intervals are needed, one to move the apple, another to reduce the energy level of the
              player. Then the method "onIntervalHit" is added to tell Xith3D what to every time the time
              interval is reached:
   this.getOperationScheduler().addInterval(new Interval(20000L, "energyInterval"));

   // add an interval to move the apple
   this.getOperationScheduler().addInterval(new Interval(7000L, "appleInterval"));
   this.getOperationScheduler().addIntervalListener(this);

   .....
   public void onIntervalHit(Interval arg0, long arg1, long arg2, TimingMode arg3)

             The "picking" part is done like this: the engine casts a ray , which doesn't have a width and
              checks for intersection with shapes, in our case, if it intersects with any of the shapes of
              the apple 3d .obj object we loaded. The final effect "looks like" if the game is checking if the
              apple object is inside the player's crosshair (HUD). This validation is triggered when the
              "pickNearest" method is invoked after the player pressed the mouse button.
             If that condition is met, then the method "onObjectPicked" will be triggered by the Xith3D
              engine and you can do the game logic required (like adding +1 to the appleCount):
          @Override
          public void onMouseButtonPressed(MouseButtonPressedEvent e, MouseButton button)
          {
                     if (button == MouseButtons.LEFT_BUTTON)
                     {
                                 // note: we pick here the "appleT" object because that is the only
                                 // object we are
                                 // interesting in checking for "picking"
                                 pickScheder.pickNearest(appleT, e.getButton(), canvas.getWidth() / 2, canvas.getHeight() / 2,
                     }
          }

   ....

          public void onObjectPicked(PickResult arg0, Object arg1, long arg2)
          {
                     // you just picked an apple!
                     appleCount++;

             The "picking" is obtained by checking if the apple object was inside the player's crosshair
              (HUD) using the "pickNearest" method when the mouse button was pressed. If that
              condition is met, then the method "onObjectPicked" will be triggered by the Xith3D engine
              and you can do the game logic required (like adding +1 to the appleCount):
             Every time the player "picks" and apple, the energy counter is restored to 1000 points
              again. If energy goes below ZERO the game ends. This will "push" the player to keep on
              looking for apples otherwise the game will end:
          public void onObjectPicked(PickResult arg0, Object arg1, long arg2)
          {
                     // you just picked an apple!
                     appleCount++;
                     scoreLabel.setText("Apples : " + appleCount); //update HUD display

                    // energy is restored!
                    energy = 1000;
   ....
          public void onIntervalHit(Interval arg0, long arg1, long arg2, TimingMode arg3)
          {
                     if (arg0.getName().equals("energyInterval"))
                     {


The lucu guide for creating videogames                                                                            Page 53 of 87
                             energy--;
                             // if energy is too low the game ends
                             if (energy <= 0)
                             {
                                         System.out.println("game over!, you got : "+appleCount+" apples");
                                         this.end();

   And that's it! Run and have fun with this little example game. Hope you learned the basics of
   creating a 3d game with the Xith3D engine that will allow you to experiment and create your own.
   The basic concepts used here (scenegraph, vectors, views, loaders) are often used by many 3D
   game engines so even if you don't want to use java or Xith3D you should be able to use these
   concepts with another language or engine.

        Tip       Another way to use Intervals is to simply extend the onIntervalHit() method in an Interval
                  extension instead of using the listener approach.
        

   In the next chapters we will learn how to add multiplayer to this game.




The lucu guide for creating videogames                                                                        Page 54 of 87
Chapter 7: Making a
2D multiplayer
game - version 2




The lucu guide for creating videogames   Page 55 of 87
   An old expression says: "the tiger retreats only with the intention to jump higher". And now it is our
   turn to go a few steps back for a moment, but for good reasons as you will see. Before we start
   coding our 3D multiplayer game we need to revisit our little 2D puzzle game we created in a
   previous chapter because there is one topic we have not covered yet: UDP. Also, this will give us
   the opportunity to better understand the network layer required for multiplayer. If done correctly
   later adding multiplayer capabilities to our 3D apple chase game (or any game) will be much
   easier. So let's get started.


A better network library

   Our first step is to replace MINA version 1.7 with the improved MINA version 2 that is now ready to
   use. Our friends at Apache have created a link with information of what changed between the new
   and the old version ( http://mina.apache.org/changes-between-2x-and-1x.html ), but for our own
   purposes the key difference is: the new version has better performance.

   We will also enhance our "network layer" design so it is more reusable in any game you want, not
   just the games of this document. We will call this layer the "ummi" layer (just to give it a name) and
   here is the new design:



                                 Your game
                                                                               UDP messages
                                                                TCP messages




                                 ummi network library

                                 MINA



                                                    Network
              Your game can use the ummi library ( which in turns uses MINA ) to send/receive TCP/UDP messages to the
                                                              network.

   The key point here is: Using MINA is great, but we need a layer that "hides/encapsulates" MINA's
   own complexities in a way that we can easily add multiplayer capabilities to any game. So the
   "ummi" library is born.

        Tip        The MINA library is very powerful, be sure to check its website ( http://mina.apache.org ) to read about real
                  uses of it to get an idea of what it can do.

                   Just to add more good examples of MINA in real life: there are some commercial gaming network libraries (
                   like ElectroServer ) that use MINA internally.




Why UDP?

   We will change two things to our puzzle game, the fist one is do an upgrade to MINA v2 (with the
   help of the ummi API) and the other one is add the ability to send UDP network messages. As you
   may recall from a previous chapter, UDP messages are fast but not guaranteed to arrive at the
   destination, this type of message suits perfect in our puzzle game to add one extra game feature:
   make the pieces move "in real time" on the player's screen at the same time another players are
   moving that piece on their own computers. The current version of the puzzle just "puts" the piece at
   whatever place the other players "dropped" it.


The lucu guide for creating videogames                                                                           Page 56 of 87
    Adding this "movement" of the piece will add an extra "human" touch to the game, to make it more
    realistic and a little more fun to play.

    UDP messages are used for scenarios like these because:

         1. Moving a piece (or a player) around the game generates a lot of info (many coordinates
            changing frequently as the piece or the player moves) during a lot of time ( players move
            constantly ). This means we need to send a lot of data (and fast!) across the network to
            update other players of the changes the others players are doing.
         2. It is not critical if one movement gets lost in network traffic because the player (or piece)
            keeps moving and will send a new updated coordinate again, so new data is always
            coming to update the old one, or replace the missing one.

    This is of course not the only case, it is up to you to decide when you need to use TCP or UDP
    while designing your game, so it is good to have them both available as options.

         Tip        Just to make the learning process easier in this guide, we will use simple text messages with UDP, but to
                   increase performance you may want to try binary (or any smaller type) messages with UDP. Check MINA's
                    documentation on how to do this.




Adding the ummi network library to the puzzle game

    Inside the source code you will notice the java project "ummi_network". It provides a set of classes
    that will allow us to send/receive network messages (TCP or UDP).

    From your game client code you use the class ClientConnection.java for this. And from your game
    server code you use the class GameServer.java. We will show how to use them by adding them
    into our puzzle game.

    The game server side

    Look at the source code of the project "puzzle_multi_v2_server"
    Notice the file server.properties, it has properties where you can enable/disable TCP or UDP
    communications and what port you want to use for them.
    Now look at the file Server.java, it is used just to start the game server (provided by the ummi
    library) in three simple steps: create a new instance of the game server, start the TCP listener, and
    start the UDP listener:

                                   GameServer gs = new GameServer();
                                   gs.startTCPServer();
                                   gs.startUDPServer();

    If you run the server you will this output showing your game server is ready:

2010-11-03 12:10:08,343 INFO   [main] org.ummi.network.server.GameServer_startTCPServer: starting TCP server
2010-11-03 12:10:08,484 INFO   [main] org.ummi.network.server.GameServer_startTCPServer: TCP server Listening on port 5555
2010-11-03 12:10:08,484 INFO   [main] org.ummi.network.server.GameServer_startUDPServer: starting UDP server
2010-11-03 12:10:08,500 INFO   [main] org.ummi.network.server.GameServer_startUDPServer: UDP server Listening on port 8888

    The game client side

    Now look at the source code of the project "puzzle_multi_v2_client"
    This is the new version of the game, now with UDP and the ummi library.
    Notice the ummi_network_client.jar added to the classpath of the project.
    Now let's study the PuzzleGame.java class to understand the necessary changes.



The lucu guide for creating videogames                                                                                       Page 57 of 87
   First, notice how the class now implements two interfaces, these is needed so that the game can
   "listen" for incoming TCP or UDP messages:

public class PuzzleGame extends Game implements MouseListener, MouseMotionListener,
TCPConnector, UDPConnector

   Also notice that we added the MouseMotionListener interface, this is needed so that the game can
   "detect" when the mouse is moving.
   We then need to register the game as a listener for mouse moving events:
                // do this to listen for mouse events
                ((AWTInput) bsInput).getComponent().addMouseListener(this);
                ((AWTInput) bsInput).getComponent().addMouseMotionListener(this);

   Now the connection to the game server is established by calling two methods (one for TCP,
   another for UDP):

   public void initResources()
           {
   ...
   // try to connect to the TCP network
   connectedToNetwork = networkClient.connectTCP(PuzzleGame.this, "localhost:5555", userName);
   ...
   // try to connect to the UDP network
   connectedToNetworkUDP = networkClient.connectUDP(PuzzleGame.this, "localhost:8888", userName);

   You must, of course, use the same ports where the game server is "listening" to incoming
   connections. Ports 5555 for TCP and 8888 for UDP in our example.

   Now we will add the game logic, in the mouseMoved() method, to send our mouse pointer
   coordinates to the other players, as we move around a puzzle piece over the screen:

         public void mouseMoved(MouseEvent e)
         {
                 if (selectedPiece >= 0)
                 {
                           if (connectedToNetworkUDP)
                           {
                                    // also, notify any other players (in the network) that we
                                    // are moving a piece
                                    StringBuffer sb = new StringBuffer();

         sb.append("moved_a_piece").append(",").append(selectedPiece).append(",");
                              sb.append("to x").append(",").append(getMouseX()).append(",");
                              sb.append("to y").append(",").append(getMouseY());
                              networkClient.broadcastUDP(sb.toString());
                       }
                }

         }

   One more piece of coding is needed, the one that "receives" incoming UDP messages from other
   players and updates the position of the pieces in the screen:

         public void messageReceivedUDP(String message)
         {
                 // in this game, when we receive a message it could be that another user
                 // is playing and we receive the information of the
                 // piece he/she moved



The lucu guide for creating videogames                                                              Page 58 of 87
                   // verify if it is a piece movement
                   if (message.indexOf("moved_a_piece") >= 0)
                   {
                             // another user moved a piece, let's move that piece in our own grid
                             // also
                             String[] data = convertLineIntoArray(message, ",");
                             puzzlePieces[Integer.parseInt(data[1])].setX(Integer.parseInt(data[3]));
                             puzzlePieces[Integer.parseInt(data[1])].setY(Integer.parseInt(data[5]));
                   }

         }

   And that's it! you can run the example and you will notice that when another player moves a piece
   you will get an update "in real time" as he moves the piece around. Now you can reuse this
   technology (even better: improve it!) to add multiplayer features to your own games.

   The flexibility of MINA

   There is one more thing you need to notice: the ummi library provides you two interfaces
   (TCPConnector.java and UDPConnector.java) for you to use depending on your gaming needs, if
   you are curious enough (and you should) to look at their source codes, you will notice that they are
   almost identical, in fact, if you review the TCP and UDP handler programs also
   (TCPCommunicationsHandlerAdapter.java and UDPCommunicationsHandlerAdapter.java) they
   will also look nearly identical. So what is the difference? Well, thanks to MINA it is easy to use one
   or the other, just by changing the type of network connection we use, and you can see in this next
   section of code in ClientConnection.java:

   public class ClientConnection implements CommunicationConstants
   {
   ...
        // TCP communications
        private NioSocketConnector connectorTCP = null;
   ...
        // UDP communications
        private NioDatagramConnector connectorUDP = null;
   ...
        public boolean connectUDP(UDPConnector udpConnector, String host, String userName)
        {
                        connectorUDP = new NioDatagramConnector();
   ...
        public boolean connectTCP(TCPConnector tcpConnector, String host, String userName)
        {
                        connectorTCP = new NioSocketConnector();


        Tip       Once again, this document is showing you just a little example of what MINA can do, be sure to
                 study more about MINA, and if you use more of its functionality try to encapsulate it inside a layer
                  (like the ummi layer) so that you can reuse and reuse all those features in many games easily.


   With this section complete, now let's add multiplayer abilities to our 3D game (apple chase) in the
   next chapter.




The lucu guide for creating videogames                                                                  Page 59 of 87
Chapter 8: Making a
3D multiplayer
game




The lucu guide for creating videogames   Page 60 of 87
Apple Chase - multiplayer design

   Since we already covered topic like network, TCP, UDP, MINA in previous chapters, we can
   concentrate our attention in more details of our game. We will propose new design considerations
   for the game "apple chase" multiplayer edition:

            The game is competitive. Players must find apples to survive.
            Only one apple is available at a given time, the player who catches it first gets its energy
             refilled.
            To reduce network bandwidth, all files and maps will be already installed on the player
             computers.
            To reduce network bandwidth, the game server will only send the apple initial position and
             projected travel path to the game clients, which in turn will render and display the apples
             with local computations. No need to "constantly" send the apple coordinates to all players.
            The position of the players changes constantly and will be sent using UDP to all game
             clients so they can update locally the display. This is the only communication that will use
             UDP, all other game information will travel using TCP.
            Players can enter/exit the game at any time.
            The score is based on the number of apples a player can catch, the higher the better.
            The score will be displayed for all players to watch.

Making some improvements to our 3D game

   First, we will remove the PickScheduler object and instead use PickingLibrary. When we are
   validating the picking we are already inside the Xith3D rendering thread so it makes more sense to
   use the PickingLibrary for a direct test instead of "scheduling" a test. The change is applied in this
   section:
   public void onMouseButtonPressed(MouseButtonPressedEvent e, MouseButton button)
   {
   .....
   PickingLibrary.pickNearest(appleT, canvas, e.getButton(), canvas.getWidth() / 2, canvas.getHeight() / 2, this);

   Second, we will separate the input logic in another package (org.applechase.input) to organize
   better our game code. As your game grows bigger it is best to separate its logic into different
   classes/packages.

   If you look at that new package ( org.applechase.input ) you will notice we added two classes there
   to manage keyboard and mouse input. The logic inside those classes is the same that previously
   was inside the main AppleChase.java class.

   Next we need to change the class we extend from. You may remember that in the first version of
   the apple chase game we extended our main class from InputAdapterRenderLoop, but extending
   from that class is recommended only for testings/demos. Now we are going to extend from
   RenderLoop:

public class AppleChase extends RenderLoop ...

   Then we need to register the new input managers inside AppleChase.java:

                   //register our keyboard input manager
                   ListenKeyboard lk = new ListenKeyboard(this);
                   InputSystem.getInstance().getKeyboard().addKeyboardListener( lk );

                   //register our mouse input manager
                   ListenMouse lm = new ListenMouse(canvas, appleT, this);
                   InputSystem.getInstance().getMouse().addMouseListener(lm);


The lucu guide for creating videogames                                                                           Page 61 of 87
   As your game grows consider delegating functions (input, rendering, picking, etc) in different
   classes so it becomes easier to maintain.

Adding server-side game logic

   For out little puzzle game, our server-side game logic was basically just managing logins, logouts
   and broadcast messages, which are functions that are handled by the default implementation
   called "DefaultProtocalHandler.java".

   But for our apple chase game we need to add some logic to the game server:

             Set the initial coordinates of the apple, and then broadcast to all players.
             Keep and broadcast all players' score in a central place.

   To do this, we create GameProtocolHandler, which extendes the basic game server functionality,
   but adds custom game logic:

   public class GameProtocolHandler extends DefaultProtocolHandler
   {
   ..........

          @Override
          public void customGameLogic(String user, String message)
          {
   ....

   The game logic we put in the server is very simple: now the server calculates the new apple
   position and sends it to the players. You may remember that in the single version of the game this
   was calculated in the game client:

          private synchronized void issueNewApple()
          {
                   int randomX = FastMath.randomInt(20);
                   int randomZ = FastMath.randomInt(20);
                   StringBuffer sb = new StringBuffer();
                   sb.append("newApple");
                   sb.append(",");
                   sb.append(randomX);
                   sb.append(",");
                   sb.append(randomZ);
                   broadcast(sb.toString());
          }


Updating the game client

   First, we added a GUI frame so we can ask the player to enter his name. This is managed by the
   InputFrame.java class. The game will first show that frame, ask the information, and when pressed
   the "continue" button the game will start:




The lucu guide for creating videogames                                                       Page 62 of 87
                                         Frame for asking the name of the player

   Notice this code that will be executed when you press the button:

   public class InputFrame extends Frame implements ButtonListener
   {
   ...
        public void onButtonClicked(AbstractButton arg0, Object arg1)
        {
                 try
                 {
   ...
                        game.startGame();

   Next, on the AppleChase.java game we add the ummi client components needed to connect to the
   game server:

   public class AppleChase extends RenderLoop implements PickListener, IntervalListener,
   TCPConnector, UDPConnector
   {
   .....
         private ClientConnection networkClient = null;

   Using TCP messages, the server will notify the clients a new apple position, here is the code that
   takes care of that:

   public void messageReceivedTCP(String arg0)
        {
                if (arg0.startsWith("newApple"))
                {
                         // let's change the position of the apple according to what the game
                         // server decided
                         String[] message = convertLineIntoArray(arg0, ",");

                      // notice how the following logic is very similar to the method
                      // setApplePath()
   //these values came from the game server:
                      randomX = Integer.parseInt(message[1]);
                      randomZ = Integer.parseInt(message[2]);
   ...




The lucu guide for creating videogames                                                      Page 63 of 87
   The next change is: inside the prepareNext method we capture our avatar coordinates in the game,
   and use UDP to notify the game server, we do this so that our own avatar is displayed in the other
   game clients:

   protected void prepareNextFrame(long gameTime, long frameTime, TimingMode timingMode)
        {
   ....
                        // capture the player's coordinates (x,y,z)
                        sb.append(firstPersonHandler.getView().getPosition().getX());
                        sb.append(",");
                        sb.append(firstPersonHandler.getView().getPosition().getY());
                        sb.append(",");
                        sb.append(firstPersonHandler.getView().getPosition().getZ());

                             // capture the player's facing direction
                             float xx = firstPersonHandler.getView().getFacingDirection().getX();
                             float yy = firstPersonHandler.getView().getFacingDirection().getZ();
                             double angle = Math.atan(yy / xx);
                             sb.append(",").append(angle);

                             networkClient.broadcastUDP(sb.toString());

   The "angle" value is calculated using a little trigonometry function. As you play the game you will
   notice it is not perfect, but for our little game demo here it will be enough.

   The goal here is: your current position and facing direction are broadcasted to other players so they
   can know where you are.

   This information will be constantly "sent" to the game server so it can be broadcasted to the other
   players. Since we are using UDP it will travel fast enough to give the illusion that all our movements
   are reflected "in real time" in the other game clients.

   Next, we add code in our game client to update the position of a 3D model in the screen (that
   represents another player) every time we get a new position by UDP:

          public void messageReceivedUDP(String arg0)
          {
   ....
                                         //parse coordinates
                                         float x = Float.parseFloat(message[2]);
                                         float y = Float.parseFloat(message[3]);
                                         float z = Float.parseFloat(message[4]);

                                         //parse rotation angle (facing direction)
                                         float angle = Float.parseFloat(message[5]);
   ...
                                         // update the position of the other player on the screen
                                         avatarTG.setRotationY(angle);
                                         avatarTG.setPosition(x, y, z);
                                         avatarTG.updateTransform();
                             }

   The game client will show many 3D models (using the model tris.md2 that comes with Xith3D) to
   display on the screen the position of other player(s). The result when multiple players are playing is
   like this:




The lucu guide for creating videogames                                                              Page 64 of 87
                                         Apple chase multiplayer edition.

   There are some details worth mentioning about the the 3d model. It is loaded and then stored
   inside a Transform object so that it can easily be moved and rotated around the 3d world. Also, we
   attached the name of the player (notice the blue text floating over each character) so that you can
   identify what other players are playing with you. The following piece of code shows these topics:

   Transform avatarTG = (Transform) players.get(otherPlayerName);
   ...
   // load a model and associate it with this player
   URL modelResource = resLoc.getResource("tris.md2");
   String skin = "marvin.pcx";
   Model model = ModelLoader.getInstance().loadModel(modelResource, skin, 0.08f);
   avatarTG = new Transform();
   avatarTG.addChild(model);
   avatarTG.addChild(new AmbientLight(Colorf.GRAY10));

   // put the other player's name in a label next to the model
   Rectangle textRect;

   textRect = TextBillboard.createFixedWidth(1.0f, otherPlayerName, new Colorf(0f, 1.0f, 0.8f), new
   Font("Arial", Font.BOLD, 18), TextRectangle.TEXT_ALIGNMENT_HORIZONTAL_CENTER);

   //the following transformation is to put the text over the head of the 3D character
   Transform tt = new Transform(textRect).setTranslation(0.1f, 2f, 0.1f).addScale(0.8f);
   avatarTG.addChild(tt);
   model.setCurrentAnimation("run");


   scene.addChild(avatarTG);

The lucu guide for creating videogames                                                     Page 65 of 87
   And there you have it, the "Apple Chase" game, multiplayer edition. Be sure to run the server and
   the game clients in a network and have fun with your friends. Try to find ways to improve the game
   and experiment with the code to learn more.

   I hope you enjoyed this guide and wish you luck in creating your own games.




The lucu guide for creating videogames                                                   Page 66 of 87
Appendix A: Extra
Resources
Library

Creating a video game requires a combination of different skills: programming, graphics design, story telling,
music composing, etc. So it usually requires a team of people to complete.

Here is a list of useful books to read (At least check their table of contents!) so you can better understand the
whole process:

Books about game design:


Book                                                       Book cover (if available)


Tittle: Game design workshop
Author: Tracy Fullerton

Notes: game design, prototyping, game industry,
quality testing...




Tittle: Game Architecture and Design: A New Edition
(New Riders Publishing)
Authors: Andrew Rollings, Dave Morris

Notes: game design, development, gaming
concepts...


Tittle: Game Design—Theory & Practice
Author: Richard Rouse III

Notes: game design, game categories, level
designs, story telling for video games, interviews
with renowned game developers...




The lucu guide for creating videogames                                                                  Page 67 of 87
Tittle: software engineering for game developers
Author: John P. Flynt

Notes: AI, video game development planning,
quality control, patterns...




Tittle: Character.Development. and
Storytelling.for.Games
Author: Lee Sheldon

Notes: designing characters for games, creating
stories and fantasies, arguments...




Tittle: A theory of fun for game design
Author: Raph Koster

Notes: A must-read book to understand the theory
of fun applied to games.




Books about video game programming:


Book                                               Book cover (if available)




The lucu guide for creating videogames                                         Page 68 of 87
Tittle: Beginning Game Programming
Author: Jonathan Harbour

Notes: DirectX, 3d programming, sprites...




Tittle: Killer Game Programming in Java
Author: Andrew Davison


Tittle: Pro java 6 3d Game Development
Author: Andrew Davison




Tittle: Physics for Game Programmers
Author: Grant Palmer

Notes: The cover says: "A one-stop resource for building
physics-based realism into your games". This book is great,
it explain how you can add physic laws in your game
programming, but I must add that it is also important to note
there are some physics libraries that you can also use in
your games, like: bullet and ODE.




Books about graphic design:


Book                                                            Book cover (if available)




The lucu guide for creating videogames                                                      Page 69 of 87
Tittle: Game character development
Author: Antony Ward




Tittle: Game character modeling and animation with 3ds max
Author: Yancey Clinton




Resources
Interesting places to get information/files/tutorials/graphics/sounds/etc about video games:


Site                                                              Notes


Devmaster                                                         Game engines and review about them.
                                                                  Information about the gaming industry.
http://www.devmaster.net/engines/


Gamedev                                                           Gaming info.
http://www.gamedev.net/reference/                                 I strongly recommend you read the coverage
                                                                  they do about gaming conferences here:
                                                                  http://www.gamedev.net/reference/list.asp?categoryid=335


                                                                  You will find real-life histories and cases from
                                                                  game developers around the world. (better yet:
                                                                  try to go to one of those conferences!)


http://www.freeprogrammingresources.com/gamelib.html              More game engines.



The lucu guide for creating videogames                                                                         Page 70 of 87
http://www.cokeandcode.com/                                                    Gaming, games, resources...


http://www.pygame.org/wiki/resources                                           Tutorials, fonts, clipart, music, sounds library...


Game Deverloper Magazine                                                       Subscribe when you can to know more about
                                                                               games and the video game industry.
http://www.gdmag.com/homepage.htm

http://freegamedev.net/wiki/index.php/Free,_cross-platform_game_engines        Resources (music, sound effects, images, fonts,
http://freegamedev.net/wiki/index.php/Free_game_libraries                      sprites, libraries, tutorials....)
http://www.twilightsembrace.com/personal/gamelibs.php
http://www.yoyogames.com/make/resources
http://www.pygame.org/wiki/resources
http://www.ebonyfortress.com/blog/free-game-development-libraries/
http://freegamedev.net/wiki/index.php/Free_3D_and_2D_art_and_audio_resources
http://www.ambrosine.com/resource.php
http://www.costik.com/articles.html
http://www.ruthless.zathras.de/facts/apps/polygonesia/game_design.php
http://www.scottkim.com/thinkinggames/index.html
http://www.stratos-ad.com/
http://www.noshysoft.com.ar




The lucu guide for creating videogames                                                                               Page 71 of 87
Appendix B: How to
setup Slick
framework with
Eclipse
            Install java 1.6 or greater. For this guide I will install it in c:\jdk16
            Install Eclipse IDE 3.2 or greater. For this guide I will use Eclipse 3.2 in d:\eclipse. Start
             Eclipse and make sure you are using that java 1.6 jdk you just installed.
            Now download the latest version of slick from http://slick.cokeandcode.com, be sure to the
             full distribution, the complete link is: http://slick.cokeandcode.com/downloads/slick.zip.
             Next, unzip the file in a temporary folder. We will be taking some files from it, from the
             folders “src” and “lib” so take a quick look at them, we will use them later.
            Notice that slick depends on a library called lwjgl (http://lwjgl.org/download.php ) . It is
             recommended that you also download the latest version of that library. For this guide I
             downloaded LWJGL 2.3
            In Eclipse, create a java project, let's call it "slick". Inside it create three folders: src_prod,
             src_test and lib. Make src_prod and src_test java source folders. Inside "lib" we will put the
             necessary jar files. So far you should have something similar to this:




            Now, put the slick source code (with the exception of the “tests” package) in the src_prod
             folder. And put only the “tests” package in the src_test folder. The reason to separate this
             is just a good practice for java programs: always have your test and real-life-production
             source codes separate, for practical reasons this also means that when you deploy or
             deliver your final game to the users, you can easily filter out anything inside the src_test
             folder, and it also means that when you create a game it will be in its own “src_game1”
             folder. You will understand this better as we code games later on.

The lucu guide for creating videogames                                                            Page 72 of 87
             Now we will put the slick jar files in the “lib” folder. But we are not going to put all jars that
              come with slick, not because we do not need them, because we will put them “as we need
              them”. This way is better because you will learn what jars you will need when you do
              certain things with the framework, and also we will let us start with the basics first. The first
              jars we will put are:

                  ibxm.jar
                  jinput.jar
                  jnlp.jar
                  jogg-0.0.7.jar
                  jorbis-0.0.15.jar
                  lwjgl-debug.jar ( you can find this jar inside the lwjgl distribution you downloaded )

        Tip       Slick distribution comes with “lwjgl.jar”, but I recommend you use “lwjgl-debug.jar”
                  instead while developing your games to get more information while you test your
                 games. You can later deploy your game with lwjgl.jar

             So copy those jars to the “lib” folder and then change the project settings in Eclipse so that
              they are included in the build path. Do a refresh in Eclipse to make sure everything is in
              order and nothing is missing. If you did everything so far, now you have the source code of
              slick installed in Eclipse and without any compilation errors (do not worry about the warning
              messages now). You should have now something like this picture:




The lucu guide for creating videogames                                                             Page 73 of 87
            Now, we need to add the native libraries in our environment. These are the needed DLLs (
             in MS Windows environment ) or .SO (for linux). They are inside the jars that come with
             slick and are called: natives-linux.jar, natives-mac.jar, and natives-win32.jar. Since this
             guide is made for a MS Windows box, we will unzip the file natives-win32.jar in a folder we
             will call d:\dev\xian\natives, like this:



The lucu guide for creating videogames                                                     Page 74 of 87
        Tip       The “easy” way to use DLLs files in a windows box is just to put them in
                  WINDOWS_FOLDER\System32 or any other place where the path or the general
                 classpath can find them. But, I don’t recommend you to do that for two reasons:

                  1.- It is better to assume the DLLs are NOT in the computer your game will run or to
                  assum that you can easily put them in the destination PC just anywhere you want.
                  2.- It is better to put these files in a folder where they can be easily found/replaced
                  later.

             Note: If you will use lwjgl.jar that came with your slick distribution, then the previous step is
              just fine, but if you are going to use lwjgl.jar or lwjgl-debug.jar from the lwjgl distribution
              then you need to get these native libraries from LWJGL, since I will be using lwjgl-
              debug.jar then I will get these files from the lwjgl-2.3.zip file here:




             Now let’s do a little “hello world” basic program to test our slick installation. Create
              “HelloWorld.java” in the tests folder and make it like this:

         package org.newdawn.slick.tests;

         import   org.newdawn.slick.BasicGame;
         import   org.newdawn.slick.GameContainer;
         import   org.newdawn.slick.Graphics;
         import   org.newdawn.slick.SlickException;
         import   org.newdawn.slick.AppGameContainer;


The lucu guide for creating videogames                                                            Page 75 of 87
         public class HelloWorld extends BasicGame {

                 public HelloWorld() {
                     super("HelloWorld");
                 }

                 @Override
                 public void init(GameContainer container) throws SlickException {}

                 @Override
                 public void update(GameContainer container, int delta)
                         throws SlickException {}

                 @Override
                 public void render(GameContainer container, Graphics g)
                         throws SlickException {
                     g.drawString("Hello world from slick", 0, 100);
                 }

                 public static void main(String[] args) {
                     try {
                         AppGameContainer app = new AppGameContainer(new HelloWorld());
                         app.start();
                     } catch (SlickException e) {
                         e.printStackTrace();
                     }
                 }
             }

            To run this program you do need to tell java where to find the “native” libraries, if you don’t
             it will show an error like this:

         Exception in thread "main" java.lang.UnsatisfiedLinkError: no lwjgl in
         java.library.path
                 at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1709)
                 at java.lang.Runtime.loadLibrary0(Runtime.java:823)
                 at java.lang.System.loadLibrary(System.java:1030)
                 at org.lwjgl.Sys$1.run(Sys.java:72)
                 at java.security.AccessController.doPrivileged(Native Method)
                 at org.lwjgl.Sys.doLoadLibrary(Sys.java:65)
                 at org.lwjgl.Sys.loadLibrary(Sys.java:81)
                 at org.lwjgl.Sys.<clinit>(Sys.java:98)
                 at org.lwjgl.opengl.Display.<clinit>(Display.java:132)
                 at org.newdawn.slick.AppGameContainer$1.run(AppGameContainer.java:39)
                 at java.security.AccessController.doPrivileged(Native Method)
                 at org.newdawn.slick.AppGameContainer.<clinit>(AppGameContainer.java:36)
                    at org.newdawn.slick.tests.HelloWorld.main(HelloWorld.java:30)

            So, go to the “run” options of Eclipse and open the “run dialog window”:




            Inside that dialog create a new “Java Application” configuration:




The lucu guide for creating videogames                                                         Page 76 of 87
            Select out test class as the Main class:




            Now in the tab “Arguments” you need to tell java where you placed the native libraries, with
             the parameter -Djava.library.path=d:\dev\xian\natives like this:




The lucu guide for creating videogames                                                      Page 77 of 87
            Now you can run this “Run configuration” from the “Run” menu of Eclipse.
            If you get an error that says something like “jar and library are from different version” is
             probably because you are not using the correct version of the native DLLs (slick or lwjgl
             versions)
            If everything went OK, you can now run this simple example and see something like this:




            A nice “game window” generated by slick framework, with the message you put in the java
             code. As a bonus you get the actual frames per second (fps) in the upper left corner.


The lucu guide for creating videogames                                                      Page 78 of 87
Appendix C: How to
setup GTGE inside
Eclipse IDE
   Just one note before starting: you can of course use another java IDE (like Netbeans, Jcreator, etc)
   instead of Eclipse. I'm using it here just because I prefer Eclipse but if you know java you can easily
   use these same steps to setup GTGE in another java IDE.

      Install java 1.4.2 or greater. For this guide I will install it in c:\jdk142
      Download Eclipse IDE from http://www.eclipse.org/downloads/




      The version you need is just the simple "Eclipse IDE for Java Developers". You can of course
       download the "Enterprise EE" version if you want.
      I will use my good old Eclipse 3.2 version that only needs java 1.4.2 to run and is the same java
       requirement as GTGE. You can try a newer Eclipse version but will probably require a newer
       java version to run. Make your choice.
      For this guide I will install Eclipse IDE 3.2 (enough for me) in d:\eclipse.



The lucu guide for creating videogames                                                       Page 79 of 87
      Now start Eclipse (which ever version you downloaded) and make sure you have java 1.4.2 as
       the default runtime option (this is the same jdk you installed in a previous step):




      Now create a java project, I will call it "gtge".
      Optional but highly recommended step: create a "source folder" called "prod" inside the gtge
       project, this will help to separate your code from the engine code, create another "source folder"
       called "test" to put some examples or little testing programs, then create one "source folder" for
       each of the games you plan to develop. If you do this your java programs will live in separate
       folders and will be easier to manage.
      Please create a separate source folder called "puzzle" for the game we will create. This also
       helps when you finished your game and want to create separate deployers/installers for each
       game. This is how my environment looks so far:




      Download GTGE engine from http://goldenstudios.or.id/products/GTGE/
      I will be using this version: GTGE_0_2_3_complete.zip
      Unzip the download file and look for the source code inside, put that java code in the "prod"
       folder or the gtge project.
      Now run the tutorial that comes with GTGE, there you will learn the basics of the framework.


The lucu guide for creating videogames                                                      Page 80 of 87
      Don´t forget that game resources (images, sound, .etc) go INSIDE the source folder of the
       game, like this:




      I recommend you to try to run the "robotic war" game (available from the same GTGE site) or
       any of the other games available there. They are all fun! This will give you and overall view and
       usability of the framework.

        Tip      When you copy, erase, delete, or rename files inside your project sometimes Eclipse
                 does not automatically recognize that... and you may get strange "File No tFound
                errors"... in those case use the "refresh" and "clean" (in that order) options of Eclipse to
                 force Eclipse to re-read the folders/files and to clean any temporal data




The lucu guide for creating videogames                                                          Page 81 of 87
Appendix D: How to
setup Xith3D inside
Eclipse IDE
   If you don't have your Eclipse IDE installed yet, please make sure you read the previous sections of
   this document to learn how to do it.

   For the rest of this section I will assume you already have your Eclipse IDE with JDK 1.6 (or
   greater) up and running already.

   First, go to Xith3D's site ( http://Xith3D.org ) and download the latest version. When I did this guide
   the latest version was 0.9.7-dev-B1831 "cooker release" of 2010-09-06.

        Tip       Don't forget to visit Xith3D's forum to meet the community and people supporting it.
                  You can get advice and learn about XITH3D.
                   Forum: http://Xith3D.org/forum/index.php

   Unzip the file you downloaded and inside you will find a document called "xin-3rd-edition.pdf".

   Make sure you read it to learn Xith3D's basics.

   Inside that zip you will also find the Xith3D libraries, third-party libraries, native libraries, source,
   examples and resources. We will put them inside Eclipse to create a development environment.

Installing the support libraries

   Inside Eclipse create a java project called "Xith3D", associate it with jdk16 and add the following
   basic libraries to the classpath:




The lucu guide for creating videogames                                                         Page 82 of 87
   Looking at these libraries is a good moment to remember the importance of using an engine to
   build your game. As you can see Xith3D already provides you a lot of functionality that otherwise
   you should have to work on adding yourself. Let's do a quick overview of what these libraries
   provide (and that you can use in your game):

             jagatoo: input (keyboard, mouse) management
             jogl: 3D graphics
             joode: physics (gravity, collisions, etc)
             lwjgl: 3D graphics
             joal: sound
             vorbis: sound/music

   Notice that swt.jar (that came with Xith3D distribution) has not been added. You can add it if you
   plan to use SWT to create Eclipse plugins. Note: I have been given this tip on the Xith3D forum:
   "On the Mac platform just having the jar in the classpath causes some problems".


        Tip           Don't forget to always "refresh" the workspace in Eclipse to make sure all files you
                      just copied are available to use inside the Eclipse IDE.
       
Adding Xith3D's own files

   To add Xith3D itself to your project, you have two options, choose the one you like best. Option 2
   requires less files/space is more "organized" and is probably the fastest and more command
   option. Option 1 usually is used only if you want to constantly look inside Xith3D source code and
   even change it to experiment a little. (I am very curious so I use option 1).

   Option 1 (put Xith3D as source files in Eclipse):

   Inside the java project create three "source folders" called "prod", "test" and "test-resources". We
   will put the engine's files in the "prod" folder, our tests, games in the "test" folder and game
   resources (graphics, textures, sound, etc) will be placed in the "test-resources" one.
   Also add a folder called "lib" to hold the engine's library jar files.

   Locate the file Xith3D-source.jar from the downloaded XITH3D distribution and extract the source
   code from inside and put it in the "prod" folder of our project.



The lucu guide for creating videogames                                                         Page 83 of 87
   Locate the file Xith3D-test-source.jar from the downloaded XITH3D distribution and extract the
   source code from inside and put it in the "test" folder of our project.

   Locate the file Xith3D-testres.jar from the downloaded XITH3D distribution and extract the source
   code from inside and put it in the "test-resources" folder of our project.

   If you followed this option you should now see something like this:




   The error (red x) is because we didn't add the swt.jar. Just erase the file CanvasPeerImplSWT to
   clean the compilation error.

   Option 2 (put Xith3D as a jar in Eclipse):

   Add xith3d.jar to the classpath.
   Go to the propertied of xith3d.jar and add xith3d-source.jar as "source attachment" to it.
   Add xith-test.jar to the classpath.
   Add xith-testres.jar to the classpath.


Adding the native libraries

   The next step is the setup of the "native" libraries. These are special files ("DLLs" for Windows
   platform, "SO" for linux... depending on your platform...) that are used by some of the jar libraries to
   access the operating system's resources. They are located inside folders called "natives" in the
   third party libraries of Xith3D. There are three options to link them to your Xith3D java project.

            Option 1 is the "classic" option and works with any IDE. I don't think anybody uses this
             option anymore for development, but it is good to know because very likely you will use this
             option to create "installers" for your games on the client machine.
            Option 2 is the "quick and dirty" option if you don't want to think too much and just want to
             make games and play them.
            Option 3 is the recommended option because it is more clean and organized.

   Choose the option that you like better. Here is the description of each option:

   Option 1: Copy the native libraries to any folder and add the "-D" parameter (referencing that
   folder) in java every time to call Xith3D. This is the standard/best option and is recommended
   always. Check java's documentation on how to do this. Here is a small example:

               java -cp .;jar\Xith3D.jar;jar\mygame.jar -Djava.library.path=native\windows package.super.MyGame

   Option 2: This is the "quick and dirty" option and the one I will use in this guide is to just copy
   those native libraries to an existing system path where java can always find them. In Windows XP
   that folder is "WINDOWS\SYSTEM32", so in my development environment I just copied these files
   there:




The lucu guide for creating videogames                                                                      Page 84 of 87
   Option 2 is liked because during testing/development one usually does/runs a lot of programs and
   adding the "-D" parameter every time you run something just makes development slower.

   Option 3 (recommended option): I just learned this one and will use it. What you have to do is just
   copy the native libraries somewhere. I put them where the normal jar files are, but they can be in
   another folder also:




   Then go to each jar that needs to reference them and add it as a "native library" option so that it
   can be located during runtime. Here is screenshot of how it's done:




The lucu guide for creating videogames                                                       Page 85 of 87
   You need to do that operation for the following jars:

            lwjgl.jar
            gluegen-rt.jar
            joal.jar
            jogl.jar
            swt.jar (if included)


Making sure Xith3D is installed correctly

   Assuming you did everything correctly you can now run Xith3D's own examples. Be sure to do that
   because you can learn a lot from watching them and inspecting their java code.

   To run the examples execute this program: org.Xith3D3d.test.Xith3D3DTestLauncher.

   Xith3D has plenty of examples, but the ones I recommend you first concentrate on are:

            BSPLoaderTest: it loads a Quake MAP level and allows you to move inside it, very useful
             to learn about maps.
            MD2LoaderTest: loads a game character from a MD2 file.
            FirstPersonInputHandlerTest: loads a game character and lets you control it in from a third
             person perspective.

   They will give you a nice overview of the engine's capabilities.




The lucu guide for creating videogames                                                      Page 86 of 87
Appendix E: Xith3D
scenegraph
   Taken from the Xith3D documentation:




The lucu guide for creating videogames    Page 87 of 87

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:208
posted:6/22/2011
language:English
pages:87