Tuesday, July 23, 2013

Int to Bin v0.4

/*Here's my first go at creating a int-to-binary convert using templates for an array class.  My goal is to create a display to show how bitwise operations affect binary numbers.

I solved it, but I harvested (read found/stole) the bitwise code, and I'm not exactly sure how.why it works, though it is very intelligent code in my opinion.  I will mark the stolen code and the source below;
(0.3 has a few corrections to put the binary print out in the right order) */

/* I have updated the code with an explanation as to how the bitwise evaluation works, now that I understand it myself.  I also tightened up the code in the actual assignment, removing the if statement and replacing it with a direction evalution (x&1)/assignment.*/

#include <iostream>
#include <cstdlib>
using namespace std;
template <typename T>
class array{
      T* val;
      int _leng;
      public:
             array(int l):_leng(l){
                 val=new T[_leng];
             };
             ~array(){
                 delete[] val;
             };
             T& operator[](int index){
                 return val[index];
             };
             int leng(){return _leng;}
             void disp(){
                 for(int i=_leng;i>=0;i--){
                     cout<<(*this)[i];      
                 }
             };
      };

// toBits operates as thus: k is the value of val right-shifted by c.  With fir this c begins as 8
// and val is 15(or 1111bin).  Since a right shift of 8 places pushes the values clear, k==0.  When
// k is compared to bin value of one(1bin), this results in a false, so 0 is assigned to fir[8].
// Next c==7, bit shifting right 7 places.  This is still too far, so the same assignment happens.
// So it goes until c==3.  Once we shift the value only 3 places, the comparison (& operator) evals
// to true, so fir[3] is assigned 1.  This repeats until c==0, when k==true and the loop is complete.
// Thus, the fir.disp() feedback 00001111.
// Now lets look at sec: 16(or 10011bin) runs to c==4.  Here, when the number is shifted
// k==1, and is assigned to fir.  When it is shifted by 3 places, we can see (if we pick the number
// in binary expression) the value is 0, and assigned as such.

void toBits(array<bool>fir,int val){
    for (int c = fir.leng(); c >= 0; c--){
// Everything from here to...
        int k,n;
        k = val >> c;
        fir[c]=k&1;//except this
// ...here all comes from this source: http://www.programmingsimplified.com/c/source-code/c-program-convert-decimal-to-binary, save for some minor modifications to fit the code.
        }
    fir.disp();
}
int main(){
    array<bool>fir(8);
    toBits(fir,4);
    int en=0;
    cin>>en;
    return 0;  
}

Programming - From PET BASIC to PHP

When I was a kid I used to own a Commodore 64, an old 8bit home computer, among the first truly successful home computers.  It came with a built in BASIC language called PET BASIC, a line-numbered procedural language that had much more potential than I ever got out of it.  Despite this lack of talent, I still managed to write a few little text-based adventure games, nothing with a parser or anything, just basic "Press A to go deeper in the cave, press B to talk to the wizard" sorts of things that provided me with a sense of accomplishment, but were terrible.  Since then, however, I've been obsessed with creating games. 
That wonderful old computer also exposed me to the concept of modems and telecommunications through a home computer, and I gained a new obsession; BBSes.  If you're too young to remember the flash-revolution that was the BBS era, it was basically the precursor to public internet use; they where computers set up on land-lines to receive phone calls from other computers to allow you access to BBS software there loaded, which typically included a few interesting "Door games", a few message boards, and maybe a poll or two.  While this sounds impossibly quaint compared to todays internet, remember that this was literally the first time a regular person (meaning someone not involved with the military or a university CS department) could use their computer and leave their home through it.  Thousands upon thousands of these existed across the globe, with North America being a highly concentrated area.  Near where I lived there where no fewer than 40 local "Boards" I could call and spend an hour talking with the various communities there on, playing the weird, ASCII/ANSI based games, and just killing time.  At one point I even ran one with my friend, which we dubbed "The Mother Board", a terrible, terrible pun that we just thought was hilarious.  These sprang up in earnest around 1985 or so and lasted until about 1995, at which point the internet was suddenly unleashed on an unsuspecting public.
Of course, the internet had existed the whole time, it was just a very specialized thing; people in the know could find places to access, but the public was typically paying extortion-level prices to access it for even an hour, and that access was typically hovering around 14.4K BAUD, which, if you had to deal with today you'd probably go insane.  And it was very UNIX centric, with some aiming more towards Dos/Windows users.  The C64 was definitely never designed to access the net, but (as was typical of the C64 community at the time) there were people who designed ways to allow you to do this.  Using a terminal program, you could now leave the confines of your local city and move right out to the whole wide world, talking in USENET groups with people from one end of the world to the other.  And that's when I gained my obsession with the internet.
As time went on the net became more and more normalized; it changed from being wild country to being a tamed village, then a city, country, to the point that it is today; a digital outline of the globe.  At the same time, gaming was taking leaps and bounds; Wolfenstein was released as shareware by ID and completely broke everyone's mind, then they released Doom, and the world never looked back.  3D environments where now a reality rather than a dream so devoutly to be wished.  The PC suddenly looked more attractive than home console systems; the NES and SMS suddenly looked ridiculous in comparision, and the SNES, TGX16, and Genisis could barely keep up. I became obsessed with learning how to write these programs, how to make these worlds that I spent so much time in.
Then everything changed.
Somehow, sometime, everything in the game industry turned into Hollywood.  No longer where PC games designed by teams of four, over the course of a year from their homes, making a solid living on shareware distributions; now there where design houses that where centered in "silicon valley" run by CEOs and boards of directors.  As a reaction to that indie scenes popped up, complete with the personality cults that things like that typically generate.  The fun in games seemed to be drained out; on the one hand you had clones of clones of clones getting regurgitated out over and over, banking on safe-bet titles and mechanics, on the other you had games "as art", with such ridiculously symbolic qualities involved, such deep personal meaning to the designers that they've lost all appeal.  Neither seems satisfactory to me.
I still like designing and writing games, but I have no real expectation that I'll be able to support myself doing it without choosing one of the two teams.  So now I'm thinking of switching to web design, bringing up my JQuery, JS, PHP, HTML, CSS and whatever other talents I can bring to bare up; it seems to still have a place for people who just love the work to make money.  
As a side note, here's a installer for a game I did for a local "game jam" called TOJam.  Obviously, I'm no artist, but it's a fairly (in my opinion) interesting take on the classic screen-wrapping side-scroller, in the sprite of defender:
http://cardiacgamestudio.ca/syreal2.1/syreal2_1.zip
The HTML5 version

