Week #24: Game Programming

  • (2 Pages)
  • +
  • 1
  • 2

25 Replies - 16938 Views - Last Post: 18 August 2010 - 07:24 PM

#1 SixOfEleven  Icon User is offline

  • using Caffeine;
  • member icon

Reputation: 945
  • View blog
  • Posts: 6,342
  • Joined: 18-October 08

Week #24: Game Programming

Post icon  Posted 28 June 2010 - 06:47 AM

GAME PROGRAMMING

CHALLENGE: Try writing a computer game!

A fascinating aspect of programming is game program. Game programming has come a long way from where it began. Games can take many forms. From simple text based games to large 3D worlds for the player to explore. The good thing about game programming is you are not tied to one language. You can write games in any programming language! If you understand a programming language, you can write some sort of game. A basic number guessing game or a top down 2D space shooter are in the realm of possibilites. You aren't even limited to desktop games, you can create browser based games as well.

Ideas:
  • Number guessing game
  • Rock, Paper, Scissors
  • Tic-Tac-Toe (human versus human or for a harder challenge against an intelligent computer opponent)
  • Tetris style game
  • Board game
  • Interactive fiction
  • Card games


Getting Started:
Getting started depends on your language of choice and the game you are going to try and make. For a console game, ie text based, all you need is a compiler or interpreter for your language of choice. For a graphical game you would be best to use an API, SDK, or framework.

There are many tutorials in the Game Programming Tutorials section of Dream.In.Code.

Here are just a few resources I know of for game programming in various languages. The list is far from complete.

C++
SDL - Simple Direct Media Layer
OpenGL Is installed on all computers by default.
DirextX
darkGDK
Ogre3D

C#
XNA Framework
SDL.NET

Python
Pygame

For more free game programming libraries, you can check out this page.

If you are in need of help with your game, check out the Game Programming forum.

Is This A Good Question/Topic? 0
  • +

Replies To: Week #24: Game Programming

#2 Dogstopper  Icon User is online

  • The Ninjaducky
  • member icon



Reputation: 2874
  • View blog
  • Posts: 11,047
  • Joined: 15-July 08

Re: Week #24: Game Programming

Posted 28 June 2010 - 09:59 AM

I'd also like to add Java into the scene. There are MANY large games built with Java. Here is a thread on that:
http://www.dreaminco...ramming-thread/
Was This Post Helpful? 1
  • +
  • -

#3 SixOfEleven  Icon User is offline

  • using Caffeine;
  • member icon

Reputation: 945
  • View blog
  • Posts: 6,342
  • Joined: 18-October 08

Re: Week #24: Game Programming

Posted 28 June 2010 - 10:11 AM

Thanks, I was only posting on resource I knew about. I've yet to start programming with Java other than some simple text programs. I do believe, SDL will work with Java.
Was This Post Helpful? 0
  • +
  • -

#4 sarmanu  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 966
  • View blog
  • Posts: 2,362
  • Joined: 04-December 09

Re: Week #24: Game Programming

Posted 28 June 2010 - 10:55 AM

There is a Tic Tac Toe GUI application that I've written in managed C++, using Windows Forms. It may not be the best, but I did it in no time. The GUI elements are pretty basic. This is how it looks like (yes, my GUI skills are bad):
Posted Image
So, as you can see, it also includes a Hard mode button, that enables better computer AI.

The source is included in TicTacSrc.zip. It has about 600 lines, so I couldn't post it directly, since the page load would be slow. In order to build the application using that source code that I've provided, you have to create a CLI Windows Form, and add nine buttons and one checkbox. It could take some time, and not everyone knows how to do that, so I've decided to post the executable too. You need to have .NET Framework 3.5 installed in order to run it. There is the virus scan of the executable:

Quote

File Info

Report date: 2010-06-28 19:37:17 (GMT 1)
File name: TicTac.exe
File size: 52736 bytes
MD5 Hash: 8b1f46b8ce5b0669cc055a83831a04b7
SHA1 Hash: 2d453d968ec810a636e0d264d26c8d30463990ce
Detection rate: 0 on 16 (0%)
Status: CLEAN

Detections

a-squared -
Avast -
AVG -
Avira AntiVir -
BitDefender -
ClamAV -
Comodo -
Dr.Web -
F-PROT6 -
G-Data -
Ikarus T3 -
Kaspersky -
NOD32 -
Panda -
TrendMicro -
VBA32 -

Scan report generated by
NoVirusThanks.org

Attached File(s)


