Calculating Air Resistance

Written in C++ this is a simple console application which calculates the trajectory of a projectile with air resistance applied. The coordinates are printed to a text file.

This was created for the first Maths & Physics Assignment of year 1 as an added extra.

#include "stdafx.h"
#include <iostream>
#include <math.h>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
const double PI = 3.14159265359;

struct XYCoords
{
 double x;
 double y;
};

vector<XYCoords> plotPoints;
XYCoords temp;
double x = 0; // x co-ordinate
double y = 0; // y co-ordinate

void fillVector()
{
 temp.x = x;
 temp.y = y;
 plotPoints.push_back(temp);
}

void openToFile(string filename, const vector<XYCoords>& v)
{
 ofstream openstream{ filename };
 if (!openstream) { cout << "Error, can't open output file" + filename << endl; }

 for (int i = 0; i < v.size(); ++i)
 {
  openstream << "x " << v[i].x << " y " << v[i].y << endl;
 }

}

int main()
{
 //constants of grenade
 double m = 0.39; //mass kg
 double radius = 0.03175; // radius of grenade in meters
 double ar = PI*(radius*radius); //area of grenade
 double cD = 0.5; // drag co-efficient
 double p = 1.225; //air density
 double d = (p*cD*ar) / 2; //drag
 double g = 9.81; //gravity

 //initial conditions
 double deltaT = 0.1; //time interval
 double deltaT2 = deltaT*deltaT; //delta time squared
 double v = 35; // velocity
 double theta = 60; // angle at launch
 double vx = v*cos(theta*(PI / 180)); // initial x velocity
 double vy = v*sin(theta*(PI / 180)); // initial y velocity
 double t = 0; // time
 double ax = -(d / m)*v*vx; // initial acceleration on x
 double ay = -g - (d / m)*v*vy; // initial acceleration on y

 //start loop
 int loop = 1; // counts the number of plot points
 while (y > -0.001) // start a loop and continue looping until the y co-ordinate goes below -0.001
 {
  //Step 5 - calculate acceleration components
  ax = -(d / m)*v*vx;
  ay = -g - (d / m)*v*vy;

  //Step 6 - Push Co-ordinates back into Vector
  fillVector();
  ++loop;

  //Step 7 - calculate new velocity
  vx = vx + ax*deltaT;
  vy = vy + ay*deltaT;

  //Step Eight - calculate new co-ordinates
  x = x + (vx*deltaT) + (0.5*ax*deltaT2);
  y = y + (vy*deltaT) + (0.5*ay*deltaT2);

  //Step 9 - increment time by delta time
  t = t + deltaT;

  //Step 9 - recalculate velocity
  v = sqrt((vx*vx) + (vy*vy));

 }

 //write to a text file
 openToFile("airResistanceCoords.txt", plotPoints);

    return 0;
}

Combo Box Selection Example

