VGOLF: AN INTERACTIVE GAME IN VPYTHON  Last Updated: 12/7/2010
\author{Mayank Kejriwal}
\title{ VGolf}
\begin{document}
\maketitle
\begin{abstract}
\emph{This project is a packaged game called VGolf consisting of a .py script file, and several .tga graphic files that have been employed to add visual originality to the game. The package, without its expansions, was developed in the Fall of 2010 as a part of an undergraduate class, Math 198, taught in the University of Illinois at Urbana Champaign by Professor G. Francis. The game requires the \emph{Visual package} developed for Python 2.7 and of course, Python 2.7 itself. Collectively, the two packages for Python 2.7 and Visual are combined into a single open source software called \emph{VPython}, that can be downloaded for free from the VPython website. Technical details, instructions, motivation behind the project and potential future development are outlined below in subsequent sections.}
\end{abstract}

\section{Introduction}
Back in the beginning of Fall 2010, I was enrolled in a class that I had long wanted to take as part of the Campus Honors Program at the University of Illinois. The class was titled \emph{Hypergraphics} and seemed to be a very fascinating mesh of independent work and study in programming, graphics and math. When I first took the course, my aim was to develop an independent project using the package OpenGL, in which some of my most favorite applications have been developed. However, I was woefully ignorant about some of the other great open source packages out there, and I found myself becoming more open minded about them as the semester progressed.
\\
One such software was VPython, which despite its limitations, interested me a lot. This was because it was mainly developed for simple physics applications and being a student of Engineering Physics, this interested me no end. Somewhere during the progression of the semester, I decided to opt for VPython in making my project of choice. This meant that I would not be able to showcase my project in the CUBE, a unique, incredible 3D environment here in the University of Illinois where user interactivity and graphical output achieves its crest. From other standpoints however, VPython made sense because being a student also in Computer Engineering, I would be learning OpenGL in the future anyways and it seemed premature to start too early with it.
\\
Choosing a suitable project for VPython was not easy, mainly because there were far too many things I wanted to implement. Ultimately, I decided to combine my love for vector fields, collisions, and games into VGolf, a well-paced, understandable playing environment that could be modified by future students and the like, even those who had little programming experience.
\\
There were many challenges associated with writing VGolf, from learning to write reasonably complex code in Python to making it run the way I wanted it to. VGolf, like many other computer endeavors, is nowhere close to being perfect, but it is my hope someone along the line will be able to continue developing it and making it as smooth and fast as possible.
\\
\section{Getting Started}
\emph{The instructions below work ideally for a Windows machine. For any other operating system, everything but the first two instructions holds. To find out how to deploy VPython on your OS please refer to the website. }
\begin{enumerate}
\item Download VPython and Python 2.7 from the website \emph{http://vpython.org}. Instructions on installation and troubleshooting are given in detail on the website.
\item Make sure that VPython works on your computer by opening the IDE, known as VIDLE, which is probably installed on your Desktop. If not, search for it in your installation folder.
\item If VIDLE opens, then proceed. Otherwise, VPython has not installed properly and you need to troubleshoot before proceeding. The website is a good source of potential issues and on how to resolve them.
\begin{enumerate}
\item Chrysanthemum.tga, Tulips.tga, Hydrangeas.tga and Penguins.tga
\item VGolf.py
\end{enumerate}
\item Open VIDLE and click on File, then Open. Use it to choose VGolf.py from your folder.
\item The code should now appear in VIDLE. Press F5 to run the game.
\end{enumerate}
\section{Gameplay}
The aim of VGolf is to guide a ball from one end of the room into a hoopla ring at the other end. Sounds simple? Factor in crazy, bouncing, out-of-control marbles and invisible vector fields waiting to fling you into oblivion and you'll find golf can never be so entertaining (and don't forget the quicksand and magnetic spots)!
\\
In its original version, VGolf comprised of four levels of increasing difficulty. Every time you succeed in a level, the elevation to the next level will be instantaneous and automatic. Note that vector fields may not remain constant across levels, among other things.
\\
When you first start the game, you'll encounter the room, the ring and the marbles but not the target ball. In order to make it appear you will have to use your mouse and click it on a particular location in the front of the room. Upon a single click, the ball will appear and will immediately start navigating the room because of the influence of the gravitational, electrostatic and magnetostatic  fields present everywhere. Note that the marbles are immune from the fields but not from colliding with physical objects, including the ball.
\\
VGolf gives you an infinite number of tries but not infinite time within a try. After a brief interval of time, if you have not beaten a level you will be asked to try again after pressing a key.
Once you have generated the ball with a click you have no control over it. This is because of the dominating influence of the fields.
\\
However, you do have the ability to quit the game when you please. To do so, press any alphanumeric key and the game will halt. You are now free to quit.
\\
If you feel the game window is too small or large, use the mouse to change the size of the viewscreen. Note that speed and performance may change as you do so.
\\
If you are interested in vector fields and what sort of objects they affect, or in collisions, feel free to check out some fantastic open-source stuff on WikiPedia!
\\
Above all, enjoy the game!
\\
\section{Technical Details}
\subsection{The Language}
VGolf is a piece of code written in Python 2.7, with heavy reliance on the \emph{Visual} package afforded by VPython. Python is a scripting language that doesn't typically rely on compilation, but Python programs can be compiled into executables using installer packages. VGolf, however, uses the traditional model and the system does not look upon the VGolf.py file as a compiled file. This is why it is not only possible, but encouraged for programmers to modify the VGolf code to make it more dynamic, interesting and optimized.
\subsection{The Program}
\subsubsection{Design Choices}
The first and most obvious feature of the program is its structured indentation which is enforced by Python, unlike other programming languages. A possible upside to this practice is that it enforces good readability of code, but future programmers must be careful with it as it can be a source of numerous errors (and a good deal of frustration).
\\
The next feature of the program itself are the numerous \emph{if} gates in the program. This is common practice in most games, which tend to have many boundary conditions. Part of the debugging process of VGolf was in making the boundary conditions as physical and sophisticated as feasible. I have attempted to condense these \emph{if} gates as much as possible.
\\
VGolf uses what I coin a \emph{flag mechanism} for maintaining game protocol. This is because it is important in games that the relevant operations be ordered, though they may at times seem random. For instance, the timer must not start ticking till the user has generated the ball with a mouse click. Moreover, causality must be maintained: the levels must change only when the ball has reached the hoopla, the game must halt only if the user presses a key and a \emph{Try again} prompt must only appear once the gamer has run out of time in a particular move. Causality is implemented by hierarchy and hierarchy through flag variables. I shall present an example, and hope the rest of the code is clear to place it in context in other situations.
\\
\subsubsection{Environment and Parameter Generation}
Consider, for instance, the program flow from the programmer's point of view, along with the gamer's point of view. The first task for the programmer is \emph{environment and parameter generation} enabling. This is what the gamer awaits when he runs the game. The environment includes the room and its components, like walls, floor, and roof, the marbles, the ring and the text, both visible and invisible, while the parameters include features like marble initial  velocity, colors, texture mapping etc.
\\
If there was only one level, we would simply generate a single environment and leave it there. However, that would make the game uninteresting. It is important to note that as the game evolves with the levels, the environment changes too. The colors of the walls, the marbles, even the ball, the level text, and parameters to increase the game difficulty must all be modified. This is the reason for the functions right at the beginning of the code, defined using the \emph{def} keyword. Notice how the function \emph{setlevel} acts as a sort of common ground or a function \emph{jump table} that uses \emph{listed function pointers} to \emph{zero, one, two} and \emph{three} that are functions denoting levels 1 to 4 respectively. The reason why the numbering is off by one is because in Computer Science we often choose to start from zero than from one.
\\
Notice that function \emph{zero} is utterly unnecessary because the game starts from level 1 and will probably never enter that function. However, it is good practice to maintain this kind of homogeneity in the code so that it is easier to debug. In the remaining functions, notice how different parameters are changed as the levels are breached. How the program gets to each of these functions is explored in more detail below. By now however, the methodology for changing and generating environments and parameters should be clearer.
\\
\subsubsection{Flags}
To understand how the \emph{flag mechanism} works, try to picture a series of concentric circles with one gate leading from one circle to another, but with different locks on both sides. This means that just because one has managed to gain \emph{entry} to an inner circle doesn't mean he can \emph{exit} it, either by going inside \emph{or} outside. Now imagine that he is doing rounds in the circle but that every time he passes a gate (leading  further inside or outside) he tries his key to see if it works. If it does, he exits, while if it doesn't he continues his rounds. The rounds are analogous to the \emph{while loops} which test for a \emph{condition}. Based on whether the condition is \emph{false} (if he is inside the loop or circle) or \emph{true}  (if he is outside the circle or loop and it trying to get inside), he would continue doing his rounds or leave.
\\
The next question is how he manages to get the right keys, if at all. In the gaming world, he would get them through \emph{events}.  For instance, when the gamer clicks the mouse, a \emph{mouse interrupt event} occurs which results in a range of operations, such as the generation of the ball. When the ball reaches the ring, another event occurs and so on. The \emph{while} and \emph{if} sequences have been written to make this sort of event triggering obvious. Notice how the outermost flag is aptly titled, and the condition for this outermost loop can only be violated if the gamer quits, or the game reaches its conclusion. Any attempt to leave the game other than these two would invite a prompt warning from the system that an attempt to kill the program while it is still running is being made.
\\
Flags are not just useful in gaming. They're used in almost all computer systems and are like signals. To complete an analogy, think of a computer as an enormous series of roads and of programs like cars. Without flags or signals, there would be utter chaos on the computer's resources. More often than not, computers still hang up for the simple reason that code does not handle flags properly.
\\
\section{The Physics}
\subsection{Vector Fields}
A question I am often asked is whether VGolf has been named simply because it is written in VPython or if it stands for Vector Golf. The answer is: both. The Project started out as Vector Golf but I decided to condense it the moment it took off in VPython. The whole premise of VGolf and what makes it original is the concept of vector fields. While you can plan where to put the ball based on the obstacles etc. that you actually see, there are factors that you will have to play around with because you won't be able to see them visually. In particular, it is important to understand what vector fields exist in what parts of the room, at least intuitively. As the game progresses, the fields become more twisty and complicated.\\
So what exactly is a vector field? Mathematicians like to classify these into force fields, acceleration fields etc. but we are going to concentrate on the physical definition, and the one most commonly in use, which is that of the Force Vector Field. A Force Field associates with each point in 4D space time, a Force Vector. To understand the basic concept of \emph{four dimensions} or \emph{vectors}, see the section \emph{The Mathematics}. \\
Typically, the vector is set up so it is the force that would exerted per unit mass or charge on any body that happened to come across it, and based on whether the field is primarily electric, magnetic or gravitational. For this game, we do not define what force type the vector fields are, even qualitatively; rather, it is simply meant to introduce the concept of a vector field visually.\\
\subsection{Snell's Law of Reflection}
For those who like to go into history, Snell's law was not postulated first by Snell, nor is it an \emph{original} law that follows from fundamental considerations. However, there are various reasons why the law is named after Snell, all of which can be looked up in a valid internet reference. Snell's law can be proved using the Huygen-Fresnel principle (or in an alternate way, Hamilton's principle), which states that each point on a \emph{wavefront} of light is itself the source of a new spherically radiating wavefront. To precisely understand what a \emph{wavefront} is, the discussion must flow into a comprehensive physics text as it is by no means a basic topic. Huygen's principle can be used to prove both reflection and refraction laws (and to explain bending effects, like diffraction), but in our case we are only concerned with the former. Simply stated, Snell's law for reflection states that the angle of incidence is equal to the angle of reflection of a \emph{ray of light} that strikes a surface. Sometimes the light is partially reflected, sometimes completely (Total Internal Reflection) and sometimes not at all (Matched Impedance: an important concept in Transmission Lines) but either way, the law is valid classically (in ray optics). Snell's law is not normally used in higher physics involving wave optics and quantum mechanics. \\
However, we are dealing here with physical, massy objects, not light. How can we justify using Snell's laws for these objects? The truth is we can't. However, it is a good way of thinking about it because \emph{elastic collisions} of the ball with the walls has the same sort of relationship as dictated by Snell's law.
\\
\subsection{Collisions}
There are primarily two types of collisions at the classical level. An \emph{elastic} collision is a collision wherein kinetic energy \emph{and} total momentum of the system is always conserved. An inelastic collision conserves the latter but not the former. The only classical restrictions on this type of a scenario are that the system be completely defined by its masses and the dynamic quantities of those masses, and that there be no external forces on this system. While the latter condition is violated in our case, since vector fields (external forces) exist everywhere in the room, we can still apply elastic collision laws \emph{locally}. It is a very good approximation for the actual collision because the ball does not accelerate by much, a few microseconds before it collides with the wall. Moreover, because the mass of the wall is so large, we do not observe it physically recoiling as it should. Since the ball starts accelerating immediately after the collisions, due to the vector fields, small changes in its velocity due to this recoil are also irrelevant.\\
\subsection{Volume Density}
Collisions occur not just between the ball and the walls but also between the ball and the marbles, as well as the marbles with themselves and the walls. Collisions of the marbles with the walls follow the same argument in the previous section. However for ball-marble or marble-marble collisions, we have made an implicit assumption, namely that the \emph{masses of all the bodies are the same}. This enables us to implement elastic collisions simply by reversing velocity components when the bodies interact. \\
What does the above assumption physically imply? Since the volume density (sometimes simply called density) of a mass is simply mass over volume, and the marbles are much smaller than the ball, \emph{the density of a marble is greater than the density of the golf ball}. In real life, this is the case as well, because marbles are usually smaller than golf balls, and the material density of marble \emph{is} greater than that of the engineered substance golf balls are composed of. \\
\section{The Mathematics}
\subsection{Vectors}
To get a layman started, a \emph{vector} differs from a \emph{scalar} number in that it has both a \emph{magnitude} and \emph{direction}. The direction of a vector can be represented by an arrow in the abstract or by \emph{components} for a defined coordinate system (like the \emph{rectangular coordinate system} with $x$, $y$ and $z$ coordinates). For details on how vectors are written, linear algebra, vector transformations, and vector operations like dot and cross products, refer to an elementary mathematical text on vector algebra.\\
\subsection{Vector Calculus}
As can well be imagined, vectors are much more apt, physically, in representing real objects like balls and marbles. It is not sufficient to say that the ball is traveling at 5 metres per second: in what direction is it actually traveling? \\
VPython uses the above mentioned rectangular coordinate system, so understanding vector representations of the ball, marbles and their dynamic quantities are an easy matter. Understanding how these quantities change, for they \emph{do} change (\emph{dynamic}), is slightly more complicated. Recall the \emph{scalar equations of motion} that you may have learnt as a consequence of Newton's laws, or refer to a high school Physics text if you have not done so. These classical equations are now derived with vector calculus using vector variables instead of scalars, which means it is important to be able to do integration and differentiation on vector quantities. Usually, it is a seamless transition, if you have already had exposure to elementary calculus, but further exploration of the topic is encouraged as it is used in most scientific arenas. \\
\\
We use two simple equations:
$$a=F/m$$
$$v=u+at$$
Here $a$ is the acceleration, $F$ is the force, $m$ is the mass, $v$ is the final velocity, $u$ is the initial velocity and $t$ is the instantaneous time. These are actually vectors but we break them into scalar components and use these scalar equations of motion in the code. On a final note, all units are consistent but undefined, since they have no place in computer code.
\subsection{Four Dimensions}
Here, I will not go into advanced discussions about Minkowski Space-Time or the like (\emph{Sorry}). The point I want to emphasize is that it is not enough to assign a vector to every point in space and simply assume that it stays put forever. It might, for instance, be rotating every second, or changing magnitude or something else. The point is that changes are occurring in \emph{time} at the \emph{same} place for a given coordinate. This is what makes these fields four dimensional, because they can change in three spatial and one temporal coordinate (You might be wondering if it's possible to have more, and the answer is, unfortunately, yes).
\\
\section{Evolution of Code}
I would love it if someone decided to make the evolution of this piece of code his project in future semesters of Math 198. In particular, these are some of the more challenging changes that can be implemented:
\begin{enumerate}
\item More levels, and with greater variety. Generate more obstacles, make the ring move crazily, have a reflection ball, enable dynamic changes in vector fields within the same level etc. The creative opportunities here are limitless so future game designers: consider this a test case of your practical abilities!
\item More artistic glamor. Implementing art through VPython programming can be quite challenging. I've dabbled in it a bit through texture mapping on the ball etc. but there's lots more that can be done, especially with the text and the walls.
\item Refined input. In particular, the game can only quit if a \emph{q} is pressed. Also, a \emph{pause} key, although I found it unnecessary for this particular game.
\item A system of scores that will update on the screen as the game progresses.
\item And many, many more.
\end{enumerate}
\section{My Original Contract}
Originally, VGolf was not meant to be as diverse as it is now. This is because I was not aware of its many capabilities, and also because I didn't realize I'd been taught so well in my earlier programming classes that I could adapt to a new, different language like python quickly enough to write the required code. Looking back at the original proposal I'd submitted sometime in the first half of this semester to Professor Francis, I noticed that there were several features lacking in the contract that ended up being implemented in the original game: \\
\begin{enumerate}
\item There is no concept of obstacles in the original contract. I can't even begin to imagine what VGolf would look, and play, like if there were no obstacles crazily bouncing around.
\item The original contract also had no artistic claim, but VGolf now employs several manual and pre-imaged texture mappings on the ball and the walls, which makes it more visually appealing.
\item As I did state in the contract, I tried and succeeded in implementing levels in the game.
\item I also incorporated user input of which there was no mention in my original contract. This allows me to allow the user to place the ball anywhere, and use timers and quit interrupts. At the time, I was so disillusioned about this aspect of this game that I specifically discarded it being a possibility at all in the game. I am happy, for a change, at my own wrongness.
\item Finally, the website that you are now perusing also had no mention in the contract, along with manuals and documentation. Currently, these have all been implemented.
\end{enumerate}
It's possible that you are wondering if there is anything in the contract that I did not fulfill since there are so many extra things that I did that were not in the original contract. Unfortunately, the answer would be yes. The original contract did have a claim that the user would be allowed to program the \emph{charge} and \emph{mass} of the ball so that it would react differently to the fields. However, this was done under the claim that the ball would only start from a predetermined point. In order to have the user control anything at all, I had to have that requirement. Now that the ball can start from any quadrant on a plane parallel to the xy plane, it seems pointless to add more parameters to make the game even slower. With due modesty therefore, I would like to state for the record that the choice to not fulfill that particular requirement was purely due to design reconsideration because of the unexpected slowness of the software. \\
I also hope that any novice programmers reading this section realize that its much more beneficial, as a student and a programmer, to seek to exceed the original terms of your contract, even if you don't have to. At the very least, it affords you boasting rights in public, and an increased sense of programming self-esteem.
\\