Sunday, July 7, 2013

DLList with UI

//dataCell.h
  class Data{
    int data;
    public:
        Data(int d=0):data(d){}
        int out()const{return data;}
};

//dllist.h
#include"node.h"
#include<iostream>
class DLList{
    Node* front;
    Node* back;
    Node* current;
    public:
        DLList():front(NULL),back(NULL),current(NULL){}
        virtual ~DLList(){
            while(current=front){
                front=front->next;
                delete current;
            }
        }
        void goBack(){current=back;}
        void goFront(){current=front;}
        void goNext(){
            if(current)current=current->next;
        }
        void goPrev(){
            if(current&&current!=front)current=current->prev;
        }
        void remove(){
            if(current){
                Node* temp=current;
                if(current==front)front=front->next;
                else {
                    current->next->prev=current->prev;
                    current->prev->next=current->next;
                    current=current->next;
                }
                delete temp;
            }
        }
        bool end(){
            return !current;
        }
        Data get()const{
            if(current){
                //current->sayPos();
                return current->data;
            }
            else return Data();
        }
        void insertBefore(const Data& a){
            if(front){
            if(current){
                Node* p=new Node(a, current->next,current->prev);
                if(p){
                    if(current->prev)current->prev->next=p;
                    else front=p;
                    current->prev=p;
                }
            }
            else{
                Node* p=new Node(a,current->next,current);
                if(p)front=back=current=p;
            }
        }
        }
        void insertAfter(const Data& a){
            if(current){
                Node* p=new Node(a, current->next,current);
                if(p){
                    if(current->next)current->next->prev=p;
                    else back=p;
                    current->next=p;
                }
            }
            else{
                Node* p=new Node(a,NULL,NULL);
                if(p)front=back=current=p;
            }
        }
};

// node.h
 #include"dataCell.h"
struct Node{
    Data data;
    Node* next;
    Node* prev;
    Node(const Data& d,Node* n,Node* p):data(d),next(n),prev(p){}
};