This is a small section of a database front end application written in C#. The database was designed to handle account data for an MMORPG. This form stores information for in game purchases but uses 3 different comboboxes which take data from other entities. The information displayed in each combobox can change depending on the chosen selection.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MySQL_Interface
{
    public partial class ingamepurchase_form : Form
    {
        Form1 firstformRef;         //reference to main form
        bool insertFlag = false;    //are we in update mode?
        string updateId = "";       //record update ID if required

        //db object
        DBConnection mySqlSrc = new DBConnection();

        public ingamepurchase_form(ref Form1 form1Handle, bool isInsert, string upId)
        {
            //set vars from constructor locals
            updateId = upId;
            insertFlag = isInsert;
            firstformRef = form1Handle;
            InitializeComponent();

            //Bind comboBox to dictionary
            //This allows us a key - value pair

            //*********-------------CHARACTER COMBOBOX----------------*****
            Dictionary<string, string> igpCharIDItem = new Dictionary<string, string>();

            //Get a new list for results of CHARACTER table
            List<string>[] results = new List<string>[7];
            results = mySqlSrc.SelectCharacter();

            //count the rows
            int rows = results[0].Count;
            for (int i = 0; i < rows; ++i)
            {
                //[column][row]
                //add to the dictionary object the ID
                igpCharIDItem.Add(results[0][i], results[4][i]);
            }

            //bind the dictionary object and set Key -> Value
            //as id _> name
            igp_charID_cb.DataSource = new BindingSource(igpCharIDItem, null);
            igp_charID_cb.DisplayMember = "Value";
            igp_charID_cb.ValueMember = "Key";

            //*********-------------CATAGORY COMBOBOX----------------*****
            Dictionary<string, string> igpcatItem = new Dictionary<string, string>();
            igpcatItem.Add("1", "Item");
            igpcatItem.Add("2", "Weapon");
            igpcatItem.Add("3", "Armour");
            int c_rows = igpcatItem.Count;

            //bind the dictionary object and set Key -> Value
            //as id _> name
            igp_cat_cb.DataSource = new BindingSource(igpcatItem, null);
            igp_cat_cb.DisplayMember = "Value";
            igp_cat_cb.ValueMember = "Key";


            //*********-------------ITEM COMBOBOX----------------*****
            igp_cat_cb.SelectedIndexChanged += new EventHandler(igp_item_cb_SelectedIndexChanged);

            igp_item_cb.SelectedIndexChanged += new EventHandler(igp_price_txt_TextChanged);

            //get item results
            List<string>[] iresults = new List<string>[6];
            iresults = mySqlSrc.SelectItem();

            //get weapon results
            List<string>[] wresults = new List<string>[6];
            wresults = mySqlSrc.SelectWeapon();

            //get armour results
            List<string>[] aresults = new List<string>[6];
            aresults = mySqlSrc.SelectArmour();

            //count the rows
            int arows = aresults[0].Count;
            int wrows = wresults[0].Count;
            int irows = iresults[0].Count;

            //------------------------------if not insert mode (update mode)
            if (!insertFlag)
            {
                //create new results list
                List<string>[] upResults = new List<string>[5];

                //send ID to get results
                upResults = mySqlSrc.SelectInGamePurchaseRow(updateId);

                //update combo box
                //get CHARACTER ID from the selected record
                string temp_charID = upResults[1][0].ToString();
                //get TYPE ID from the selected record
                string temp_typeID = upResults[2][0].ToString();
                //get TYPE ID from the selected record
                string temp_name = upResults[3][0].ToString();

                //loop through rows of full CHARACTER results
                //(to loop through combo box)
                for (int i = 0; i < rows; ++i)
                {
                    //get the account_id of the current combo box index
                    string value = ((KeyValuePair<string, string>)igp_charID_cb.Items[i]).Key;

                    //if the value matches the current character_id
                    //set the SelectedIndex to this interation
                    //To display correct character
                    if (value == temp_charID)
                        igp_charID_cb.SelectedIndex = i;
                }

                //loop through rows of full CATAGORY results
                //(to loop through combo box)
                for (int i = 0; i < c_rows; ++i)
                {
                    //get the account_id of the current combo box index
                    string value = ((KeyValuePair<string, string>)igp_cat_cb.Items[i]).Key;

                    //if the value matches the current CAT ID
                    //set the SelectedIndex to this interation
                    //To display correct character
                    if (value == temp_typeID)
                        igp_cat_cb.SelectedIndex = i;
                }



                //loop through rows of full ITEM TYPE results
                //(to loop through combo box)
                if(((KeyValuePair<string, string>)igp_cat_cb.SelectedItem).Value.ToString() == "Item")
                {
                    for (int i = 0; i < irows; ++i)
                    {
                        //get the id of the current combo box index
                        string value = ((KeyValuePair<string, string>)igp_item_cb.Items[i]).Value;

                        //if the value matches the current ITEM ID
                        //set the SelectedIndex to this interation
                        //To display correct character
                        if (value == temp_name)
                            igp_item_cb.SelectedIndex = i;
                    }
                }
                if (((KeyValuePair<string, string>)igp_cat_cb.SelectedItem).Value.ToString() == "Armour")
                {
                    for (int i = 0; i < arows; ++i)
                    {
                        //get the id of the current combo box index
                        string value = ((KeyValuePair<string, string>)igp_item_cb.Items[i]).Value;

                        //if the value matches the current ITEM ID
                        //set the SelectedIndex to this interation
                        //To display correct character
                        if (value == temp_name)
                            igp_item_cb.SelectedIndex = i;
                    }
                }
                if (((KeyValuePair<string, string>)igp_cat_cb.SelectedItem).Value.ToString() == "Weapon")
                {
                    for (int i = 0; i < wrows; ++i)
                    {
                        //get the id of the current combo box index
                        string value = ((KeyValuePair<string, string>)igp_item_cb.Items[i]).Value ;

                        //if the value matches the current ITEM ID
                        //set the SelectedIndex to this interation
                        //To display correct character
                        if (value == temp_name)
                            igp_item_cb.SelectedIndex = i;
                    }
                }


                //update text box
                igp_price_txt.Text = upResults[4][0].ToString();
            }
        }

        private bool ValidateFields()
        {
            //valid flag and messagte
            bool validFlag = true;
            string validMsg = "";

            if (igp_charID_cb.Text.ToString() == "")
            {
                //if not update message and flag
                validMsg += "You need to select a character!";
                validFlag = false;
            }

            if (igp_cat_cb.Text.ToString() == "")
            {
                //if not update message and flag
                validMsg += "You need to select a catagory!";
                validFlag = false;
            }

            if (igp_item_cb.Text.ToString() == "")
            {
                //if not update message and flag
                validMsg += "You need to select an Item!";
                validFlag = false;
            }

            if (igp_price_txt.Text.ToString() == "")
            {
                //if not update message and flag
                validMsg += "Price has not been updated!";
                validFlag = false;
            }
                //if invalid show message
                if (!validFlag)
                MessageBox.Show(validMsg);

            //return result
            return validFlag;

        }

        private void ins_igp_btn_Click(object sender, EventArgs e)
        {
            //check if insert or update mode; send relevant data
            //to relevant methods to run queries following
            //validation checks
            if (insertFlag)
            {

                if (ValidateFields())
                {
                    mySqlSrc.InsertInGamePurchase(((KeyValuePair<string, string>)igp_charID_cb.SelectedItem).Key.ToString(),        //send character ID
                                                  ((KeyValuePair<string, string>)igp_cat_cb.SelectedItem).Key.ToString(),          //send itemtype ID
                                                  ((KeyValuePair<string, string>)igp_item_cb.SelectedItem).Value.ToString(),        //send item name
                                                  igp_price_txt.Text.ToString());                                                        //send item price
                    this.Close();
                }
            }
            else
            {
                if (ValidateFields())
                {
                    mySqlSrc.UpdateInGamePurchase(updateId, ((KeyValuePair<string, string>)igp_charID_cb.SelectedItem).Key.ToString(),        //send character ID
                                                            ((KeyValuePair<string, string>)igp_cat_cb.SelectedItem).Key.ToString(),          //send itemtype ID
                                                            ((KeyValuePair<string, string>)igp_item_cb.SelectedItem).Value.ToString(),        //send item name
                                                            igp_price_txt.Text.ToString());                                                   //send item price
                    this.Close();
                }
            }
        }

        //form closing event
        private void ingamepurchase_form_FormClosing(object sender, FormClosingEventArgs e)
        {
            firstformRef.ingamepurchaseFormIsOpen = false;
            firstformRef.SelectInGamePurchaseResults();
        }

        private void igp_cat_cb_SelectedIndexChanged(object sender, EventArgs e)
        {
            Dictionary<string, string> igpitemItem = new Dictionary<string, string>();

            if (((KeyValuePair<string, string>)igp_cat_cb.SelectedItem).Value.ToString() == "Item")
            {
                //Get a new list for results of ITEM table
                List<string>[] iresults = new List<string>[6];
                iresults = mySqlSrc.SelectItem();

                //count the rows
                int irows = iresults[0].Count;
                for (int i = 0; i < irows; ++i)
                {
                    //[column][row]
                    igpitemItem.Add(iresults[0][i], iresults[1][i]);
                }
            }

            if (((KeyValuePair<string, string>)igp_cat_cb.SelectedItem).Value.ToString() == "Weapon")
            {
                //Get a new list for results of WEAPON table
                List<string>[] wresults = new List<string>[6];
                wresults = mySqlSrc.SelectWeapon();

                //count the rows
                int wrows = wresults[0].Count;
                for (int i = 0; i < wrows; ++i)
                {
                    //[column][row]
                    //add to the dictionary object the ID
                    igpitemItem.Add(wresults[0][i], wresults[1][i]);
                }
            }

            if (((KeyValuePair<string, string>)igp_cat_cb.SelectedItem).Value.ToString() == "Armour")
            {
                //Get a new list for results of ARMOUR table
                List<string>[] aresults = new List<string>[6];
                aresults = mySqlSrc.SelectArmour();

                //count the rows
                int arows = aresults[0].Count;
                for (int i = 0; i < arows; ++i)
                {
                    //[column][row]
                    //add to the dictionary object the ID
                    igpitemItem.Add(aresults[0][i], aresults[1][i]);
                }
            }

            //bind the dictionary object and set Key -> Value
            //as id _> name
            igp_item_cb.DataSource = new BindingSource(igpitemItem, null);
            igp_item_cb.DisplayMember = "Value";
            igp_item_cb.ValueMember = "Key";
        }

        private void igp_item_cb_SelectedIndexChanged(object sender, EventArgs e)
        {
            //------------------------Get a new list for results of ITEM table
            List<string>[] iresults = new List<string>[6];
            iresults = mySqlSrc.SelectItem();

            List<string>[] wresults = new List<string>[6];
            wresults = mySqlSrc.SelectWeapon();

            List<string>[] aresults = new List<string>[6];
            aresults = mySqlSrc.SelectArmour();

            //count the rows
            int arows = aresults[0].Count;
            int wrows = wresults[0].Count;
            int irows = iresults[0].Count;

            if (((KeyValuePair<string, string>)igp_cat_cb.SelectedItem).Value.ToString() == "Armour")
            {
                for (int i = 0; i < arows; ++i)
                {
                    //[column][row]
                    //add to the dictionary object the ID
                    if (((KeyValuePair<string, string>)igp_item_cb.SelectedItem).Key.ToString() == aresults[0][i])
                        igp_price_txt.Text = aresults[5][i];
                }
            }

            if (((KeyValuePair<string, string>)igp_cat_cb.SelectedItem).Value.ToString() == "Weapon")
            {
                for (int i = 0; i < wrows; ++i)
                {
                    //[column][row]
                    if (((KeyValuePair<string, string>)igp_item_cb.SelectedItem).Key.ToString() == wresults[0][i])
                        igp_price_txt.Text = wresults[5][i];
                }
            }

            if (((KeyValuePair<string, string>)igp_cat_cb.SelectedItem).Value.ToString() == "Item")
            {
                for (int i = 0; i < irows; ++i)
                {
                    //[column][row]
                    if (((KeyValuePair<string, string>)igp_item_cb.SelectedItem).Key.ToString() == iresults[0][i])
                        igp_price_txt.Text = iresults[5][i];
                }
            }
        }

        private void igp_price_txt_TextChanged(object sender, EventArgs e)
        {
        }
    }
}