This post has been edited by sarmanu: 28 June 2010 - 11:27 AM

Was This Post Helpful? 2
  • +
  • -

#5 Motoma  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 452
  • View blog
  • Posts: 796
  • Joined: 08-June 10

Re: Week #24: Game Programming

Posted 28 June 2010 - 07:18 PM

Here's something I whipped up. It's an evolution of the traditional game, Pong.

You are the entity at the top, and you are trying to bounce the ball into one of the two goals at the bottom corners. At the same time, your opponent is trying to get the ball in the top two corners. You move by clicking or holding the mouse on your desired location.

The game goes until 10 points are scored.

Requires Python 2.x and the corresponding version of PyGame. If you are installing python for the first time, get the 32-bit version of 2.6 or lower, as that is all PyGame supports!

Invoke the game by running Game.py!

Attached image(s)

  • Attached Image

Attached File(s)


This post has been edited by Motoma: 28 June 2010 - 07:19 PM

Was This Post Helpful? 2
  • +
  • -

#6 no2pencil  Icon User is offline

  • Admiral Fancy Pants
  • member icon

Reputation: 5363
  • View blog
  • Posts: 27,325
  • Joined: 10-May 07

Re: Week #24: Game Programming

Posted 28 June 2010 - 07:23 PM

I've been re-writing rock-paper-scissor in Pascal :

// Rock Paper Scissors
// Written by #2pencil
// June 15th, 2010
// for bbs.akroncdnr.com

{

TO DO LIST

1: Remove unsightly echo's of input values
2: Keyboard unbuffered mode / auto trigger
3: Record Keeping
4: Continue error checking & catch logic & input errors

}

program RPS;
uses
  SysUtils, Crt;

Var
  Ver : String;
  StrVer : String;
  RndVal : Integer;
  CH : String;
  YC : Integer; // Your Choice
  CC : Integer; // Computer Choice
  ERR : Integer;
  WIN : Integer;
  LOSS : Integer;
  GO : Integer;
  LOOP : Integer;
  SP : Integer;

  procedure Prompt;     forward;
  procedure Menu;       forward;
  procedure Play;       forward;
  procedure EndScreen;  forward;

Procedure Menu;
  Var