// doublelinks.cpp
#include"dllist.h"
using namespace std;
int menu(){
    int x;
    cout<<"Please make a selection"<<endl;
    cout<<"1) Enter data before this position"<<endl<<"2) Enter data after this position"<<endl;
    cout<<"3) Move ahead on list"<<endl<<"4) Move back on list"<<endl;
    cout<<"5) Move to front of list"<<endl<<"6) Move to back of list"<<endl;
    cout<<"7) Remove data at this position"<<endl<<"8) Print all data"<<endl;
    cin >> x;
    return x;
}
int main(){
    //choice(DLList* r){
    DLList r;
    int x=0;
    bool flip=false;
    while(!flip){
    switch(menu()){
        case 1:
            cout<<"Please input integer: ";
            cin >> x;
            r.insertBefore(x);
            break;
        case 2:
            cout<<"Please input integer: ";
            cin >> x;
            r.insertAfter(x);
            break;
        case 3:
            r.goNext();
            cout<<"The data here is: "<<r.get().out();
            break;
        case 4:
            r.goPrev();
            cout<<"The data here is: "<<r.get().out();
            break;
        case 5:
            r.goFront();
            cout<<"The data here is: "<<r.get().out();
            break;
        case 6:
            r.goBack();
            cout<<"The data here is: "<<r.get().out();
            break;
        case 7:
            r.remove();
            cout<<"Data deleted";
            break;
        case 8:
            while(!r.end()){
                cout<<r.get().out()<<endl;
                r.goNext();
            }
            r.goFront();
            break;
        default:
            flip=true;
            break;
    };
    cout<<endl;
    }
    return 0;
}

Saturday, June 1, 2013

Fun with cui

/*  Here's a really, and I mean REALLY basic version of a dodging game that I did up just as an exercise.  It has an odd collision detection going on, and it's not really much of a game, but it does show how objects can interact with the cui.  If you decide you're going to make a little game with the same namespace and the bconsole/console files let me know, cause I'd love to see what people come up with.
The idea is: Every time a 'T' falls on you you loose a point, everytime a @ falls on you you gain one.  You are the '*' and you control, one step at a time, with the arrow keys.
 */
#include "console.h"
#include <cstdlib>
#include <time.h>
#include <stdio.h>
//#include <Windows.h> -- This is an early attempt at coloring the chars
using namespace cui;

class DropObj{
    char sym;
    int row,col;
    public:
        DropObj();
        DropObj(char);
        ~DropObj();
        void newLoc();
        void move();
        char disp();
        void place();
        int outside();
        int colcall();
        void set(char);
};
void DropObj::newLoc(){
    row=0;
    col=rand()%console.getCols();
}
int DropObj::colcall(){
    return col;
}
void DropObj::set(char t){
//    system("color 01");
    sym=t;
}
DropObj::DropObj(){
    sym='@';
    row=0;
    col=rand()%console.getCols();
}
DropObj::DropObj(char ty){
    sym=ty;
    row=0;
    col=rand()%console.getCols();
}
DropObj::~DropObj(){}
void DropObj::move(){
    row++;
    if(row>console.getRows()-1)row=0;
}
char DropObj::disp(){
    return sym;
}
void DropObj::place(){
    console.setPos(row,col);
    printf("%c",disp());
}
int DropObj::outside(){
    return row;
}

class BadGuy:public DropObj{
public:
    BadGuy();
    BadGuy(char);
};
BadGuy::BadGuy(){
    DropObj();
}
BadGuy::BadGuy(char n):DropObj(n){}

/*void hitCheck(DropObj star,BadGuy bads[],int i,int r,int c){
    for(int j=0;j<i;j++){
        if(bads[j].outside()==r+1&&bads[j].colcall()==c)printf("YOU'RE HIT!");
    }
}*/
int main(){
  srand(time(NULL));
  DropObj dropPoint;
  BadGuy Go[99];
  for(int j=0;j<99;j++)Go[j].set('T');
  bool done = false;
  int row = console.getRows()-1;
  int col = 0;
  int launch=0;
  int ii=0;
  int score=0;
  bool dead=false;
  int key;
  while(!done){
    launch=rand()%20;
    if(launch<5&&ii<99){
        Go[ii].place();
        ii++;
      }
    dropPoint.place();
    dropPoint.move();
    if(dropPoint.outside()==row+1&&dropPoint.colcall()==col){
      score++;
      dropPoint.newLoc();
    }
    for(int i=0;i<ii;i++){
      Go[i].place();
      Go[i].move();
      if(Go[i].outside()==row+1&&Go[i].colcall()==col){
        score--;
        Go[i].newLoc();
      }
    }
    if(row+1==console.getRows()&&col+2==console.getCols()||row+2==console.getRows()&&col+1==console.getCols())dead=true;
    else dead=false;
    console.setPos(row-1,40);
    printf("Score=%d",score);
    console.dspstr("*",row,col);
    key = console.getKey();
    switch(key){
    case DOWN:
      if(row+1<console.getRows()&&!dead){
        row++;
      }
      console.clear();
      break;
    case UP:
      if(row>0){
        row--;
      }
      console.clear();
      break;
    case RIGHT:
      if(col+1<console.getCols()&&!dead){
        col++;
      }
      console.clear();
      break;
    case LEFT:
      if(col>0){
        col--;
      }
      console.clear();
      break;
    case ESCAPE:
      done = true;
      break;
    default:
        console.clear();
        break;
    }
  }
  return 0;

}