Exporting Databases to Webpages Example

This was created for the last assignment of Database Concepts & Programming and written in C#. The button "outputdb_btn_Click" is a button on the main page of a database application. When clicked it opens up the database in the default web browser as a html file with css styles applied. Currently only the account entity is exported.

The function also creates a matching XML file and a well formed XSD file.

        //
        //
        //-----------------OUTPUT DATABASE AS XML, XSD & XSLT
        //
        //

        //get account details for each account and push them into a data set to
        //create XML and XSD files
        private void outputdb_btn_Click(object sender, EventArgs e)
        {
            var ds = new DataSet("Accounts");
            var dt = ds.Tables.Add("Account");
            dt.Columns.Add("ID", typeof(string));
            dt.Columns.Add("username", typeof(string));
            dt.Columns.Add("firstname", typeof(string));
            dt.Columns.Add("surname", typeof(string));
            dt.Columns.Add("phonenumber", typeof(string));
            dt.Columns.Add("email", typeof(string));
            dt.Columns.Add("password", typeof(string));


            //create results list
            List<string>[] results = new List<string>[7];

            //get results
            results = mySqlSrc.SelectAccount();

            //count the rows
            int rows = results[0].Count;

            //loop through each row
            for (int i = 0; i < rows; ++i)
            {
                //[column][row]
                dt.Rows.Add(results[0][i],    //account id
                                    results[1][i],    //account username
                                    results[2][i],    //account fname
                                    results[3][i],    //accoutn sname
                                    results[4][i],    //account phonenum
                                    results[5][i],    //account email
                                    results[6][i]);   //account password
            }

            //for use with stylesheets that use DOCTYPE
            //Prevents security error however this is a prototype and unfinished
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.DtdProcessing = DtdProcessing.Parse;

            //Convert the data set into an XML file
            string xmlData = ds.GetXml();
            string filepath = "dbxml.xml";
            ds.WriteXml(filepath);

            //Convert the Data set into an XSD file
            string xmlSchema = ds.GetXmlSchema();
            string filepath2 = "dbxmlschema.xsd";
            ds.WriteXmlSchema(filepath2);

            //Transfrom either the xsd or xml into a styled webpage using the pre-defined stylesheet
            var myxslTrans = new XslCompiledTransform();
            myxslTrans.Load("stylesheet.xsl");
            myxslTrans.Transform(filepath, "result.html");

            //launch webpage
            System.Diagnostics.Process.Start("result.html");
        }
    }
}