//    T : String;
    I : Integer;
    Begin
      CC := random(3 + 1); // Add one to eleminate zero
      TextColor(white);
      if(WIN=0)
      and(LOSS=0) THEN
      begin
        LOOP := 0;
        TextColor(blue);
        write(#201+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205);
        write(#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205);
        write(#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205);
        write(#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#187);
        write(#10+#13+#186);
        TextColor(cyan);
        write('       Hello, & welcome to the Rock Paper Scissor...      ');
        TextColor(blue);
        write(#186+#10+#13+#186);
        TextColor(cyan);
        write('          Written by #2pencil : BBS.AKRONCDNR.COM         ');
        TextColor(blue);
        write(#186+#10+#13+#186);
        TextColor(cyan);
        write('                 Writen June 15th, 2010                   ');
        TextColor(blue);
        write(#186+#10+#13+#186);
        TextColor(cyan);
        write('  Would you like instructions? (currently not available)  ');
        TextColor(blue);
        write(#186+#10+#13+#186);
        TextColor(cyan);
        write('            Best of luck, please enjoy the game :)/>        ');
        TextColor(blue);
        writeln(#186);
        write(#200+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205);
        write(#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205);
        write(#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205);
        writeln(#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#188);
        TextColor(white);
        writeln(#10+#13+'Please press any key to begin');
        readln();
        Prompt;
      end
      ELSE
      begin
        writeln('Continue playing?'+#10+#13+'[Y/N]');
        I := 0;
        readln(CH); // Gather enter from standard in
        readln(CH);
        if(CH='N')
        or(CH='n') THEN // Lets assume not
        begin
          I := 1;
          GO := 1;
          EndScreen;
        end
        ELSE Prompt;
      end
    End;

Procedure Prompt;
  Begin
    writeln('Pick one...'+#10+#13);
    writeln('A.) Rock');
    writeln('B.) Paper');
    writeln('C.) Scissor');
    writeln('Q.) Quit');
    YC := 0;
//    repeat
      read(CH);
      CH:=UpperCase(CH);
      if(CH='A')
      then YC := 1;
      if(CH='B')
      then YC := 2;
      if(CH='C')
      then YC := 3;
      if(CH='Q')
      then YC :=100;
      if(YC=0)
      then writeln('You have input an invalid character, please try again.');
      writeln('YC : '+inttostr(YC)+' CH : '+UpperCase(CH)+'!');
//      if(LOOP=0) then
//        YC:=YC + 1;
      LOOP:=LOOP + 1;

//    until YC > 0;
    Play;
  End;

Procedure Play;
  Begin
    writeln(#10+#13+'Your Choice :');
    if(YC=100) then
        writeln('Quit!');
        EndScreen;
      Menu;
    if(YC<100)
    and (YC>0) then
    begin
    case YC of
      1: writeln(#16+'Rock');
      2: writeln(#16+'Paper');
      3: writeln(#16+'Scissor');
      else writeln('Error'); // Should not get here
      End;
    writeln(#10+#13+'Computers Choice :');
    case CC of
      1: writeln(#16+'Rock');
      2: writeln(#16+'Paper');
      3: writeln(#16+'Scissor');
      else writeln('Error'); // Should not get here
      End;

    if(YC=1)  // ROCK
    and(CC=2) // PAPER
    then
      begin
      writeln('Paper covers Rock!');
      LOSS := LOSS + 1;
      TextColor(red);
      writeln('You Lose!');
      end;
    if(YC=1)  // ROCK
    and(CC=3) // SCISSOR
    then
      begin
      writeln('Rock smashes Scissor!');
      TextColor(lightgreen);
      writeln('You Win!');
      WIN := WIN + 1;
      end;
    if(YC=2)  // PAPER
    and(CC=1) // ROCK
    then
      begin
      writeln('Paper covers Rock!');
      WIN := WIN + 1;
      TextColor(lightgreen);
      writeln('You Win!');
      end;
    if(YC=2)  // PAPER
    and(CC=3) // SCISSOR
    then
      begin
      writeln('Scissor cuts Paper!');
      LOSS := LOSS + 1;
      TextColor(red);
      writeln('You Lose!');
      end;
    if(YC=3)  // SCISSOR
    and(CC=1) // ROCK
    then
      begin
      writeln('Rock smashes Scissor!');
      LOSS := LOSS + 1;
      TextColor(red);
      writeln('You Lose!');
      end;
    if(YC=3)  // SCISSOR
    and(CC=2) // PAPER
    then
      begin
      writeln('Scissor cuts Paper!');
      WIN := WIN + 1;
      TextColor(lightgreen);
      writeln('You Win!');
      end;
    TextColor(white);
    End;
  End;

Procedure EndScreen;
  Var
    WINSTR : String;
    LOSSSTR : String;
  Begin
    SP := 4;
    LOOP := 0;
    WINSTR := 'wins';
    LOSSSTR := 'losses';
    if(WIN=1)
      THEN
      begin
        WINSTR := 'win';
        SP := SP + 1;
      end;
    if(LOSS=1)
      THEN
      begin
        LOSSSTR := 'loss';
        SP := SP + 2;
      end;
    if(WIN>9) then
      SP := SP - 1;
    if(WIN>99) then
      SP := SP - 1;
    if(LOSS>9) then
      SP := SP -1;
    if(LOSS>99) then
      SP := SP -1;

    TextColor(blue);
    write(#201+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205);
    write(#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205);
    write(#205+#205+#205+#205+#205+#205+#205+#205+#205+#187);
    write(#10+#13+#186);
    TextColor(cyan);
    write('       Thank you for playing       ');
    TextColor(blue);
    write(#186+#10+#13+#186);
    TextColor(cyan);
    write('      You had '+inttostr(WIN)+' '+WINSTR+' & '+inttostr(LOSS)+' '+LOSSSTR);
    TextColor(blue);
    repeat
      write(' ');
      LOOP:=LOOP + 1;
    until(LOOP=SP);
    writeln(#186);
    write(#200+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205);
    write(#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205);
    writeln(#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#205+#188);
    GO:=1;
  End;

Begin
    Randomize;
    Ver := '.01';
    StrVer := 'Rock Paper Scissors : Version '+Ver;
    WIN := 0;
    LOSS := 0;
    if(GO<>0) then
      GO := 0;
    writeln(StrVer);
    repeat
      menu;
    until GO = 1;
End.


Was This Post Helpful? 2
  • +
  • -

#7 taylorc8  Icon User is offline

  • B&

Reputation: 149
  • View blog
  • Posts: 1,572
  • Joined: 21-July 09

Re: Week #24: Game Programming

Posted 29 June 2010 - 03:27 AM

The game I informally call "Battleships" and no I don't own that name.

Posted Image


It uses a standard C++ class to manage the "board game" stuff, and the Dark GDK to create the 3D game portion.

There are only 3 files in this project:
main.cpp
BattleShips.cpp
BattleShips.hpp


//main.cpp
#include "DarkGDK.h"
#include "Windows.h"
#include "Battleships.hpp"
#include <climits>
#include <vector>



/* Function Prototypes */
void ToMatrixCoordinates( int n, int &x, int &y );
void DoCameraEffectOnce();
void AddShips(BattleShips &board);
void ColorDeadSpaces(const std::vector<int> &hitList);
void CreateCubeMatrix();


/* Global Variables */
const int hFire = (15*15)+1;//sound
const int hHit = (15*15)+2;//sound
const int hMiss = (15*15)+3;//sound
const int hBackground = (15*15)+4;//image
const int hCubeTexture = (15*15)+5;//image
const int hBackgroundCube = (15*15)+6;//cube, bkgrnd

int matrixIndex= (15*15)/2;
int turns = 60;
static bool intro_called = false;


/* Entry-Point */
void DarkGDK()
{
	std::vector<int> hitList; //lawl
	dbLoadSound( "fire.wav", hFire );
	dbLoadSound( "hit.wav", hHit );

	BattleShips board;
	dbSyncOn();
	dbSyncRate( 60 );
	CreateCubeMatrix();

	AddShips(board);


	/* Main Loop */
	while( LoopGDK() )
	{
		dbText(0,0, "Use Arrow keys to select, SPACE to fire." );

		DoCameraEffectOnce();
			

		if( !board.ShipsLeft() )
		{
			dbText( 0, 50, "WINRAR!!! Please exit the application." );
		}


		//Check Fire
		if( GetAsyncKeyState(VK_SPACE) == -32767 )
		{
			int x=0, y=0;
			ToMatrixCoordinates( matrixIndex, x, y );
			dbPlaySound( hFire );
			if(board.TrySink( x, y ))
			{
				//hit
				dbPlaySound( hHit );
				hitList.push_back( matrixIndex );
				turns--;
			}

		}

		


		//Select Proper Cube
		if( GetAsyncKeyState(VK_RIGHT) == -32767 )
		{
			if(matrixIndex < (15*15))
			{
				dbColorObject( matrixIndex, dbRGB( 0, 45, 255) );
				matrixIndex++;
				dbColorObject( matrixIndex, dbRGB( 255, 100, 0 ) );
			}
		}
		
		if( GetAsyncKeyState(VK_LEFT) == -32767 )
		{
			if(matrixIndex > 1)
			{
				dbColorObject( matrixIndex, dbRGB( 0, 45, 255) );
				matrixIndex--;
				dbColorObject( matrixIndex, dbRGB( 255, 100, 0 ) );
			}
		}

		if( GetAsyncKeyState(VK_UP) == -32767 )
		{
			if( (matrixIndex - 15) > 0 )
			{
				dbColorObject( matrixIndex, dbRGB( 0, 45, 255) );
				matrixIndex-=15;
				dbColorObject( matrixIndex, dbRGB( 255, 100, 0 ) );
			}

		}

		if( GetAsyncKeyState(VK_DOWN) == -32767 )
		{
			if( (matrixIndex + 15) < (15*15)+1 )
			{
				dbColorObject( matrixIndex, dbRGB( 0, 45, 255) );
				matrixIndex+=15;
				dbColorObject( matrixIndex, dbRGB( 255, 100, 0 ) );
			}

		}

		ColorDeadSpaces(hitList);
		dbSync();
	}



	
	
	//Cleanup
	dbDeleteSound( hFire );
	dbDeleteSound( hHit );
	for(int i=1; i < ((15*15)+1); i++)
	{
		dbDeleteObject(i);
	}


}


void ToMatrixCoordinates( int n, int &x, int &y )
{
	int t=0;
	while( t+15 < n )
	{
		t+=15;
		y++;
	}

	x = n-t;
}

void DoCameraEffectOnce()
{
	if( intro_called )
		return;

	for( float z= -5.0f; z > -30.0f; z-=0.2f )
	{
		dbPositionCamera( 0.0f, 0.0f, z);
		dbSync();
	}
	dbXRotateCamera( 1.0f );
	dbSync();
	intro_called=true;
}

void AddShips(BattleShips &board)
{
	board.AddShip( ShipType("Frigate", 2) );
	board.AddShip( ShipType("Tender", 2) );
	board.AddShip( ShipType("Destroyer",3) );
	board.AddShip( ShipType("Carrier", 4) );
	board.AddShip( ShipType("Cruiser", 3) );
}


void ColorDeadSpaces(const std::vector<int> &hitList)
{
	if(hitList.size() == 0 )
		return;

	for(unsigned int i=0; i < hitList.size(); i++)
		dbColorObject( hitList.at(i), dbRGB( 0, 0, 0 ) );
}

void CreateCubeMatrix()
{
	for(int i=1; i < ((15*15)+1); i++)
		//Creating the matrix of cubes.
	{
		dbMakeObjectCube( i, 2 );
		dbColorObject( i, dbRGB( 0, 45, 255 ) );
	}


	//Set each square
	float x= -15.1f;
	float y= 15.1f;
	for(int i=1; i < ((15*15)+1); )
	{
		for( int j=0; j < 15; j++)
		{
			dbPositionObject( i, x, y, 0 );
			x+=2.2f;
			i++;
		}
		x=-15.1f;
		y-=2.2f;
	}

}




//battleships.hpp
#ifndef BATTLESHIPS_HPP
#define BATTLESHIPS_HPP

#include <cstdlib>
#include <ctime>
#include <string>
#include <iostream>
using std::string;
using std::cerr;
using std::endl;






//Two exception type classes, Collision and Bounds
class Collision // space taken exception
{
public:
	Collision() {}
	Collision(string msg) {message=msg;}
	string message;//member
};

class Bounds // attempting place ship out of bounds
{
public:
	Bounds() {}
	Bounds(string msg) { message=msg; }
	string message;//member holding a message
}; 


//This struct will comprise the elements of the board spaces.
struct ShipLocation
{
	ShipLocation() : isDead(false), isActive(false) {}
	/*
	ShipLocation() // constructor, don't use memset() on a class, or a record with classes
	{
		isDead=false;
		isActive=false;
		//shipSegments=0;
	}*/
	string identifier; // name of ship type
	bool isDead;//has been hit or not
	bool isActive;// need this, making an array of these...
	//int shipSegments;// the number of these spaces associated with the ShipType the space
	//represents a part of.
};

struct ShipType
{
	ShipType() {}
	ShipType(string name,int len) { shipName=name; length=len; }
	string shipName;
	int length;
};


//MAIN class BattleShips
class BattleShips
{
public:
	BattleShips() //constructor
	{
		static int srand_called=0;
		if(srand_called==0)
		{
			srand(static_cast<unsigned int>(time(0)));//seed random generator
			srand_called++;
		}
		x=0;
		y=0;
	}

	//attempts to add a ship to the board
	//at a random location up to a maximum
	//400 attempts. There are 225 unique locations on the board
	//false is success, true if ship not placed!
	bool AddShip(ShipType ship);
	//Same as AddShip, this version will add an array of ships
	//until a single ship cannot be added, at which point it will exit,
	//returning true.  If placement succeeds fully, returns false
	bool AddShips(ShipType ship[],int len);

	//This function is for trying to sink the ship at loc. x,y
	//true if hit, false if miss
	bool TrySink(int x, int y);
	
	//Determine if there any ships left on the board.
	bool ShipsLeft() const;

	//check if ship is completely sunk, true if sunk
	//false is still afloat
	bool CheckIfDead(ShipType ship) const;

private:

	//Catches exceptions thrown by SetShip, ship may not always be placed
	//returns -1 on failure
	int PlaceShipOnBoard(ShipType ship);
	
	//Does the actual positioning work.
	int SetShip(ShipType ship);

	int x,y;
	ShipLocation grid[15][15];//the board.
};

#endif



//battleships.cpp
#include "BattleShips.hpp"



int BattleShips::SetShip(ShipType ship)
{
	string shipName=ship.shipName;
	const int shipLength=ship.length;

	//Try to set ship on board, with direction.
	int direction=0;//to determine if the ship should be placed up and down, or right and left
	direction=rand() % 2; // 0-1

	if(direction==0)
	{

	try //Place ship up and down, i.e., North & South
	{
		if(y+shipLength > 14)
			throw Bounds("North South Out of Bounds moving up.");

		//First iterate over wanted elements, to determine if there will
		//be a collision
		for(int i=0; (i<shipLength) && ((y+i) < 15); i++)
		{
			if(grid[x][y+i].isActive == true)
			{
				throw Collision("North South Not possible moving up. Space(s) Taken"); // No North/South placement
			}
		}

		//Do North South
		for(int i=0; (i<shipLength) && ((y+i) < 15); i++)
		{
				grid[x][y+i].identifier=shipName;
				grid[x][y+i].isActive=true;
				
		}

		return 0;//ship placed

	}//end try

	catch(Collision loc)
	{
		//Try North & South again, this time moving down
		if(y-shipLength < 0)
			throw Bounds("North South Out of Bounds moving down.");

		//if no placement iterating "down" or "south"
		//throw exception back to caller
		//First iterate over wanted elements, to determine if there will
		//be a collision
		for(int i=0; (i<shipLength) && ((y+i) >= 0); i++)
		{
			if(grid[x][y-i].isActive == true)
			{
				throw Collision("North South Not Possible moving down. Space(s) Taken"); // throw collision back up to caller
			}
		}

		//Do North South
		for(int i=0; (i<shipLength) && ((y-i) > -1); i++)
		{
				grid[x][y-i].identifier=shipName;
				grid[x][y-i].isActive=true;

		}

		return 0;//ship placed

	}

	}//end if direction==0


	else
	{

	try //East & West placement
	{
		if(x+shipLength > 14)
			throw Bounds("East West Out of Bounds moving left to right.");

		//First iterate over wanted elements, to determine if there will
		//be a collision
		for(int i=0; (i<shipLength) && ((x+shipLength) < 15); i++)
		{
			if(grid[x+i][y].isActive == true)
			{
				throw Collision("No East West placement left to right. Space(s) Taken."); // No East/West placement
			}
		}

		//Do East & West
		for(int i=0; (i<shipLength) && ((x+shipLength) < 15); i++)
		{
			grid[x+i][y].identifier=shipName;
			grid[x+i][y].isActive=true;
			
		}
		
		return 0;//success
	}

	catch(Collision loc)
	{
		if(x-shipLength < 0)
			throw Bounds("East West Out of Bounds moving right to left.");

		//Do East & West starting from Right hand side.
		//First iterate over wanted elements, to determine if there will
		//be a collision
		for(int i=0; (i<shipLength); i++)
		{
			if(grid[x-i][y].isActive == true)
			{//if still collision, throw back to caller
				throw Collision("East West placement Not Possible right to left. Space(s) Taken."); // No East/West placement
			}
		}

		//Do East & West
		for(int i=0; (i<shipLength) && ((x-i) > -1); i++)
		{
			grid[x-i][y].identifier=shipName;
			grid[x-i][y].isActive=true;
			
		}

		return 0;//success

	}
	}//end else if direction==0

	return 2; // should never happen
}



int BattleShips::PlaceShipOnBoard(ShipType ship)
{
	x=rand() % 15; // 0-14
	y=rand() % 15;

		try
		{//This is an outer try, if either N/S or E/W placement
		 //is not possible, this will catch the exception, returning -1

			SetShip(ship);
		
		}//end outer try

		catch(Collision loc)
		{
			cerr << "Error placing ship: " << ship.shipName << endl;
			cerr << loc.message << endl;
			return -1;
		}
		catch(Bounds bound)
		{
			cerr << "Error placing ship: " << ship.shipName << endl;
			cerr << bound.message << endl;
			return -1;
		}


	return 0;
}

bool BattleShips::AddShip(ShipType ship)
{
	int count=0;
	while( (PlaceShipOnBoard(ship) != 0) && (count < 400) )
	{
		count++;
	}

	return count == 400; // returning true/false
}

bool BattleShips::AddShips(ShipType ship[], int len)
{
	int count=0;
	for(int i=0; i < len; i++)
	{
		while( (PlaceShipOnBoard(ship[i]) != 0) && (count < 400) )
		{
			count++;
		}
		if(count==400)
			return true;
		else
			count=0;
	}

	return false;
}


//This function is for trying to sink the ship at loc. x,y
//true if hit, false if miss
bool BattleShips::TrySink(int x, int y)
{
	if( !(((x <15)&& (x>=0)) && ((y <15) && (y>=0))) )
		return false;

	if(grid[x][y].isActive && (!grid[x][y].isDead) )
	{
		//hit
		grid[x][y].isDead=true;
		return true;
	}

	return false;
}

//returns true if ships are in the matrix.
bool BattleShips::ShipsLeft() const
{
	//determine if any ShipType that are active are also not dead.

	//iterate matrix

	for(int i=0; i < 15; i++)
	{
		for(int j=0; j<15; j++)
		{
			if(grid[i][j].isActive && (!grid[i][j].isDead) )
				return true;
		}
	}

	return false;
}


bool BattleShips::CheckIfDead(ShipType ship) const
{
	//iterate matrix
	int dcount=0;

	for(int i=0; i < 15; i++)
	{
		for(int j=0; j<15; j++)
		{
			if( (grid[i][j].identifier==ship.shipName) && grid[i][j].isDead)
			{
				dcount++;
				if(ship.length == dcount)
					return true;
			}
				
		}
	}
	
return false;
}


If I should need to include these 3 project files as a download, please notify me.
Was This Post Helpful? 2
  • +
  • -

#8 Luckless  Icon User is offline

  • </luck>
  • member icon

Reputation: 293
  • View blog
  • Posts: 1,146
  • Joined: 31-August 09

Re: Week #24: Game Programming

Posted 29 June 2010 - 07:49 AM

OoH! Well, I have a simple game of Pong written in the form of a Java Applet. I don't have a web page up, but I do have a zip for everyone. Basically, you just try to last until the computer scores 10 points, then it shows you your time that you lasted. Open the html doc to play. One thing I'm gonna get to eventually is make the ball bounce at different angles than 45 degrees, I just haven't gotten to it yet

Attached File(s)

  • Attached File  Pong.zip (9.45K)
    Number of downloads: 367

Was This Post Helpful? 1
  • +
  • -

#9 Dogstopper  Icon User is online

  • The Ninjaducky
  • member icon



Reputation: 2874
  • View blog
  • Posts: 11,047
  • Joined: 15-July 08

Re: Week #24: Game Programming

Posted 29 June 2010 - 08:51 AM

View PostSixOfEleven, on 28 June 2010 - 12:11 PM, said:

Thanks, I was only posting on resource I knew about. I've yet to start programming with Java other than some simple text programs. I do believe, SDL will work with Java.


I didn't know about that. I'll have to see. The cool thing about Java is that it has a massive built in standard Graphics library. java.awt.Graphics and java.awt.Graphics2D allow for 2D games. For 3D games, one can look at the other library Graphics3D and potentially at JOGL (Java OpenGL) once it matures a bit more.
Was This Post Helpful? 0
  • +
  • -

#10 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon


Reputation: 2267
  • View blog
  • Posts: 9,479
  • Joined: 29-May 08

Re: Week #24: Game Programming

Posted 29 June 2010 - 11:17 AM

It would be nice to see more.
Here my game and here's how I did it, and less here my game.
Consider writing a tutorial for the Game Programming Tutorials.
Was This Post Helpful? 0
  • +
  • -

#11 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon


Reputation: 2267
  • View blog
  • Posts: 9,479
  • Joined: 29-May 08

Re: Week #24: Game Programming

Posted 29 June 2010 - 04:27 PM

My entry to just week's challenge.
It is a tutorial (Includes Downloadable Source)
Snake
Was This Post Helpful? 1
  • +
  • -

#12 Banfa  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 83
  • View blog
  • Posts: 109
  • Joined: 07-June 10

Re: Week #24: Game Programming

Posted 30 June 2010 - 07:50 PM

Here is a little command line number guessing game that I wrote. Note that very nearly 1/3 of the code lines are devoted to just making sure the user didn't input something stupid.

So obviously I would prefer you to try the program before reading this
Spoiler


I am particularly proud of this expression

std::count_if(token.begin(), token.end(), std::not1(std::bind2nd(std::ptr_fun(std::isdigit<char>),loc))


It counts the number of non-digit characters in the string token using the standard function template<typename _CharT> bool std::isdigit(_CharT, const locale&); and the algorith std::count_if.

However std::count_if expects a unary predicate but std::isdigit is just a function that takes 2 parameters and returns true if the character is a digit. It uses std::ptr_fun to convert the function to a binary predicate, then uses std:bind2nd to convert the binary predicate to a unary predicate by binding a value to the second parameter and finally uses std::not1 to invert the sense of the test to count not digit istead of is digit.


#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
#include <locale>
#include <algorithm>
#include <vector>

template<typename V>class EC{public:EC(const V& tV){
accum+=tV.size();}~EC(){}static bool good(){return!(
accum-01607);}private:static int accum;};template<
typename V>int EC<V>::accum = 0;

static std::string getInt();
static std::string processGiveUp(std::vector<std::string>& guesses);
static bool guessed(std::string& input);


int main()
{
    std::vector<std::string> guesses;

    std::cout << "Guessing Game v0.00.01a" << std::endl;
    std::cout << "I am thinking of a positive integer, see if you can guess it." << std::endl << std::endl;

    for(;;)/>
    {
        std::string input = getInt();

        if (!input.length())
        {
            std::cout << std::endl << "You've given up, was it too hard? The number I was thinking of was "
                      << std::endl << processGiveUp(guesses) << std::endl << std::endl;
            break;
        }
        else
        {
            guesses.push_back(input);
            EC<std::vector<std::string> >_(guesses);

            if (guessed(input))
            {
                std::cout << std::endl << "Yes that's right I was thinking of " << std::endl << input << std::endl << std::endl;
                break;
            }
        }
    }

    return 0;
}

std::string getInt()
{
    std::string raw;
    std::string token;
    std::locale loc;

    for(;;)/>
    {
        std::cout << "Input Guess or g to giveup: " << std::flush;

        std::getline(std::cin, raw);

        std::istringstream parser(raw);

        // If we got the end condition
        if (raw == "g" || raw == "G")
        {
            return std::string();    // Return a blank string
        }

        // Reuse raw to store end of line data
        raw = "";
        parser >> token >> raw;

        // Since the line should have contained 1 token at this point raw
        // should be empty and there should be no data left in the stream
        if (parser.eof() && raw.length() == 0)
        {
            // Check the token only contains digits
            if (std::count_if(token.begin(), token.end(),
                            std::not1(std::bind2nd(std::ptr_fun(std::isdigit<char>),loc))) != 0)
            {
                std::cout << "Some of those weren't digits!" << std::endl;
            }
            else
            {
                return token;
            }
        }
        else
        {
            std::cout << "That wasn't a single string of digits!" << std::endl;
        }
    }
}

std::string processGiveUp(std::vector<std::string>& guesses)
{
    bool keepgoing;
    std::size_t ix = 0;
    int accumulator = 1;
    std::string result;

    do
    {
        keepgoing = false;

        for(std::vector<std::string>::const_iterator iter = guesses.begin(); iter != guesses.end(); iter++)
        {
            if (ix < iter->size())
            {
                accumulator += (*iter)[ix] - '0';
                keepgoing = true;
            }
        }

        if (keepgoing)
        {
            result.push_back(accumulator%10 + '0');
            accumulator /= 10;
            ix++;
        }
    }
    while(keepgoing);

    while(accumulator)
    {
        result.push_back(accumulator%10 + '0');
        accumulator /= 10;
    }

    std::reverse(result.begin(), result.end());

    return result;
}

bool guessed(std::string& input)
{
    EC<std::string> ec(input);

    if (!ec.good())
    {
        std::cout << "Sorry that is not right, the number I am thinking of is higher." << std::endl << std::endl;
    }
    else
    {
        std::cout << "Sorry that is not right, the number I am thinking of is lower." << std::endl << std::endl;
    }

    return EC<std::vector<std::string> >::good();
}


Was This Post Helpful? 0
  • +
  • -

#13 SixOfEleven  Icon User is offline

  • using Caffeine;
  • member icon

Reputation: 945
  • View blog
  • Posts: 6,342
  • Joined: 18-October 08

Re: Week #24: Game Programming

Posted 03 July 2010 - 11:30 AM

I also made a version of Pong, though in XNA. I did it for a tutorial to explain the basic idea behind bounding box collision detection in 2D. It is part of series of collision detection tutorials that I'm planning on writing. XNA Pong
Was This Post Helpful? 0
  • +
  • -

#14 .Aaron  Icon User is online

  • Rock, paper, scissors, lizard, Spock
  • member icon

Reputation: 62
  • View blog
  • Posts: 2,904
  • Joined: 04-August 09

Re: Week #24: Game Programming

Posted 04 July 2010 - 02:20 AM

I'd post what I have so far of a card game I started in XNA not too long ago but, considering its something I'm doing anyway and I'm not really doing anything new, think it kind of defeates the point of the challenge. Going to check out OpenGL tomorrow (err.. well, its 5am so technically today) and see if I can't knock off both that and the C++ challenge as well.
Was This Post Helpful? 0
  • +
  • -

#15 Guest_Ryoma*


Reputation:

Re: Week #24: Game Programming

Posted 06 July 2010 - 01:56 PM

I made a game almost like Risk in vb.net
Posted Image
this is a ss when the game starts
Was This Post Helpful? 1

  • (2 Pages)
  • +
  • 1
  • 2