You are on page 1of 49

Kurdistan Regional of Iraq

University Of Human Development

College of Science and Technology / IT Department

Group B1 5th
Semester

2020 -2021
Game programmers commonly use Java for game development, because
Java supports multithreading and sockets. Multithreading uses less
memory and makes the most of available CPU, without blocking the user
out when heavy processes are running in the background. Sockets help in
building multiplayer games. Plus, Java runs on a virtual machine, so your
game will be easier to distribute. In comparison to programming languages
like C++, Java is easier to write, debug, learn and compile.
When talking about game development there is no specific or defined
language that is the standard, The thing is all the languages are suited for
game development, the next thing is that how to make a game in the
language I chose.
There are many programming languages that do certain tasks well while
others do the same task better. Most modern games use the language(s)
supported by the game’s engine. Engines are chosen using a number of
factors, such as cost, platform availability, and technical limitations. For
example, Unity is affordable, can publish applications for a variety of
platforms, and supports several languages for object scripting (C#,
Javascript, and Boo). If you are building your own engine, then use what
you are comfortable with. Most languages have libraries for DirectX or
OpenGL support.
the best language for programming games in 2020 are:
C++ , C# , JAVA , JavaScript , HTML5
Best of them to make PC or console games is C++, unless you use the
Unity or MonoGame game engines, if you want a high-speed action game
use C++ , if you want a moderate speed game (like a Bejeweled clone), but
are afraid of C++ Then use C# with a game engine that supports it (Unity,
MonoGame), C# , it’s easier than C++.
C++ is the king of game programming languages. Not only is it one of the
fastest languages (because it compiles to machine language), it has a whole
ecosystem that caters to it. C# is good too, but it uses automatic garbage
collection, which can hinder performance. Some professional games have
been made in C#, but because of this drawback, C++ still reigns supreme.

1
 A Thread is used to allow more than one task to be performed at one
time.
 This is achieved by Time Slicing where one thread is executed for a
short time, then pre-empted by another thread.

 Threads may run simultaneously on a machine with more than one


processor.

There are three basic ways to use Threads in Java


– Extend the Thread Class
– Implement the Runnable Interface
– Use anonymous inner classes

2
Extend the thread class and override the run() method

Then create and start the thread:


Thread myThread = new MyThread(); myThread.start();

Any object that implements the Runnable Interface can be passed as a


parameter to the constructor of a Thread object.

The MyClass class implements Runnable, passes itself into a new thread,
then starts that thread which executes MyClass.run() .

3
 The wait() and notify() methods provide a means for putting one
thread to sleep until it is ―woken up‖ by an outside source.
wait() is a method of the java.lang.Object class. It is called in a
synchronized block of code by an executing thread and causes the
threads lock on the object to be released and the thread to be put to
sleep. notify() is also a method of java.lang.Object. It notifies one
thread that is waiting on the same lock. If several threads are waiting
on the same lock one of them is notified randomly.
 .stop(): kills a specific thread .
 .suspend() and resume(): deprecated.
 .join(): wait for specific thread to finish.
 .setPriority(): 0 to 10 (MIN_PRIORITY to MAX_PRIORITY); 5 is
default (NORM_PRIORITY).
 yield(): current thread gives up processor so another of equal
priority can run.
 sleep(0.8): stop executing for 0.8 millisecond

MULTITHREADING in Java is a process of executing two or more


threads simultaneously to maximum utilization of CPU. Multithreaded
applications execute two or more threads run concurrently. Hence, it is also
known as Concurrency in Java. Each thread runs parallel to each other.
Mulitple threads don't allocate separate memory area, hence they save
memory. Also, context switching between threads takes less time.
multithreading, java being the most famous. Java multithreading is
mostly used in games, animation, etc.
The advantages of java multithreading can be summarized as follows :

 Threads are independent and one can perform multiple operations


at the same time.
 Multiple operations can be performed together, so it saves time.
 Threads are independent, so it does not affect other threads if an
exception occurs in a single thread.
4
In multithreading, there is the asynchronous behavior of the programs. If
one thread is writing some data and another thread which is reading data at
the same time, might create inconsistency in the application. When there is
a need to access the shared resources by two or more threads, then
synchronization approach is utilized. Java has provided synchronized
methods to implement synchronized behavior.
In this approach, once the thread reaches inside the synchronized block,
then no other thread can call that method on the same object. All threads
have to wait till that thread finishes the synchronized block and comes out
of that.
In this way, the synchronization helps in a multithreaded application. One
thread has to wait till other thread finishes its execution only then the other
threads are allowed for execution. It can be written in the following form:

Synchronized(object)
{ //Block of statements to be synchronized }
5
The Java 2D API provides two-dimensional graphics, text, and imaging
capabilities for Java programs through extensions to the Abstract
Windowing Toolkit (AWT). This comprehensive rendering package
supports line art, text, and images in a flexible, full-featured framework for
developing richer user interfaces, sophisticated drawing programs, and
image editors. Java 2D objects exist on a plane called user coordinate space,
or just user space. When objects are rendered on a screen or a printer,
user space coordinates are transformed to device space coordinates.
The following links are useful to start learning about the Java 2D API:
 Graphics class
 Graphics2D class
The Java 2D API provides following capabilities:
- A uniform rendering model for display devices and printers
- A wide range of geometric primitives, such as curves, rectangles, and
ellipses, as well as a mechanism for rendering virtually any geometric
shape
- Mechanisms for performing hit detection on shapes, text, and images
- A compositing model that provides control over how overlapping
objects are rendered
- Enhanced color support that facilitates color management
- Support for printing complex documents
- Control of the quality of the rendering through the use of rendering
hints.

 Points
The most simple graphics primitive is a point. It is a single dot on the
window. There is a Point class for representing a point in a coordinate
space, but there is no method to to draw a point. To draw a point, we used
the drawLine() method, where we supplied one point for the both
arguments of the method . PointsEx ex = new PointsEx();

6
 Lines
A line is a simple graphics primitive. A line is an object which connects two
points. Lines are drawn with the drawLine() method.
g2d.drawLine(30, 30, 200, 30);

 Basic Stroke
The BasicStroke class defines a basic set of rendering attributes for the
outlines of graphics primitives. These rendering attributes include width,
end caps, line joins, miter limit, and dash.
BasicStroke bs1 = new BasicStroke(1, BasicStroke.CAP_BUTT,
BasicStroke.JOIN_ROUND, 1.0f, dash1, 2f);
g2d.setStroke(bs1);
g2d.drawLine(20, 80, 250, 80);
 Caps
Caps are decorations applied to the ends of unclosed subpaths and dash
segments. There are three different end caps in Java
2D: CAP_BUTT, CAP_ROUND, and CAP_SQUARE.
 CAP_BUTT — ends unclosed subpaths and dash segments with no
added decoration.
 CAP_ROUND — ends unclosed subpaths and dash segments with a
round decoration that has a radius equal to half of the width of the
pen.
 CAP_SQUARE — ends unclosed subpaths and dash segments with a
square projection that extends beyond the end of the segment to a
distance equal to half of the line width.

7
 Joins
Line joins are decorations applied at the intersection of two path segments
and at the intersection of the endpoints of a subpath. There are three
decorations: JOIN_BEVEL, JOIN_MITER, and JOIN_ROUND.
 JOIN_BEVEL — joins path segments by connecting the outer corners
of their wide outlines with a straight segment.
 JOIN_MITER — joins path segments by extending their outside edges
until they meet.
 JOIN_ROUND — joins path segments by rounding off the corner at a
radius of half the line width.

In this example, we draw six basic shapes on the panel: a square, a


rectangle, a rounded rectangle, an ellipse, an arc, and a circle. The shapes
will be drawn in a gray background.

 The fillRect() method is used to draw both a rectangle and a square.


The first two parameters are x, y coordinates of a shape to be drawn.
The last two parameters are the width and the height of the shape.
g2d.fillRect(20, 20, 50, 50);
g2d.fillRect(120, 20, 90, 60);

 Here we create a rounded rectangle. The last two parameters are the
horizontal and vertical diameters of the arc at the four corners.
g2d.fillRoundRect(250, 20, 70, 60, 25, 25);

8
 The fill() method draws the interior of the given shape—an ellipse.
g2d.fill(new Ellipse2D.Double(10, 100, 80, 100));

 The fillArc() method fills a circular or elliptical arc covering the


specified rectangle. An arc is a portion of the circumference of a circle.
g2d.fillArc(120, 130, 110, 100, 5, 150);

 A circle is drawn using the fillOval() method.


g2d.fillOval(270, 130, 50, 50);

In computer graphics, we can achieve transparency effects using alpha


compositing. Alpha compositing is the process of combining an image with
a background to create the appearance of partial transparency.
The composition process uses an alpha channel. Alpha channel is an 8-bit
layer in a graphics file format that is used for expressing translucency
(transparency). The extra eight bits per pixel serves as a mask and
represents 256 levels of translucency.

9
The AlphaComposite class is used to work with transparency in Java 2D. It
implements the basic alpha compositing rules for combining source and
destination pixels to achieve blending and transparency effects with
graphics and images. To create an AlphaComposite, we provide two values:
the rule designator and the alpha value. The rule specifies how we combine
source and destination pixels. Most often it is AlphaComposite.SRC_OVER.
The alpha value can range from 0.0f (completely transparent) to 1.0f
(completely opaque).

10
Clipping is restricting of drawing to a certain area. This is done for
efficiency reasons and to create various effects. When working with the clip,
we must either work with a copy of the Graphics object or to restore the
original clip attribute. Changing the clip does not affect existing pixels; it
affects future rendering only.
g2d.clip(new Ellipse2D.Double(pos_x, pos_y, RADIUS, RADIUS));
g2d.drawImage(image, 0, 0, null);

An affine transform is composed of zero or more linear transformations


(rotation, scaling or shear) and translation (shift). Several linear
transformations can be combined into a single matrix. A rotation is a
transformation that moves a rigid body around a fixed point. A scaling is a
transformation that enlarges or diminishes objects. The scale factor is the
same in all directions. A translation is a transformation that moves every
point a constant distance in a specified direction. A shear is a
transformation that moves an object perpendicular to a given axis, with
greater value on one side of the axis than the other.
The AffineTransform is the class in Java 2D to perform affine
transformations.

We draw a rectangle. Then we do a translation and draw the same rectangle


again.
g2d.translate(150, 50);

11
This example demonstrates a rotation.

The next example demonstrates scaling of an object. Scaling is done with


the scale() method. In this method, we provide two parameters. They are
the x scale and y scale factor, by which coordinates are scaled along the x or
y axis respectively.
tx1.scale(0.5, 0.5);
12
We use the share() method.
tx2.shear(0, 1);
this shears in y axis as the number 1 is in the place of y axis.

In the following example we create an complex shape by rotating an ellipse.

Donut shape
13
The Color class is a part of Java Abstract Window Toolkit(AWT) package.
The Color class creates color by using the given RGBA values
where RGBA stands for RED, GREEN, BLUE, ALPHA or using HSB value
where HSB stands for HUE, SATURATION, BRIcomponents. The value for
individual components RGBA ranges from 0 to 255 or 0.0 to 0.1. The value
of alpha determines the opacity of the color, where 0 or 0.0 stands fully
transparent and 255 or 1.0 stands opaque.

public abstract boolean drawImage(Image img, int x, int y, ImageObserver


observer):
is used draw the specified image.

14
Changing the state of an object is known as an event. For example, click on
button, dragging mouse etc. The java.awt.event package provides many
event classes and Listener interfaces for event handling.

 Types of Event
The events can be broadly classified into two categories:
 Foreground Events - Those events which require the direct
interaction of user.They are generated as consequences of a person
interacting with the graphical components in Graphical User Interface.
For example, clicking on a button, moving the mouse, entering a
character through keyboard,selecting an item from list, scrolling the
page etc.
 Background Events - Those events that require the interaction of
end user are known as background events. Operating system
interrupts, hardware or software failure, timer expires, an operation
completion are the example of background events.

 What is Event Handling?


Event Handling is the mechanism that controls the event and decides what
should happen if an event occurs. This mechanism have the code which is
known as event handler that is executed when an event occurs. Java Uses
the Delegation Event Model to handle the events. This model defines the
standard mechanism to generate and handle the events.Let's have a brief
introduction to this model.
The Delegation Event Model has the following key participants namely:
 Source - The source is an object on which event occurs. Source is
responsible for providing information of the occurred event to it's
handler. Java provide as with classes for source object.
 Listener - It is also known as event handler.Listener is responsible
for generating response to an event. From java implementation point
of view the listener is also an object. Listener waits until it receives an
event. Once the event is received , the listener process the event an
then returns.

15
ActionListener in Java is a class that is responsible for handling all action
events such as when the user clicks on a component. Mostly, action
listeners are used for JButtons.
The method actionPerformed handles all the actions of a component,
and inside this method, you will define or write your own codes that will be
executed when an action occurred. Here’s an example on how to implement
ActionListener in Java.

16
The listener interface for receiving keyboard events (keystrokes). The class
that is interested in processing a keyboard event either implements this
interface (and all the methods it contains) or extends the
abstract KeyAdapter class (overriding only the methods of interest).
The listener object created from that class is then registered with a
component using the component's addKeyListener method. A keyboard
event is generated when a key is pressed, released, or typed. The relevant
method in the listener object is then invoked, and the KeyEvent is passed to
it. Methods of Key Listener :

17
Mouse events notify when the user uses the mouse (or similar input device)
to interact with a component. Mouse events occur when the cursor enters or
exits a component's onscreen area and when the user presses or releases
one of the mouse buttons.
The following example shows a mouse listener. At the top of the window is
a blank area (implemented by a class named BlankArea). The mouse
listener listens for events both on the BlankArea and on its container, an
instance of MouseEventDemo. Each time a mouse event occurs, a
descriptive message is displayed under the blank area. By moving the
cursor on top of the blank area and occasionally pressing mouse buttons,
you can fire mouse events.

 Methods of MouseListener :

18
The listener interface for receiving window events. The class that is
interested in processing a window event either implements this interface
(and all the methods it contains) or extends the
abstract WindowAdapter class (overriding only the methods of interest).
The listener object created from that class is then registered with a Window
using the window's addWindowListener method. When the window's status
changes by virtue of being opened, closed, activated or deactivated,
iconified or deiconified, the relevant method in the listener object is
invoked, and the WindowEvent is passed to it.

19
The Java Sound API is a low-level API for effecting and controlling the
input and output of sound media, including both audio and Musical
Instrument Digital Interface (MIDI) data.
The Java Sound API provides the lowest level of sound support on the Java
platform. It provides application programs with a great amount of control
over sound operations, and it is extensible. For example, the Java Sound
API supplies mechanisms for installing, accessing, and manipulating
system resources such as audio mixers, MIDI synthesizers, other audio or
MIDI devices, file readers and writers, and sound format converters.
The Java Sound API includes support for both digital audio and MIDI data.
These two major modules of functionality are provided in separate
packages:
 javax.sound.sampled – This package specifies interfaces for capture,
mixing, and playback of digital (sampled) audio.
 javax.sound.midi – This package provides interfaces for MIDI
synthesis, sequencing, and event transport.
The javax.sound.sampled package is fundamentally concerned with audio
transport — in other words, the Java Sound API focuses on playback and
capture.

20
The AudioSystem class acts as the entry point to the sampled-audio system
resources. This class lets you query and access the mixers that are installed
on the system. AudioSystem includes a number of methods for converting
audio data between different formats, and for translating between audio
files and streams.

21
public class ByteArrayInputStream
extends InputStream
A ByteArrayInputStream contains an internal buffer that contains bytes
that may be read from the stream. An internal counter keeps track of the
next byte to be supplied by the read method.

LoopingByteInputStream is also a method works as similar as


ByteArrayInputStream but the only difference is that it idefinitely reads
byte array in a loop until its close() method is called.

Java 3D is a new cross-platform API for developing 3D graphics


applications in Java. Its feature set is designed to enable quick development
of complex 3D applications and, at the same time, enable fast and efficient
implementation on a variety of platforms, from PCs to workstations.
The Java 3D API includes a rich feature set for building shapes, composing
behaviors, interacting with the user, and controlling rendering details.

22
 Geometry Model Model the details of every 3D shape in our graph
scene, but this requires a substantial modeling effort. The more shapes
we have the more things to draw
 Image Model Create the illusion of geometry details by taking a picture
of the "real image‖, and then attaching the image onto a simple 3D
geometry. The benefits of this approach is that realism is increased
without having to draw a large amount of geometry objects

23
A Pathfinding Algorithm is a technique for converting a graph –
consisting of nodes and edges – into a route through the graph.
This graph can be anything at all that needs traversing. For this article,
we're going to attempt to traverse a portion of the London Underground
system:

A* is one specific pathfinding algorithm, It is generally considered to be the


best algorithm to use when there is no opportunity to pre-compute the
routes and there are no constraints on memory usage.
Both memory and performance complexity can be O(b^d) in the worst case,
so while it will always work out the most efficient route, it's not always the
most efficient way to do so.
24
A* is actually a variation on Dijkstra's Algorithm, where there is additional
information provided to help select the next node to use. This additional
information does not need to be perfect – if we already have perfect
information, then pathfinding is pointless. But the better it is, the better the
end result will be.

The A* Algorithm works by iteratively selecting what is the best route so far,
and attempting to see what the best next step is.
When working with this algorithm, we have several pieces of data that we
need to keep track of. The ―open set‖ is all of the nodes that we are currently
considering. This is not every node in the system, but instead, it's every
node that we might make the next step from.
We'll also keep track of the current best score, the estimated total score and
the current best previous node for each node in the system.
As part of this, we need to be able to calculate two different scores. One is
the score to get from one node to the next. The second is a heuristic to give
an estimate of the cost from any node to the destination. This estimate does
not need to be accurate, but greater accuracy is going to yield better results.
The only requirement is that both scores are consistent with each other –
that is, they're in the same units.
At the very start, our open set consists of our start node, and we have no
information about any other nodes at all.
At each iteration, we will:
 Select the node from our open set that has the lowest estimated total
score
 Remove this node from the open set
 Add to the open set all of the nodes that we can reach from it

25
Since C++ is a high-level language that will teach you the basics of object-
oriented programming, it's a good idea to learn it. It's also the language
used to build most big console and Windows games. C++ is complemented
by C in these games, and assembly languages for creating low-level engine
modules. Scripts like Python, Lua, UnrealScript, or some in-house scripts
will thread through the code. Plus, shader code for graphics uses OpenGL,
or a similar framework. But for tackling big games in the larger gaming
companies, knowing C++ is critical. It's fast, the compilers and optimizers
are solid, and you get a lot of control over memory management. It has
extensive libraries, which come in handy for designing and powering
complex graphics. you'll find a helpful online community who are ready and
willing to answer your queries.
C++ is by no means an easy language to learn. But it can be rewarding, not
only because C++ games are easy to distribute across various platforms, but
also because you can quickly learn C# and other object-oriented languages
if you already know C++.
Both C++ and C# are widely used in popular game engines today, like
Unreal, Sony's free PhyreEngine and the indie-favorite Unity
Engine, and we all know game engines can take a lot of the grind out of
game development. You also need to remember that some game engines
like Unreal will only take C++ (unless you want to use the engine's scripting
language to script from scratch).
The C++ programming language was originally called ―C with classes.‖ It
was created to take modern principles, like object-oriented computer
programming, and combine it with the low-level features seen by
languages such as C. In so doing, it would allow users to more easily create
their programs with readability, while not losing advanced features such as
memory management. Given its general-purpose nature, C++ has, all
around, become one of the most widely used programming languages,
having applications for software and – as is the topic of this article –
games. In fact, many modern engines, such as Unreal Engine, are built
on the language, so learning to code C++ is considered key by many
professional developers.
26
While C++ is the best game creation language but it also has pros and cons :
Pros :
 Being so close to C, C++ is amazingly efficient and is one of the fastest
programming languages to choose if you have lots of complex tasks to
run in your games.
 C++ has perhaps the largest community and tutorial support given its
universal usage almost everywhere.
 Its ability to do things like memory management is very handy if you
want tighter control on game performance.
 It has a large amount of scalability and can be used for both small and
large game projects.
 It is platform-independent, meaning you can port projects around very
easily regardless of OS.

Cons :
 While there are plenty of game engines to use, finding lighter-weight
frameworks for C++ game development can be a challenge. You also
can’t easily develop games with JUST C++.
 Of the languages on this list, C++ is probably the most difficult to
learn and is the least beginner-friendly.
 Though C++ gives you more control over memory management and
the like, this comes at the cost of lacking automatic garbage collection
– which means more work on the developer’s end.
 As an older language, some modern features seen in other languages
are not present or standardized with C++.
 Since C++ allows developers to do more, this also allows less security
– meaning you could get tons of unexpected behavior in your games
without intention.

27
The Helicopter Game in C++ is an interesting game/console application
designed in the object oriented programming language C++, with the use
of SDL graphics, SDL (Simple Direct Media Layer) is a cross-platform
development library designed to provide low level access to audio,
keyboard, mouse, joystick, and graphics hardware via OpenGL and
Direct3D. It is used by video playback software, emulators, and popular
games including Valve's award winning catalog and many Humble
Bundle games.
SDL officially supports Windows, Mac OS X, Linux, iOS, and Android.
SDL is written in C, works natively with C++, and there are bindings
available for several other languages, including C# and Python.
The Helicopter Hurdle game is an excellent example of utilization of
C++ programming language in the field of game development. It
demonstrates all the basic commands, syntaxes, functions, structures as
well as concepts of file handling in C++
The Helicopter Hurdle game is very simple to start, play and terminate.
In order to start the game, you should click at the application file of the
game and there comes the game window or the main menu. In the main
menu, you will have following options to choose:
1. Play:- Click at this option to play new session of the Helicopter Game.
28
2. Options:- Click at this option for entering the menu setting of the
game. From here, you can turn sound on or off.
3. High Score:- If you want to see the high scores of the game, click at
this option.
4. Instructions:- The option tells you the rules and how to play the game.
5. Credit:- The option is included to display the name of our engineers
who helped to develop this game.
6. Quit:- If the Helicopter Game is to be terminated without playing, click
at this option.

Features:
 The use of SDL graphics and the sound have made the Helicopter
Game in C++ more realistic, entertaining and interesting for playing.
 The options in the game can be chosen with the mouse arrow.
 In Helicopter Hurdle, you have the facility of turning the sound on or
off, and there are many more functions.
In the game, you have to keep the helicopter flying without any collision
with the vertical walls or the obstacles in the game. If the helicopter collides
with any obstacles, the game is stopped and you will get back to main

29
menu. The more you are able to keep the helicopter flying without collision,
the more score you will gain.
In the Helicopter Game in C++, certain keys have been fixed to play the
game. The UP ARROW key, lifts the helicopter up or helps to gain the
height where as the DOWN ARROW key is for landing the helicopter. If no
key is pressed, the helicopter loses its height.

We have two type of files used in the game as a source code :

 Header Files (.h) .


 C++ Files (.cpp) .

The major header files used in the source code. As usual the user defined
header files are named such that it explains their respective functions, They
are :

30
1. game_functions.h :
Here are some Samples Of Lines of Codes that this file contain :
 ///LOAD THE MENU IMAGES
 menu = load_image("images/menu/menu.png");
 play_menu =
load_image("images/menu/play.png");Mix_PlayChannel(
-1,proceed,0); ///PLAYS PROCEED SOUND
 SDL_Delay(5000); ///SETS THE DELAY
 back_music=Mix_LoadWAV("sound/menu.wav");
 Mix_PlayChannel(-1,back_music,0); ///PLAYS THE
BACKGROUND MUSIC
 if(mouse_event.type==SDL_MOUSEMOTION)
///WHEN MOUSE IS IN MOTION
 x = mouse_event.motion.x; ///SET THE COORDINATES
 IF Statements Like :
if((x>960)&&(x<1210)&&(y>120)&&(y<180))
///HIGHLIGHT PLAY

{
apply_surface(0,0,play_menu,screen);
if(music_sol==0)
{
Mix_PlayChannel(-1,selection,0); ///PLAYS THE
SELECTION SOUND

music_sol=1;
}
}
 if(mouse_event.type == SDL_MOUSEBUTTONDOWN)
///IF MOUSE BUTTON IS PRESSED

31
x = mouse_event.motion.x; ///SETS THE COORDINATES

y = mouse_event.motion.y;
if((x>960)&&(x<1210)&&(y>120)&&(y<180))
{
choice = 1; ///RETURNS 1

session = false;
}
///LOAD THE OPTION IMAGES

optionsOFF = load_image("images/options off.png");


soundON = load_image("images/sound on.png");
soundOFF = load_image("images/sound off.png");
optionsback=load_image("images/options
back.png");
apply_surface(0,0,optionsOFF,screen);
SDL_Flip(screen);
int ax,ay;
bool bye = false;
music_sol = 0;
while(!bye)
{
while(SDL_PollEvent(&mouse_event))
{
 if(mouse_event.type==SDL_MOUSEMOTION)
///HIGHLIGHTS

{
32
//high_score();
 highscoreOFF=load_image("images/highscore off.png");
highscoreON=load_image("images/highscore on.png");

///Credits loop:

 creditsOFF = load_image("images/credits message


off.png");
creditsON = load_image("images/credits message on.png");
apply_surface(0,0,creditsOFF,screen);
SDL_Flip(screen);
 else if((x>960)&&(x<1205)&&(y>550)&&(y<680))
{ choice = 6; ///QUIT

session = false;
}
///Free surfaces

 SDL_FreeSurface(menu);
SDL_FreeSurface(play_menu);
SDL_FreeSurface(option_menu);
SDL_FreeSurface(Score_menu);
SDL_FreeSurface(Instruc_menu);

33
2. heli.h :
Class of the Helicopter Contains codes like :
///Takes key presses and adjusts the helicopter's velocity :
 void handle_input();

//Moves the helicopter :


 void move();

///Shows the helicopter on the screen :


 void show();

///Sets the camera over the helicopter :

 void set_camera();
private:
///The velocity of the helicopter
int xVel, yVel;
static int score; ///SCORE

///If a key was pressed


 if( event.type == SDL_KEYDOWN )
{
///Adjust the velocity

switch( event.key.keysym.sym )
{
case SDLK_UP: yVel -= HELI_HEIGHT / 2;
break;
case SDLK_DOWN: yVel += HELI_HEIGHT / 5;
break;
default:
break;
}
score+=2; }
34
 void Heli::move()
{
///Move the helicopter up or down

box.y += yVel;
boom=Mix_LoadWAV("sound/boom.wav");
///LOADS THE CRASH SOUND

 for(int i=0;i<7;++i) ///COLLISION LOOP OF THE HELICOPTER

{
///If the helicopter went too far up or down or has collided with the OBSTACLES

if( ( box.y < 0 ) || ( box.y + HELI_HEIGHT >


SCREEN_HEIGHT ) ||( check_collision( box, wall2 )||
check_collision(box,wall3[i])))
{
///Move back

box.y -= yVel;
Mix_FreeMusic( music );
heli=NULL;
heli=load_image("images/dandan edited.png",1);
///LOADS THE CRASH IMAGE

game_over=load_image("images/game_over.png");
apply_surface(box.x,box.y,heli,screen);
SDL_Flip(screen);
Mix_PlayChannel(-1,boom,0); ///PLAYS THE CRASH SOUND

SDL_Flip(screen);

35
///LOADS THE GAME OVER IMAGE

apply_surface(0,0,game_over,screen);
SDL_Delay(2000);
SDL_Flip(screen); }
 apply_surface( box.x - camera.x, box.y - camera.y, heli,
screen );
///Show the helicopter

 if( camera.x < 0 ) ///Keep the camera in bounds

{ camera.x = 0; }
if( camera.y < 0 )
{ camera.y = 0; }
if( camera.x > LEVEL_WIDTH - camera.w )
{ camera.x = LEVEL_WIDTH - camera.w; }
if( camera.y > LEVEL_HEIGHT - camera.h )
{ camera.y = LEVEL_HEIGHT - camera.h; } }

3. loader.h :
Contains Such Codes :
 SDL_Surface *load_image( std::string filename,intn=0 )
///FUNCTION FOR LOADING IMAGE

{
///The image that's loaded

SDL_Surface* loadedImage = NULL ;

36
 Uint32 colorkey = SDL_MapRGB( optimizedImage->format,
73, 203, 58 ); ///Map the color key

///Set all pixels of color R 0, G 0xFF, B 0xFF to be transparent


SDL_SetColorKey( optimizedImage,
SDL_SRCCOLORKEY, colorkey );
 music = Mix_LoadMUS( "sound/heli-running2.wav" );
///Load the game music
 void clean_up()
{
///Free the surface

SDL_FreeSurface( heli );
SDL_FreeSurface(OBSTACLES);
///Close the font that was used

TTF_CloseFont( font );
///Free the music

Mix_FreeMusic( music );
Mix_FreeChunk(boom);

4. constants.h :
Contains Codes Like :
 const int FRAMES_PER_SECOND = 50;
const int SCREEN_BPP = 32;
const int LEVEL_WIDTH = 1366;
SDL_Rect wall2;
SDL_Rect wall3[7];
///NAMESPACE CONTAINGIN ALL THE CONSTANTS

37
5. play.h :
Contains such codes :
 void wall3_coord()
///SETS COORDINATES OF THE OBSTACLES

{
wall3[0].x =0; wall3[0].w=30; wall3[0].h=234;
wall3[0].y =0;
wall3[1].x =0; wall3[1].w=30; wall3[1].h=234;
wall3[1].y =400;

 if( Mix_PlayMusic( music, 0 ) == -1 )


///PLAY THE GAME MUSIC
{ return 1; }

 while( SDL_PollEvent( &event ) )


{ ///While there's events to handle

///Handle window events

myWindow.handle_events();
///Handle events for the heli

myheli.handle_input()

 if(event.type==SDL_KEYDOWN)
{ ///If escape was pressed

if( event.key.keysym.sym==SDLK_ESCAPE) {
Mix_FreeMusic( music );
quit=true; } 38
 if( event.type == SDL_QUIT )
{ ///If the user has Xed out the window
///Quit the program

quit = true; }
6. variable.h :
Contains Codes such as :
 #ifndef VARIABLES_H_INCLUDED
#define VARIABLES_H_INCLUDED
///SDL SURFACE POINTERS

SDL_Surface *game_over=NULL;
SDL_Surface *background = NULL;
SDL_Surface *background = NULL;
SDL_Surface *OBSTACLES= NULL;
SDL_Surface *credits=NULL;
Mix_Music *music = NULL;
///MUSIC VARIABLES

Mix_Chunk *back_music=NULL;
Mix_Chunk *boom=NULL;
///Main Menu images

SDL_Surface* menu =NULL;


SDL_Surface* Score_menu = NULL;
SDL_Event event;
SDL_Event mouse_event;
SDL_Color textColor = { 255, 0, 0};

39
7. window.h :
Contains Such Codes :
 screen = SDL_SetVideoMode( SCREEN_WIDTH,
SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE |
SDL_FULLSCREEN ); ///Set up the screen

 screen = SDL_SetVideoMode( event.resize.w, event.resize.h,


SCREEN_BPP, SDL_SWSURFACE | SDL_RESIZABLE );
///Resize the screen

 else if( ( event.type == SDL_KEYDOWN ) && (


event.key.keysym.sym == SDLK_RETURN ) )
{ ///If enter was pressed

toggle_fullscreen(); ///Turn fullscreen on/off

 screen = SDL_SetVideoMode( SCREEN_WIDTH,


SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE |
SDL_RESIZABLE | SDL_FULLSCREEN );
///Set the screen to fullscreen

 if( screen == NULL )


{ ///If there's an error

windowOK = false;
return;
}

40
8. obstacle.h :
Contains Such Codes :
 SDL_Rect camera = { 0, 0, SCREEN_WIDTH,
SCREEN_HEIGHT };
bool check_collision( SDL_Rect A, SDL_Rect B )
{
///The sides of the rectangles

int leftA, leftB;


int rightA, rightB;
int topA, topB;
int bottomA, bottomB;
///Calculate the sides of rect A

leftA = A.x;
rightA = A.x + A.w;
topA = A.y;
bottomA = A.y + A.h;
///If any of the sides from A are outside of B

if( bottomA <= topB )


{ return false; }

if( topA >= bottomB )


{ return false; }

41
Contains Two Files :
1. main.cpp :
Contains such codes :
 #include "SDL.h"
#include "SDL_image.h"
#include <SDL_mixer.h>
#include <string>
#include "heli.h"
#include "loader.h"
#include "timer.h"
#include "window.h"
#include "obstacles.h"
#include "game_functions.h"
#include "play.h"
///THE HEADER FILES

 my.toggle_fullscreen();
wel_come(); ///WELCOME SCREEN FUNCTION CALL

int opt;
while(cont) {
opt=game_menu(); ///GAME MENU FUNCTION CALL

switch(opt) {

42
2. timer.cpp :
Contains such codes :
 void Timer::start()
{
//Start the timer

started = true;

//Unpause the timer

paused = false;

//Get the current clock time


startTicks = SDL_GetTicks(); }

 void Timer::pause() {
//If the timer is running and isn't already paused

if( ( started == true ) && ( paused == false ) )


{ //Pause the timer

paused = true;

43
Game programmers commonly use Java for game development, because
Java supports multithreading and sockets. Multithreading uses less
memory and makes the most of available CPU, without blocking the user
out when heavy processes are running in the background. Sockets help in
building multiplayer games. Plus, Java runs on a virtual machine, so your
game will be easier to distribute. In comparison to programming languages
like C++, Java is easier to write, debug, learn and compile.
There are many programming languages that do certain tasks well while
others do the same task better. Most modern games use the language(s)
supported by the game’s engine. Engines are chosen using a number of
factors, such as cost, platform availability, and technical limitations. For
example, Unity is affordable, can publish applications for a variety of
platforms, and supports several languages for object scripting (C#,
Javascript, and Boo). If you are building your own engine, then use what
you are comfortable with. Most languages have libraries for DirectX or
OpenGL support.
the best language for programming games in 2020 are:
C++ , C# , JAVA , JavaScript , HTML5

C++ is the king of game programming languages. Not only is it one


of the fastest languages (because it compiles to machine language),
it has a whole ecosystem that caters to it. C# is good too, but it uses
automatic garbage collection, which can hinder performance. Some
professional games have been made in C#, but because of this
drawback, C++ still reigns supreme.

44
 https://www.quora.com/Which-is-the-best-programming-
language-to-use-for-developing-games
 https://www.freelancer.com/articles/programming/what-is-
the-best-programming-language-for-games
 https://codegym.cc/groups/posts/182-java-game-
programming-for-beginners-where-to-start
 https://gamedevacademy.org/best-game-development-
languages/#About-3
 https://www.codewithc.com/helicopter-game-in-c-sdl/
 https://www.cs.miami.edu/home/visser/csc329-files/Games-
Threads.pdf
 https://www.researchgate.net/publication/337604169_Multit
hreading_in_game_development
 https://www.guru99.com/multithreading-java.html
 https://docs.oracle.com/javase/tutorial/2d/overview/index.ht
ml
 https://zetcode.com/gfx/java2d/basicdrawing/
 https://www.javatpoint.com/Displaying-image-in-swing
 https://www.geeksforgeeks.org/java-awt-color-class/
 https://www.tutorialspoint.com/awt/awt_event_handling.ht
m
 https://javapointers.com/java/java-se/actionlistener/
 https://docs.oracle.com/javase/7/docs/api/java/awt/event/K
eyListener.html
 https://docs.oracle.com/javase/tutorial/uiswing/events/mous
elistener.html
 https://docs.oracle.com/javase/8/docs/api/java/awt/event/
WindowListener.html
 https://docs.oracle.com/javase/tutorial/sound/index.html
 https://docs.oracle.com/javase/7/docs/api/javax/sound/sam
pled/AudioSystem.html
 https://docs.oracle.com/javase/7/docs/api/java/io/ByteArray
InputStream.html
 https://webdocs.cs.ualberta.ca/~anup/Courses/604/NOTES/
J3Dtexture.pdf
 https://users.cs.jmu.edu/bernstdh/web/common/lectures/su
mmary_java3d-texture-mapping.php
 https://www.baeldung.com/java-a-star-pathfinding

You might also like