Tic Tac Toe Server Example

Written in Python, this was created for the last assignment of Networking Concepts in Year 1. There are 2 other files player1.py and player2.py which interact with server.py. The player files contain the game board and main game loop. This works over a local network and allows players to play Tic Tac Toe on different computers.

Server.py

import socket, select

#function to broadcast chat messages to all connected clients
def broadcast_data (sock, message):
    #do not send the message to master socket and the client who has sent the message
    for socket in CONNECTION_LIST:
        #for each socket in the connection list do this:
        if socket != server_socket and socket != sock:      #if the socket is not equal to the server socket and the socket that sent the message, do this:
            try:
                socket.send(message)        #send the message to the other socket
            except:
                #broken socket connection may be, chat client pressed ctrl+c for example
                socket.close()      #close the connection and remove it from the list of connected sockets
                CONNECTION_LIST.remove(socket)
if __name__== "__main__":

    #list to keep track of socket descriptors
    CONNECTION_LIST = []
    RECV_BUFFER = 4096  #data buffer size
    PORT = 5004         #port number

    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)       #create a stream socket called server_socket
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server_socket.bind(('', PORT))      #bind port number to the address, left empty so it can be any address the server is on
    server_socket.setblocking(0)        #set the port to non-blocking so it can listen for other connections and talk to them instead of waiting for one client
    server_socket.listen(10)            #keep listening for connections, allow up to 10

    #add server socket to list or readable connections
    CONNECTION_LIST.append(server_socket)
    print socket.gethostname()      #prints the name of the host the server is on
    print "Tic Tac Toe server started in port " + str(PORT)
    while 1:
        #get the list sockets which are ready to be read through select
        read_sockets, write_sockets, error_sockets = select.select(CONNECTION_LIST,[],[])
        for sock in read_sockets:       #for every sock in read_sockets do this:
            #new connection
            if sock == server_socket:
                #if the incoming connection has the same details, accept the client and add it's address to the connection list, printing that it has connected
                sockfd, addr = server_socket.accept()           #accept the connection
                CONNECTION_LIST.append(sockfd)                  #push back connection details into the list
                print "Client (%s, %s) connected" % addr

            #some incoming message from a client
            else:
                try:
                    #get the incoming data, if there is something, send it to the other clients connected to the server
                    data = sock.recv(1024)
                    if data:
                        broadcast_data(sock, data)
                except:
                    #if a client disconnects print a message saying the client has disconnected, close the associating socket and remove it from the connection list
                    broadcast_data(sock, "Client (%s, %s) is offline" % addr)
                    print "Client %s, %s) is offline" % addr
                    sock.close()
                    CONNECTION_LIST.remove(sock)
                    continue

    server_socket.close()     
                    

