Friday, September 28, 2012

More Game Maker and GML

Learning a new programming language at this point in my academic career is not that hard. If the language has great documentation (I'll usually just settle for documentation), and a forum  of developer for that language that discuss the language and syntax I can get the language down and making programs beyond that of a Hello World or Linked List within a week. If that language is a scripting language, even faster.

I have however came across some languages that have poor documentation, and the forum that discusses them is lucky to get any traffic. This is usually rare since the languages worth programming in have great support and a great community that helps those in need. Game Maker has neither.

For those of you who don't know, Game Maker is a drag and drop (with a "scripting language" attached to it). It greatly speeds up development since you can get a prototype of a typical flash game that you can find on Kongregate in just a week. This is if you use the drag and drop. Game Maker does have its own language called GML. If I were to compare it to another scripting language, its syntax is similar to Javascript. I decided to play around with GML and get the basics so that I can get into development without too many bumps as possible.

When writing code for GML. you just write a snippet of code (a script) and attach it an object to perform that script. Unity has a very similar design to this (that's where the similarities end) where their scripting language you can choose between C# or Javascript. This is a bit strange to get a grasp of since I'm more use to programming using objects like in C# or C++. Thinking about it, it is very similar to that type of programming. You can make an object (foo.cpp) where you can attach events to that object, i.e. the create event (the constructor) and a destroy event (the destructor), where they will initiate the script that you've written. That's not bad, in fact I could actually learn to use it. It's what happens in the script where the problems lie.

My biggest problem lies with collision detection and general physics. The way to detect a collision detection is place_free(x,y). It will tell if the object collides with another object. It is however really buggy. Half the time, my object goes through half another object (mostly the floor), where the character can move around and still jump. I've checked the hit rectangles and they seem to be fine. I've tried looking online, but an unhelpful community and poor documentation doesn't reveal anything. When my character jumps and goes into a wall, he sticks to the wall and will release if you move away from the wall. This has cost me more unnecessary time on debugging and figuring out what GML is actually saying.

The thing is I've done all of those things successfully without too much error in openGL c++ and actionscript 3.0. With a little math and some built in functions, it is all possible without too much headaches, it just takes a little more time. I've tried doing what I would normally do in actionscript or c++, but GML complains even more when you do what it doesn't want you to do. When I want the character to move horizontally I have to specify hspeed and not x += velocity. When I do use x += velocity, it creates a jigging effect where the character moves forward by 5, stops for a moment then moves forward by 5 again.

One of my teammates, who practiced with Game Maker using the drag and drop commands replacing the script found it easier and did more in the same amount of time. I would use do that except for that of my pride, and there are some things you have to do using GML to make the best game (comparatively) that you can using such a primitive tool from hell that rivals that of Fortran.

I'll get it eventually, fighting a language is like fighting any other language; just give it enough time and the battle with always be won. Then the cycle repeats itself when I have to find a better physics engine for Game Maker. I am looking  at two right now (GMPhysics and Extreme Physics). Both of which require use of GML.

Friday, September 21, 2012

Game Dev 1: Pitch, Fallen, and Game Maker

This post will be catch up to what I am doing in the development process in Game Dev 1... The class Game Dev 1 (Film 3710) is basically making a game in a semester using a pre-existing engine (Unity, Unreal, Game Maker, Game Salad, etc). The game will usually be in the fashion of a flash game-esque and won't be as expansive as I would like. Though a semester to make a game is better than 2 - 4 weeks. This development process will be from pitch, to game design document, to development, to testing, to release. My team is already doing level design and working out game flow and the mechanics of the game, so I will go through of my initial pitch.

Pitch:

About 2 weeks ago from this posting, I gave my pitch for a game I made up on the spot (I was just happy to do someone else's game). The reason for this is because, I do have some great ideas for games that I will present for my capstone project and maybe a person project (If I can become good friends with an artist).

My game idea came for the idea of a Halloween costume. I love steampunk, and I too love Victorian attire (especially an aristocrat with the top hat, cane, and monocle). So I decided to go as Death if he were an English gentleman. This costume is just the Aristocrat attire with a skull face mask and a skull cane. The main character in my game would be death in his attire. A soul was able to escape from the Underworld and escape to the world above and posses many humans. Death must go above and reclaim that which he lost while trying to either kill or save those who are possessed. This game is a 2D side scroller and relies heavily on visual gags. This was a game I would not make (I probably would save the character of Death for a different game), but need to give a pitch for a grade.

For the actual pitch, since I didn't care for my idea I decided to rely on showmanship and dressed up as my Halloween costume. I was the only one to show up and I did receive some positive feedback about the game. Not surprisingly, I didn't go ahead with the idea. When teams of 3 were formed, we decided to make a different game (one for the better).

Fallen:

We formed into teams of three (1 programmer, 1 artist, and 1 producer). This setup does worry me a bit since I am the only programmer and will have to do all that responsibility for the entire game. I was initially thinking that when we got into the teams of 3, we would improve the game idea and present that to the class, and the professor would merge some teams together to have a bigger development team, but as time goes on I doubt it more and more.

When my team met, we decided not to do any of our ideas and form an idea from a genre that we all love (RPG). We decided to center our game around a fallen angel who has fallen to depths of hell and must escape.

Elevator Pitch:
Thrown out of heaven for somewhat trivial reasons, an Angel finds himself at the bottom of the 10 realms of the underworld. Fighting his way back to the surface the angel must choose to seek vengeance or offer mercy to those he believes has wronged/betrayed him. Fallen is a Action RPG 2D Platformer with puzzles to solve, demons to fight, bosses to suppress and a choice between good and evil to make.
I really like this idea, since it allows us to really get into the visuals and atmosphere. It will also allow me to practice my coding experience on platformers. I believe that if this is done correctly, then it will be an awesome game.


The game is an RPG because the player can choose between three trees (Vengeance, Justice, and Mercy) which represent warrior (melee), ranger (ranged), and mage (magic) respectively. The player can level up each tree and will have a certain weapon that goes with each one (sword with Vengeance, bow with Justice, and staff with Mercy). We are still deciding how a player can switch between the trees or if they can select just one tree at the beginning and they are either Vengeance, Justice, or Mercy.

At the start of the game, the player starts in the bottom of Hell where he must climb out. He faces tougher and tougher demons as he levels up. When he escapes the pit, he has a choice if he will join the demons and invade Heaven and exact revenge on the angel who cast him out. Or rejoin the angels after a brief confrontation and go back to the pit and destroy hell. This will most likely leave a cliffhanger for a sequel that will most never happen.

There are some pitfalls that I do forsee and have currently seen my teammates and myself make. That is we make this game too big. The scope of this game is an epic adventure like most other RPG's. If we had the time and resources this game could have been a AAA game that was fully 3D open world RPG (much like Dragon Age). The choices can be more integrated to show a transform into either a fallen (dark) angel or an archangel (good) both equally as powerful. Like with everything, we won't be able to put everything we want in, but with only a semester for a development time that will be even more so.

Game Maker:

Because we have only a Semester to this game I cannot make this game as I have made it in the past using an IDE and a language (C# using XNA or C++ using QT). I am forced to use a pre-existing engine such as Unity, Unreal SDK, Game Maker, or Game Salad.

I really want to use either Unity or Unreal SDK because their tools are just simply awesome and the scripts they use are actually languages (for example javascript and C# are used for Unity). Game maker uses a bastardized language called GML and Game Maker doesn't even have a scripting language you can use. In fact, one person even went as far as saying "Meet the startup that is going to make programming a thing of the past." The Article. The reason I can't use Unity or Unreal is because they are 3D engines and don't do 2D. You can technically do 2D since its just 3D, but the loss of a dimension but it won't have that flash feel to it and would be awkward to program. I tried Game Maker and even though its alright, I really would rather not use it. If I could, I would like to use Flashbuilder to make this game, but I would need another programmer or more time to do that. Therefore, I have to use Game Maker for this semester.

Game Maker is you drag and drop program for those who don't have any programming experience. While it does have a scripting language (GML) which is similar to javascript, its rather clunky and finding documentation for it was the biggest pain in the ass. There are ways to make this game without writing a single line of code, but it would be similar to how Scratch writes code and that you drag a block of code into a window that does a certain command, a conditional, or a loop. It takes all the joy out of programming and the feel of accomplishment when your eternal fight against the OS and compiler has a temporary victory when a block of code starts to work.

That is all for now. I'll write again in the next development phase, when my team has planned out the flow of the game and the layout of each level.

Summer Project: CSV Parser

Welcome to the third and final installation of the Summer Project series. This project, although isn't having me fix bugs 3 months after release, was the biggest project and did require the most knowledge of certain servers (Mostly LDAP and Active Directory LDAP). This application takes in several .csv files (a file that has a list of students and certain attributes) and creates an Engineering account for them. This application has many parts to it that made it possible:

  • CSV Parser
  • Create Account
  • Create Cards and allow to download
  • Setting up the csv files from the user
These were originally a series of perl files that a person would have to do manually in a linux terminal. My task was to take these perl files and port them into php and have the user (my boss) just select which csv files he wants to add and the code does all the rest. Note: porting perl to php can be an excruciating task (especially when translating regular expressions).

Setting up the .csv file:

In order to parse and process the csv files, the user will have needed to provide some. The first thing that needed to be done was to allow the user to open up a file explorer and select the csv file. This can be done using this html tag

<form action="formatfile.php" method="POST" enctype="multipart/form-data">

     <input type="hidden" name="MAX_FILE_SIZE" value="1000000" />

     <input type="file" name="inputFile" />

     <input type="submit" value="Add File" />
</form>

It has to be in the from because when the user does select "Add File", then it will upload that file to the server into a tmp folder. Adding a file to the tmp folder proved to be difficult because all folder have a default mod of 755 with the user as root and the group as apache. Some people online suggested to chmod it to 777 to allow apache to add. This would be disastrous and I was surprised that they would suggest it. With a security setting of 777, anyone can write anything in the tmp folder whether it be javascript files or other scripts. I needed to find a way for apache to write to the folder without anyone else. Since apache belongs to the group apache, a security setting of 775 would allow apache to write to the folder and no one else. 

When the file is uploaded, it is stored in a temporary location in $_FILES, that if left will be deleted. Therefore, I had to create a helper script to move the file from the tmp location to my more permanent tmp folder on the server. The script would also check to see if the file was really a valid csv file before adding it to the folder. 

After the file had been uploaded, the index page then moves on to show all the files that are uploaded where the user can add more files, remove some files, or parse the files which leads me to:

CSV Parser:

The CSV Parser goes through each line of the .csv file and extracts the relevent student information (name, uid, major, class). From there it puts it in the Create Student script (to be covered below). From there it will print the student information out and how much it completed (in percent). When testing, this process can take about 2 - 3 hours just to parse and add some 2000 students. I have no idea why it takes so long (though I do expect it has to do with adding to AD LDAP (connecting to Windows). After it does this for each .csv file, it will then create cards for each class they are in (i.e. CS1410-001) so that the teacher can hand out their account information at the first or second day of class (for those who request it). Part of the information that is pulled out is what engineering class they are taking. This is able to work too since each .csv file is just a department (i.e. MSE, BIOEN, CH EN, CS, ECE, ME EN). (The card generating algorithm will be covered below). 

This was the first script that I made that I had to port from perl. The way the perl script extracted the information from the line was that each information was at a certain point (uid took up the first eight, name had the next 50, etc). The perl script was able to use regular expressions to get it. 


($uuid,                 # (8)

   $fullname,             # (50) LAST, FIRST MIDDLE|M.I.

   $adm_stat,             # (4)  admission stat   (??)

   $major,                # (4)
   $degree,               # (5)  degree
   $enroll,               # (2)  enrollment class (??)
   $flag,                 # (2)  ???
   $colldes,              # (2)  college descriptor
   $coursedept,           # (5)  course department
   $coursenum,            # (4)  course number
   $coursesect,           # (3)  course section
#  $credithrs,            # (3)  credit hours
#  $grade,                # (2)
#  $crnocrf,              # (1)  credit no/credif flag
#  $courseti,             # (8)  course title INDEX (numeric)
#  $coursetitle,          # (30) course title       (descriptive name)
#  $addline1,             # (35) address line 1
#  $addline2,             # (35) address line 2 (seems to be empty)
#  $city,                 # (14) 
#  $state,                # (2)
#  $zip,                  # (5) ) = /^(\d{8})(.{50})(.{4})(.{4})(.{5})(.{2})(.{2})(.{2})  (.{5})  (.{4})(.{3})/;

Since in php, regular expression are a pain to do, I decided to use a substring(currentLine, index of first char, length of string). This took some fine tuning since my reading of regular expressions isn't the best. From the information extracted, the script would then translate some of it into what the Create Student needed. $degree would be used to determine class (bs, bhs => ugrad AND phd, ms, men => grad AND all else => class). All trailing and leading whitespace would be removed. Then their major would be translated into the department they belonged to (CS => cs, ME EN => me, etc). From there, all the information would be put into an array to be processed by the Create Student algorithm. 


        $MAJOR = array(

            'BIOE' => 'be',

            'CECS' => 'ce',

            'CFEN' => 'ch',

            'CHEN' => 'ch',
            'CPSC' => 'cs',
            'CVEN' => 'cv',
            'MEEN' => 'me',
            'ECE' => 'ee',
            'MSE' => 'ma'
        );

        $COE = array(
            'CS   ' => 'cs',
            'ME EN' => 'me',
            'ECE  ' => 'ee',
            'CHFEN' => 'ch',
            'BIOEN' => 'be',
            'CVEEN' => 'cv',
            'MSE  ' => 'ma',
            'CH EN' => 'ch'
        );

        $uid = trim(substr($line, 0, 8));
        $fullname = trim(substr($line, 8, 50));
        $major = trim(substr($line, 63, 4));
        $degree = trim(substr($line, 67, 5));
        $coursedept = substr($line, 79, 5);
        $coursenum = trim(substr($line, 87, 4));
        $coursesect = trim(substr($line, 91, 3));

        $name = explode(',', $fullname);
        $name1 = explode(' ', $name[1]);

        $last = $name[0];
        $first = $name1[0];
        $middle = count($name1) == 2 ? $name1[1] : '';

        $first = ucfirst($first);
        $middle = ucfirst($middle);
        $last = ucfirst($last);

        if(array_key_exists($major, $MAJOR))
        {
            if($degree === "BS" || $degree === "BHS" || $degree === "MIN")
            {
                $rank = 'ugrad';
            }
            else if($degree === "MEN" || $degree === "MS" || $degree === "PHD")
            {
                $rank = 'grad';
            }
            else
            {
                $rank = 'class';
            }
            $dept = $MAJOR[$major];
        }
        else
        {
            $dept = $COE[$coursedept];
            $rank = 'class';
        }
        
        $student = array(
            'First' => $first,
            'Middle' => $middle,
            'Last' => $last,
            'Uid' => $uid,
            'Dept' => $dept,
            'Rank' => $rank,
            'CourseNumber' => $coursenum,
            'CourseSect' => $coursesect,
            'CourseDept' => $coursedept
        );
        
        return $student;

Create Student:

This algorithm was originally created by a coworker who created this so that an oper can create an account for a student who did not get one in this process. While his algorithm was good, I had to do a lot of work to make it work for my code. For instance, he used a framework made by code igniter. I tried to get it to work at first, but there were a lot of errors. I gave up and made the code from scratch. This was a long process, but I was able to get it to work at the end. 

The first thing the code does is to create the attributes for the user to insert on LDAP (Linux side). The attribute is using the information extracted from the CSV Parser and some new information using it such as UID (user id for chmod), GID (group id for chgrp), a username, location of their home directory, and a random password that is encrypted. 

The username is generated by using a combination of the users full name (usually the first name with last initial, or first initial with last name). It will test each try and go on to the next if the suggested username is already taken. It will then see if the user already exists. If the user already exists, then the code will terminate, tell the user, and go on to the next student. 

If the student is valid, then it will connect to ldap and add the student using ldap_add. If at any point, ldap connection or ldap_add should fail, it will tell the user and go on to the next student. 

When the student has been added to LDAP, it will then create the student on Active Directory LDAP on the windows side. This required a third party library (ADLDAP).

AD LDAP:
Author Scott Barnett, Richard Hyland
Copyright (c) 2006-2010 Scott Barnett, Richard Hyland
License http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html LGPLv2.1
Revision $Revision: 91 $
Version 3.3.2
Link http://adldap.sourceforge.net/

In order to create an account on the windows side, this required me to redo the attributes and add a few categories. These changes were to revamp where the home directory was located on the windows server, add a description (their uid), create .win_profile path, and tell which OU the student belonged to. 

After that, AD LDAP was able to add the student to the server and add them to the ENG Student group. Of course if any of that failed, then the code will tell the user and go on to the next student.

After creating the account on both the windows and linux side of LDAP, the script will then create the students home directory where they will have access to all their work. This is a very simple script that calls another unix script that does all the dirty work. 

      if(preg_match('/[^a-z]/', $user))
            {
                throw new Exception("Illegal Username: " . $user);
            }
            $cmd = "$sudo $homedir " . "$user $uid $gid" . ' 2>&1';
            exec($cmd, $output, $returncode);
            //var_dump($output);
            //var_dump($returncode);
            if($returncode != 0)
            {
                throw new Exception("Could nt create homedir: " . implode("\n", $output));
            }
            return true;

That is all the Create Student account needs to do, the student is ready to use his/her account. The scrip then returns the users password and username for the Card Generation algorithm.

Card Generator:

After the student has been created, then the array that was returned by the Create Student algorithm is added to the $student array that was generated by the CSV Parser. The student is added to a 2D array where the row are Class numbers and the column is the Student's uid where the $student array is stored at that location.

$course = $student['CourseNumber'] . "." . $student['CourseSect'];
     
        if(!array_key_exists($course, $courses))
        {
            $courses[$course] = array();
            $courses[$course][$student['Uid']] = $student;
        }
        else
        {
            $courses[$course][$student['Uid']] = $student;
        }

When the parser is finished with each .csv file. The 2D array is then parsed over in a double array where each class and the students in each class is added to a txt file with the class name one it. That file is then temporarily stored in the cards folder in the server.


foreach($courses as $course)
        {
            $tmp = array_values($course);
            $title = $tmp[0]['CourseDept'];
            $courseNum = $tmp[0]['CourseNumber'] . "." . $tmp[0]['CourseSect'];
         
            $ourFileName = "cards/accounts." . $title . "." . $courseNum . ".txt";
            $file = fopen($ourFileName, 'w')
                    or die("Can't open file " . $ourFileName);
         
            foreach($course as $student)
            {
                $fullname = $student['Last'] . ", " . $student['First'] . " " . $student['Middle'];
                $lineBreak = '-----------------------------';
             
                fwrite($file, $lineBreak . "\n" );
                fwrite($file, $fullname . "   CADE Lab Login: ". $student['Username'] . "   Password: " . $student['Password'] . "\n");
                fwrite($file, "\n");
                fwrite($file, $student['Uid'] . "          To change your lab password, type 'passwd' at a UNIX prompt.\n");
                fwrite($file, "                  Use 'remote_passwd' to set your password for remote services,\n");
                fwrite($file, "                  such as POP mail or FTP.\n");
                fwrite($file, $lineBreak . "\n");
                fwrite($file, "\n");
            }
         
            fclose($file);
        }
     
        Zip_And_Download();



function Zip_And_Download()
{
    exec("zip -r cards/cards cards/");     
    echo "<a href='download.php'>Download cards.zip</a><br />";
}


After each file has been made, then the user can download each file in a .zip file; however, if they were to refresh the page or clear it, then the cards folder would be wiped clean and could never be gotten again (excluding .snapshot) because the script won't add the same students twice once they've been created.

Downloading a zip file is a lot simpler than it seems.


    header('Content-Type: application/zip');
    header('Content-Disposition: attachment; filename=cards.zip');
    readfile("/home/kray/public_html/UserCreateTemp/cards/cards.zip");


That is all for the CSV parser. I couldn't post as much of the code as I would have liked to due to security and me liking my job. This concludes the Summer Projects series. I am now in full development in my Game Dev class and I will be focusing on that for this semester.

Monday, September 17, 2012

Summer Project: CoE Network Request

Welcome to part 2 of the Summer Project series. The second project I made was a Network Request form for people to request access of their computer to the College of Engineering. This was the easiest project of the summer. This is quite simple as the there was only two major pages. The form and the database.

The form is a basic form where the user enters in basic information about them (name, email, department, etc), where computer is located at, and basic information about the computer (name, mac address, and port). With this information an email is sent to the opers where one will connect their computer to the Network. Also the mac address is check against the other address on the database to detect a duplicate. If there is a duplicate mac address, then the system asks the user if they still wish to proceed with the conflict. If they do proceed, then the request is sent to the opers and the information is stored in a separate table where the oper can decide if the conflict should override the current entry. If there should be an override, then the current entry will be deleted and replace by the conflict. This is extremely rare because of the uniqueness of mac addresses.

There is a separate page where only authorized people can view all the mac address in the system and potential conflicts in another page. Since a request comes in nearly every day, the number of mac address in the system is numerous. So the page doesn't load every single mac address in a single page, I made it similar to what other large lists do (split it up). Only 10 mac address would show at any one time, with a series of numbers below that the user can use to jump to any set of mac address (<first 1 2 3 ... (n -1) (n) last>).

Also on the page is a search box, where the user can enter in a mac address and when enter is hit, it will pull up the information on the mac address (if it exists). This is the same for the conflicts tables as well.

That is all for this. I know it wasn't too interesting, but the project itself was very small and not like the Reservation system which had an interesting algorithm to show. The final part of the series will be a CSV Parser where it will take in a list of students and create an Engineering account for them. This will be just as interesting as the Reservation system with some good algorithms to show off.

Friday, September 7, 2012

Summer Project: Reservation System

This is the first part of my Summer Project series. My current job is working the help desk at a Linux lab for the College of Engineering at the University of Utah. During the school year, I am expected to help student with problems they incur when using a Linux. During the Summer, I do some actual programming that my boss needs to get done at the time. I know that this isn't games, but it is programming and the experience will help greatly in my endeavors.

Each of these projects that I did were Web Applications written in PHP. I don't like PHP. It is a poorly written language that doesn't know when to die. Half the time is me fighting PHP when it doesn't do what I need it to do and when it doesn't crash when any other language would crash. Its too lenient when the programmer makes a mistake and the array that is an abomination of a hash map. For all the problems I have with PHP, the reason I still choose to program with it instead of JSM or Ruby on Rails is that first, I know PHP; and second, PHP has built in functions to connect to LDAP.

 The first project I did was a Lab Reservation System. The lab I work for (CADE) is one in seven labs, either windows, linux, or mac. Not only are these for students to get work for, but some are teaching labs and used by professors to help teach their engineering class. These labs can also be used for other purposes, such as summer camps or orientation, if they ask permission first. Now enter in the reservation system. When my boss approached me, there was already a reservation system in place. The layout was horrible and the person approving the request would have to enter in the entry into the SQL server by hand. My job was to completely rebuild it.

I started out by turning my computer into a temporary apache server and database for testing purposes. Getting the layout and css was a lot easier than I imagined because the College of Engineering already has a layout ready to use. From there, I set up the index page to list all the reservations that were approved. A page for a forum to submit a request, and a page that only admins could access in order to approve/deny requests.

After all that was set up, I created a separate script that would check to see if the request had any conflicts. If it did, it would let the user know; else, send the request through to be approved. Checking for conflicts proved to be the most nightmarish part of the whole experience and had flaws in it even past release. The last bug report I got about it was three months after the reservation system was released.

The way I did check for conflicts was to start out general and keep shaving off requirements that did conflict until the program was certain that there was a conflict. Here is the overview of it in pseudocode:

$requestorsInfo

foreach(person in the database as $databaseInfo)
{
     //both want same lab
     if($databaseInfo->lab == $requestorInfo->lab)
     {
            //if the range of dates they want for overlaps with the other
            if($databaseInfo->dateRange conflicts with $requestorInfo->dateRange)
            {
                    //Even though the person specifies a range of dates Aug 8, 2012 - Dec 10, 2012
                    //They can only have it on a certain day of the week such as Tuesday, Thursday
                    //Therefore this will check to see if they both want the lab on the same day of the week
                   if($databaseInfo->dayWeek conflicts with $requestorInfo->dayWeek)
                   {
                           //If they both want it at overlapping times, then that seals the deal. There is a conflict
                          if($databaseInfo->timeRange conflicts with $requestorInfo->timeRange)
                          {
                                  return true //there is a conflict
                          }
                   }
            }
     }
}
return false //there isn't a conflict.

Finding a date conflict took a bit of thinking, but after picturing all the different kinds of overlap might look like, I was able to form a boolean expression to determine conflicts in time.

s1: start date for the requester
e1: end date for the requester

s2: start date for database entry
e2: end date for database entry

Conflict 1:
s1                              e1
|--------------------------|
                 |--------------------------|
                s2                                    e2

Conflict 2:
                   s1                          e1
                    |------------------------|
|-------------------------|
s2                                 e2

Conflict 3:
s1                                       e1
|-------------------------------------|
           |--------------------|
          s2                           e2

Conflict 4:
           s1                        e1
            |------------------|
|---------------------------------|
s2                                               e2

Conflict 3 is true if Conflict 1 AND Conflict 2 are true, so we can remove it from the boolean expression since it is enough if Conflict 1 OR Conflict 2 is true.

The boolean expression is:
($s2 <= $e1 && $e1 <= $e2) || ($s2 <= $s1 && $s1 <= $s2) || ($s1 <= $s2 && $e2 <= $e1)

When calculating the date, I make a gaffe early on. The database takes it in the from Month_Day_Year and stores each part in an array. The database also returns it likewise. When the project was "complete" and I was taking it into beta testing, I read about the Date field for SQL and that it could do such comparisons. However, since the project was so complete, I choose to stick with what I had and work out the bugs instead of choosing to rewrite my code and rearrange my database in an attempt to do the least amount of work possible. I still keep it as is after doing more work debugging because it does work and I am really lazy about rewriting code and reworking the database.

Since I choose to stick with what I had, I needed to represent the dates as value in order to compare them. I could have used a lot of conditionals if the months were the same and if the years were the same, but that felt like more work that was needed. I then decided to split the month, day and year. That of course did not work. After some more thought, I decided to represent each date as a unique integer that could be compared a lot easier. By turning the month into how many days until that event (January would be worth 31 and February would be 59 or 60 depending on the year. Then summing each value up (i.e. January 1, 2012 would be 31 + 1 + 2012). This will produce a unique integer that can compare any date of any year.


To check the conflict of the day of the week actually gave me more problems than I had expected and was the last part that was responsible for bugs even three months after release. A conflict happens when there is at least one day of the week that both people want (i.e. a wants Tuesday Thursday and b wants Wednesday Thursday). The day of the week that a person wants is stored in a array of bytes.

$dayWeek = array(
            'Monday' => 0 | 1
            'Tuesday' => 0 | 1
            'Wednesday' => 0 | 1
            'Thursday' => 0 | 1
            'Friday' => 0 | 1
            'Saturday' => 0 | 1
            'Sunday' => 0 | 1
);

1 if they want it, 0 if not.

A conflict should return true if you go through each day of the week for each comparing the two and ANDing them together. If any AND returns true, then there is a conflict. There were two things I tried before I go (I believe) the correct solution.

Try 1:
 return ($requestor->$dayWeek['Monday'] == $database->$dayWeek['Monday']) || ($requestor->$dayWeek['Tuesday'] == $database->$dayWeek['Tuesday']) || ($requestor->$dayWeek['Wednesday'] == $database->$dayWeek['Wednesday']) || ($requestor->$dayWeek['Thursday'] == $database->$dayWeek['Thursday']) || ($requestor->$dayWeek['Friday'] == $database->$dayWeek['Friday']) || ($requestor->$dayWeek['Saturday'] == $database->$dayWeek['Saturday']) || ($requestor->$dayWeek['Sunday'] == $database->$dayWeek['Sunday'])

The reason this didn't work is because I was treating the 1 and 0 as booleans and not integers. False == False is False, but 0 == 0 is true.

Try 2:
return $requestor->$dayWeek === $database->$dayWeek

This would only work if the user and database wanted the same days of the week and were clones of each other. I should have figured this out at first, but I was pretty lazy.

Implementation:

foreach(dayof the week as $i)
{
      if($requestor->dayWeek[$i] == 1 && $requestor->dayWeek[$i] == 1)
             return true;
}
return false;

This was basically the 1st implementation (Try 1) had the compiler treated 1 and 0 as bools and not integers.

The last conflict check was for the time. This works the same way as the Date checker. The only exception is how it compares times. The time that is inputted is in the 12-hour format. The program takes the the time and converts it into the 24-hour format and then converts the hours into minutes and sums the two up. This creates a unique integer that can be compared easily.

That is the algorithm that checks for conflict in a request. I would like to see how a more complicated system would check for it (like hotel reservations). The rest of the code is basically a bunch of calls to the database to either remove entries, add them, or manipulate them to present to the viewer.

That's all for the Reservation System. It was definitely a challenge and really helped my problem solving. Next part int he Summer Project Series will be CoE Network Request which will not be as long as this one.
               

Tuesday, September 4, 2012

Back Again

School has started again and I am ready to get developing again (I did write three web applications over the summer, but that's for a different time). For this spring semester, I mostly have theory classes such as Computer Organizations, Discrete Structures, and Probability and Statistics. So I won't be doing too much programming. I am; however, taking a Game Development course where we make a simple game from pitch to development to release. I am coming up with a pitch right now (my ideas are too big for this class) and will post them when they come up. That's all for now, and I will update you with each detail.