movebox.cpp

/*   To stop the box from moving into the corner where it causes the weird scroll, I used a bool and flipped it on and off as appropriate.  Otherwise I simply checked for the borders on a 25x80 console window and prevented the rows/cols from advancing if the box was at the consoles edge.  I also included <stdio.h> for debugging purposes with printf, and would have removed all references to it, but I left it in as a reminder to myself. 
 */
#include "console.h"
#include <stdio.h>
using namespace cui;

void prnbox(int row, int col){
  console.dspstr("*****************", row ,  col);
  console.dspstr("*****************", row + 1, col);
  console.dspstr("*****************", row + 2, col);
}

int main(){
  bool done = false;
  int row = 0;
  int col = 0;
  bool dead=false;
  int key;
  while(!done){
    if(row+3==console.getRows()&&col+18==console.getCols()||row+4==console.getRows()&&col+17==console.getCols())dead=true;
    else dead=false;
    //console.setPos(row,40);
    //printf("Row: %d Col: %d Dead=%d",row,col,dead);  DEBUG LINE
    //console.setPos(10,55);
    //printf("TotRow: %d TotCol: %d",console.getRows(),console.getCols()); BASED ON 25x80 console
    prnbox(row, col);
    key = console.getKey();
    switch(key){
    case DOWN:
      if(row+3<console.getRows()&&!dead){
        row++;
      }
      console.clear();
      break;
    case UP:
      if(row>0){
        row--;
      }
      console.clear();
      break;
    case RIGHT:
      if(col+17<console.getCols()&&!dead){
        col++;
      }
      console.clear();
      break;
    case LEFT:
      if(col>0){
        col--;
      }
      console.clear();
      break;
    case ESCAPE:
      done = true;
      break;
    }
  }
  return 0;

}

Friday, May 24, 2013

Rewinding Variadic Lists

/* Written as a personal challenge; it is possible to rewind a Variadic list; in fact it's extremely easy, as it is based on the use of pointers, which have a definitive size in memory, so you can move up and down the list simply by adjust the pointer of the list.  In this example this was accomplished using the sizeof function and adjust the list pointer by iterations of this (I believe it's 4 bytes, but I might be wrong about that).  I haven't tested this with any other type in the list (chars*, doubles, etc) but it seems like it aught to work.
 */
#include <iostream>
#include <stdarg.h>
using namespace std;
void out(int sou,...);
int main(){
    int i=0;
    out(i,3,4,5,6,0);
    cin >> i;
    return 0;
}
void out(int sou,...){
    int r=0,i=1;
    va_list test;
    int start=sizeof(test);/*this grabs the size of the pointer*/
    va_start(test,sou);
    while(r=va_arg(test,int)){
        cout << "int = " << r << ":"<<(int)test << endl;
        i++;/*this counts the number of parameters passed to the function*/
        }
    test-=start*i;//this rewinds the pointer to the start of the list
    while(r=va_arg(test,int)){
        cout<<r<<endl;
        }
    va_end(test);
    va_list test2;
    va_start(test2,sou);/*this is just provided as a second method of "rewinding the list" though is less efficient*/
    while(r=va_arg(test2,int))cout << "int = " << r << ":"<<(int)test << endl;
    va_end(test2);
}

Thursday, May 23, 2013

Variadic Example #3

/*  Here's one more example on using variadic functions that I was playing with.  This on scans an entered string and looks for '!', reporting if it's found with "DETECTED", then applies a few different treatments to the string depending on what int parameters are sent down.  Mostly I did this to see if I could, with the idea being: could it be possible to pseudo-replicate what happens with a "printf" function?
 */
#include <iostream>
#include <stdarg.h>
using namespace std;

void newp(char* dat,...);

int main(){
    char rr[99];
    int ii=999;
    cout<<"Enter a string:";
    cin >> rr;
    newp(rr,1,2,1,3,1);
    cin >> ii;
   
}
void newp(char* dat,...){
     char gist;
     va_list o;
     int i=0,j=strlen(dat),k=0;
     for(k;k<j;k++){
         if(dat[k]=='!')cout<<"DETECTED!"<<endl;
     }
     va_start(o,dat);
     while(gist=va_arg(o,int)){
         switch(gist){
             case 1:
                 cout << dat << dat <<endl;
                 break;
             case 2:
                 cout << endl << "WORD!" << endl;
                 break;
             case 3:
                 cout.setf(ios::right);
                 for(i=61;i<85;i++){
                     cout.width(i);
                     cout<<i<<")"<<dat;
                 }
                 cout<<endl;
                 break;
             default:
                 cout<<"Undefined parameter"<<endl;
                 break;
         }
     }
}