Super SEGD World Main Game Loop

Written primarily in C++ (utilising C elements) this is the main game loop of my Super Mario World Clone, created for the second assignment of 2D Games Programming.

//Super Segd World
//Game.cpp
//Main Program

#include "DXHandle.h"
#include "Background.h"
#include "Player.h"
#include "Enemy.h"
#include "Controls.h"
#include "Items.h"
#include "HUD.h"
#include "GameStates.h"
#include "TitleScreen.h"

//title of app
const string APPTITLE = "Super Segd World";

//Game Initialisation
bool Game_Init(HWND window)
{

 //set random number seed
 srand(time(NULL));

 //Initialise Direct 3D for use, return error message if something goes wrong
 if (!Direct3D_Init(window, SCREENW, SCREENH, false))
 {
  MessageBox(0, "Error initialising Direct3D", "Error", 0);
  return false;
 }

 //Initialise Direct Input for use, return error message if something goes wrong
 if (!DirectInput_Init(window))
 {
  MessageBox(0, "Error initialising DirectInput", "Error", 0);
  return false;
 }

 //Initialise Direct Sound for use, return error message if something goes wrong
 if (!Init_DirectSound(window))
 {
  MessageBox(0, "Error initialising DirectSound", "Error", 0);
  return false;
 }

 //load sprite textures 
 loadStartScreen();

 //-----------------------------------------------------MARIO
 Mario_obj = LoadTexture("marioimage.png", bgcolour);
 errorWithLoad("marioimage.png", Mario_obj);

 //-----------------------------------------------------ITEMS
 ItemBlock_obj = LoadTexture("itemblock.png", bgcolour);
 errorWithLoad("itemblock.png", ItemBlock_obj);

 CoinBlock_obj = LoadTexture("coinblock.png", bgcolour);  //also used for plain block
 errorWithLoad("coinblock.png", CoinBlock_obj);

 Items_obj = LoadTexture("items.png", bgcolour);
 errorWithLoad("items.png", Items_obj);

 Coins_obj = LoadTexture("coin.png", bgcolour);
 errorWithLoad("coin.png", Coins_obj);

 GoalPosts_obj = LoadTexture("goalposts.png", bgcolour);
 errorWithLoad("goalposts.png", GoalPosts_obj);

 GoalBar_obj = LoadTexture("goalbar.png", bgcolour);
 errorWithLoad("goalbar.png", GoalBar_obj);

 Fireball_obj = LoadTexture("fireball.png", bgcolour);
 errorWithLoad("fireball.png", Fireball_obj);

 //---------------------------------------------------ENEMIES
 RedShell_obj = LoadTexture("spinredshell.png", bgcolour);
 errorWithLoad("spinredshell.png", RedShell_obj);

 RedTurtle_obj = LoadTexture("redturtle.png", bgcolour);
 errorWithLoad("returtle.png", RedTurtle_obj);

 Thwomp_obj = LoadTexture("thwomp.png", bgcolour);
 errorWithLoad("thwomp.png", Thwomp_obj);

 BulletBill_obj = LoadTexture("bulletbill.png", bgcolour);
 errorWithLoad("bulletbill.png", BulletBill_obj);

 ReznorBackground_obj = LoadTexture("reznorbackground.png", bgcolour);
 errorWithLoad("reznorbackground.png", ReznorBackground_obj);

 ReznorPlatform_obj = LoadTexture("reznorplatform.png", bgcolour);
 errorWithLoad("reznorplatform.png", ReznorPlatform_obj);

 Reznor_obj = LoadTexture("reznor.png", bgcolour);
 errorWithLoad("reznor.png", Reznor_obj);

 ReznorFireball_obj = LoadTexture("reznorfireball.png", bgcolour);
 errorWithLoad("reznor.png", ReznorFireball_obj);

 //-------------------------------------------------------HUD
 HUD_obj = LoadTexture("huddisplay.png", bgcolour);
 errorWithLoad("huddisplay.png", HUD_obj);

 ItemBoxHUD_obj = LoadTexture("iteminbox_hud.png", bgcolour);
 errorWithLoad("iteminbox_hud.png", ItemBoxHUD_obj);



 //set properties for sprites
 //-----------------------------------------------------MARIO
 Mario.setValues(10, 465, 7, 16, 40, 60, 7, 15, 0, 2, 2, 1, 1, health1, 0);
 createMarioRect();

 //-------------------------------------------------------HUD
 createHUDvalues();

 //-----------------------------------------------------ITEMS
 createItemBlocks();
 createItems();
 createCoinBlocks();
 createPlainBlocks();
 createCoinsForCoinBlocks();
 createCoinsForPlainBlocks();
 createGoalPosts();

 //---------------------------------------------------ENEMIES
 createRedShells();
 createRedTurtles();
 createThwomps();
 createBulletBills();
 createReznor();

 //load background image
 buildBackground();

 //music
 loadmusic();

 //get the back buffer surface
 d3ddev->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &backbuffer);

 return true;
}

//Game Update
void Game_Run(HWND window)
{
 //run gamestates
 startGame();

 //display back buffer on the screen
 d3ddev->Present(NULL, NULL, NULL, NULL);
 
 //escape key exits
 if (Key_Down(DIK_ESCAPE))
  gameover = true;

 //controller back button also exits
 if (controllers[0].wButtons & XINPUT_GAMEPAD_BACK)
  gameover = true;
}

//Game Shutdown
void Game_End()
{
 //free memory and shut down
 HUDShutdown();
 enemyObjShutdown();
 itemObjShutdown();
 playerObjShutdown();
 backgroundShutdown();
 DirectInput_Shutdown();
 Direct3D_Shutdown();
}

Super SEGD World Enemy Example

This is the AI for one of the enemies in my game created for 2D Games programming. The first function updates the animation of the enemy each loop and checks for collision with characters. The enemy is placed on a platform and rotates in a circle. The second function animates the fireball delivered by the enemy and checks for collision each loop.

 void updateReznor(SPRITE* whichReznor, SPRITE* whichPlatform)
{
 //while reznor has health
  if (whichReznor->health > 0)
  {
  //has animation delay reached threshold?
  if (++whichReznor->animcount > whichReznor->animdelay)
  {
   //reset counter
   whichReznor->animcount = 0;
   //animate the sprite
   if (++whichReznor->curframe > 1)
    whichReznor->curframe = 0;

   //if reznor curframe is equal to 1, release a fireball
   if (whichReznor->curframe == 1)
   {
    if (Mario.x > 3800)
    {
     PlaySound(reznor);
     lState = bossFight;
     ReznorFireball.setValues(whichReznor->x + 45, whichReznor->y + 50, 0, 3, 40, 40, 0, 2, 0, 2, 2, 0, 1, nohealth, 0);
     reznorfireballvector.push_back(ReznorFireball);
    }

   }
  }

  //make the reznor move in a circle on the platform
  angle += 0.0005f;
  double rez1x = 0;
  double rez1y = 0;
  
  rez1x = cos(angle) * radius;
  rez1y = sin(angle) * radius;

  rez1x += centerpointX;
  rez1y += centerpointY;

  reznorvector[0].x = rez1x;
  reznorvector[0].y = rez1y;
  reznorplatformvector[0].x = rez1x + 19;
  reznorplatformvector[0].y = rez1y + 99;

  //if there is a collision between mario and reznor
  if (CollisionD(Mario, reznorvector[0]))
  {
   Mario.health -= reznorvector[0].damage;
   Mario.x -= 150;
  }
  }

  //if reznor has no health, make it fall off screen
  if (whichReznor->health <= 0)
  {
   if (whichReznor->state == nohealth)
   {
    whichReznor->x += 0.02f;
    whichReznor->y += 0.3f;

    if (whichReznor->y >= 620)
     whichReznor->y = 700;
   }
   else
   {
    whichReznor->state = nohealth;
    Mario.score += whichReznor->score; //give mario points for killing reznor
   }
  }
}

 void updateReznorFireballs()
 {
  //only start throwing fireballs once mario reaches the boss part of the stage
  if (Mario.x >= 4000)
  {
   for (int i = 0; i < reznorfireballvector.size(); ++i)
   {
    //move and animate sprite

   //has animation delay reached threshold?
   if (++reznorfireballvector[i].animcount > reznorfireballvector[i].animdelay)
   {
    //reset counter
    reznorfireballvector[i].animcount = 0;
    //animate the sprite
    if (++reznorfireballvector[i].curframe > 1)
     reznorfireballvector[i].curframe = 0;
   }

    reznorfireballvector[i].x -= 0.4f;

    //if collision between mario and fireball, remove health
    if (CollisionD(Mario, reznorfireballvector[i]))
    {
     Mario.health -= reznorfireballvector[i].damage;
    }

    //if fireball goes offscreen, remove from vector
    if (reznorfireballvector[i].x < 3000)
    {
     reznorfireballvector.erase(reznorfireballvector.begin() + i);
    }

   }
  }
}