Quick Search for:  in language:    
playable,game,Battleships,Microsoft,console,m
   Code/Articles » |  Newest/Best » |  Community » |  Jobs » |  Other » |  Goto » | 
CategoriesSearch Newest CodeCoding ContestCode of the DayAsk A ProJobsUpload
C/ C++ Stats

 Code: 715,766. lines
 Jobs: 107. postings

 How to support the site

 
Sponsored by:

 
You are in:
 
Login





Latest Code Ticker for C/ C++
Click here to see a screenshot of this code!Button Game
By L!xy on 1/29

(Screen Shot)

SimpleService
By Gaidar Magdanurov on 1/29


ip2bin
By Joe Sloan on 1/29


Click here to see a screenshot of this code!c++ basic all
By Hamdi Farah on 1/28

(Screen Shot)

biopro.c --- search for words that do not exist in the dictionary file
By Donald Bono on 1/28


BruteForce Engine
By koby-GR on 1/28


Catch Me If U Can !!
By ashish & manas on 1/27


nOS ver 1.0
By - Snake - on 1/27


WordInFile.c -- look up a dictionary file for the word you just entered (source code only)
By Donald Bono on 1/27


Click here to put this ticker on your site!


Add this ticker to your desktop!


Daily Code Email
To join the 'Code of the Day' Mailing List click here!

Affiliate Sites



 
 
   

Battleships

Print
Email
 
VB icon
Submitted on: 12/19/2003 6:39:33 AM
By: Simon Fraser  
Level: Beginner
User Rating: Unrated
Compatibility:C, C++ (general), Microsoft Visual C++

Users have accessed this code 606 times.
 
(About the author)
 
     A playable game of Battleships for Microsoft console mode using a variety of coding techniques. My first project and a rating/feedback would be most appreciated. Thanks.

 
code:
Can't Copy and Paste this?
Click here for a copy-and-paste friendly version of this code!
 
Terms of Agreement:   
By using this code, you agree to the following terms...   
1) You may use this code in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.   
2) You MAY NOT redistribute this code (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
3) You may link to this code from another website, but ONLY if it is not wrapped in a frame. 
4) You will abide by any additional copyright restrictions which the author may have placed in the code or code's description.

//**************************************
//     
// Name: Battleships
// Description:A playable game of Battle
//     ships for Microsoft console mode using a
//     variety of coding techniques. My first p
//     roject and a rating/feedback would be mo
//     st appreciated. Thanks.
// By: Simon Fraser
//
// Assumes:This code doesn't use Borland
//     's graphics - all done using Microsoft c
//     onsole.I got a bit carried away with mac
//     ros where functions would have been neat
//     er.
//
// Side Effects:Known problem - in Win 9
//     8 "Enter name" routine for hi scores pic
//     ks up last key press. OK in XP.
//
//This code is copyrighted and has// limited warranties.Please see http://
//     www.Planet-Source-Code.com/vb/scripts/Sh
//     owCode.asp?txtCodeId=7312&lngWId;=3//for details.//**************************************
//     

/* Written in C using Microsoft VisualC++ 6.0 by Simon Fraser
December 2003 ... first project after a month's learning. 
Compiles fine in debug mode. Release mode requires 
settings: optimisations - disable debug
			 link generate debug info - enabled
Known problem - in Win 98 Enter name routine for hi scores picks up last key
press. OK in XP.
*/
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>	 
#include <conio.h> 
#include<wincon.h>		 
#include<string.h>
#include <sys/timeb.h> 
#include <time.h>	 
// Standard error macro for reporting AP
//     I errors 
#define PERR(bSuccess, api){if(!(bSuccess)) printf("%s:Error %d from %s \
on line %d\n", __FILE__, GetLastError(), api, __LINE__);}
// macro to set text colours to normal
#define RESETCOLOUR SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),\
BACKGROUND_BLUE& BACKGROUND_RED& BACKGROUND_GREEN|\
FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE ); 
#define DRAWGREEN FillConsoleOutputAttribute(GetStdHandle(STD_OUTPUT_HANDLE),\
		BACKGROUND_INTENSITY | BACKGROUND_GREEN,y,locate,p);
#define DRAWRED FillConsoleOutputAttribute(GetStdHandle(STD_OUTPUT_HANDLE), \
		BACKGROUND_INTENSITY | BACKGROUND_RED,y,locate,p);
#define DRAWPURPLE FillConsoleOutputAttribute(GetStdHandle(STD_OUTPUT_HANDLE), \
		BACKGROUND_INTENSITY | BACKGROUND_BLUE| BACKGROUND_RED,y,locate,p);
#define DRAWBEIGE FillConsoleOutputAttribute(GetStdHandle(STD_OUTPUT_HANDLE), \
		BACKGROUND_INTENSITY | BACKGROUND_BLUE|BACKGROUND_GREEN,y,locate,p);
#define DRAWBLUE FillConsoleOutputAttribute(GetStdHandle(STD_OUTPUT_HANDLE), \
		BACKGROUND_INTENSITY | BACKGROUND_BLUE,y,locate,p);
#define SETCURSOR SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), \
		cursor);
#define CELLBORDER DrawText(" ",cursor.X ,cursor.Y,BACKGROUND_BLUE| \
		 FOREGROUND_BLUE | FOREGROUND_RED|FOREGROUND_GREEN);
#define CELLDETAILS cursor.X ,cursor.Y,BACKGROUND_INTENSITY |BACKGROUND_BLUE| \
		 FOREGROUND_INTENSITY|FOREGROUND_BLUE | FOREGROUND_RED|FOREGROUND_GREEN
#define CELLDETAILS_MISS cursor.X ,cursor.Y,BACKGROUND_INTENSITY |BACKGROUND_BLUE| \
		 FOREGROUND_INTENSITY|FOREGROUND_BLUE | FOREGROUND_RED|FOREGROUND_GREEN
#define CELLDETAILS_AC cursor.X ,cursor.Y,BACKGROUND_INTENSITY | \
		BACKGROUND_RED
#define CELLDETAILS_CRUISER cursor.X ,cursor.Y,BACKGROUND_INTENSITY |\
		BACKGROUND_GREEN
#define CELLDETAILS_DESTROYER cursor.X ,cursor.Y,BACKGROUND_INTENSITY |\
		BACKGROUND_BLUE | BACKGROUND_RED
#define CELLDETAILS_SUB cursor.X ,cursor.Y,BACKGROUND_INTENSITY |\
		BACKGROUND_BLUE|BACKGROUND_GREEN
#define ACLENGTH 4
#define CLENGTH 3
#define DLENGTH 2
#define SLENGTH 1
#define NUMHISCORES 10
#define NUMCELLS 25
#define NUMSHIPCELLS 10
#define MAXATTEMPTS 18
#define NAMELENGTH 10
#define AMMO 20
#define UNSORTED 0
#define SORTED 1
typedef struct SHIP
    {
    	unsigned int X, Y;		
    	int direction;			// horizontal or vertical flag, 1 & 0
    	int ShipType;			// Length
    	SHIP* next;
} Ship;

struct map { int X; // location coords int Y; int flag; // cell selected yet? char shipType; // A = a/carrier etc,m = miss };
struct gHITS { int totalHits; int acHits; int cHits; int dHits; int subHits; };
struct HISCORE { int points; char name[NUMHISCORES]; };
void setScreenSize(); void drawIntro(); void showCursor(); void hideCursor(); void menu(); void letsPlay(); void instructions(); void highScores(); void drawShips(); void drawAC(Ship* ac ); void drawCruiser(Ship* Cruiser ); void drawDestroyer(Ship* Destroyer ); void drawSub(Ship* Submarine ); void doHiScore(int nAttempts); void drawGrid(); void assignToGrid(int letter, int* pAttempts); int CheckForShip(int x,int y, bool *pSunk); Ship* drawAllShips(); int searchShipList(Ship check); void sinkingShip(int ShipType); void push(Ship** headPtr, int x,int y, int direction, int ShipType); void resetGlobals(); void sortScores(HISCORE* HiScore); void cls( HANDLE hConsole ); // clearscreen function MSDN void DrawText(char* tex,int x,int y,WORD colour); //write text to screen Iain Fraser char* getTime(); void splash(char* title); void clearscreen(); void setTitle(char* title); void displayTime(char* title); void displayProgramStart(char* title); // globals extern Ship* gShipNode; extern int gMaxAttempts[25]; // max number of attempts extern gHITS gHits; void displayProgramStart(char* title) { splash(title); displayTime(title); }
// CLEARSCREEN FUNCTION - MSDN void cls( HANDLE hConsole ) { COORD coordScreen = { 0, 0 }; /* here's where we'll home the cursor */ bool bSuccess; DWORD cCharsWritten; CONSOLE_SCREEN_BUFFER_INFO csbi; /* to get buffer info */ DWORD dwConSize; /* number of character cells in the current buffer */ /* get the number of character cells in the current buffer */ bSuccess = GetConsoleScreenBufferInfo( hConsole, &csbi; ); PERR( bSuccess, "GetConsoleScreenBufferInfo" ); dwConSize = csbi.dwSize.X * csbi.dwSize.Y; /* fill the entire screen with blanks */ bSuccess = FillConsoleOutputCharacter( hConsole, (TCHAR) ' ', dwConSize, coordScreen, &cCharsWritten; ); PERR( bSuccess, "FillConsoleOutputCharacter" ); /* get the current text attribute */ bSuccess = GetConsoleScreenBufferInfo( hConsole, &csbi; ); PERR( bSuccess, "ConsoleScreenBufferInfo" ); /* now set the buffer's attributes accordingly */ bSuccess = FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten; ); PERR( bSuccess, "FillConsoleOutputAttribute" ); /* put the cursor at (0, 0) */ bSuccess = SetConsoleCursorPosition( hConsole, coordScreen ); PERR( bSuccess, "SetConsoleCursorPosition" ); return; }
// Write text to sceen - Iain Fraser void DrawText(char* tex,int x,int y,WORD colour) { // Get Size Of String _CHAR_INFO *info = new _CHAR_INFO[strlen(tex)]; _CHAR_INFO *temp = info; for(unsigned int i=0;i<strlen(tex);i++) { temp->Char.AsciiChar = tex[i];//(char)i*j; temp->Attributes = colour; temp++; } COORD p1,p2; p1.X = strlen(tex); p1.Y = 1; p2.X = p2.Y = 0; _SMALL_RECT rct; rct.Left = x; rct.Top = y; rct.Right = rct.Left + strlen(tex); rct.Bottom = rct.Top + 1; DWORD result = WriteConsoleOutput(GetStdHandle(STD_OUTPUT_HANDLE),info,p1,p2,&rct;); if(!result) { printf("error writing to console - %d",result); } delete [] info; return; }
char* getTime() { struct _timeb timebuffer; char *timeline; _ftime( &timebuffer; ); timeline = ctime( & ( timebuffer.time ) ); return timeline; }
void splash(char* title) { setTitle(title); // TO FILL CELLS OF CONSOLE WITH COLOUR COORD locate; // COORD defined in wincon.h locate.X = 0; locate.Y = 0; unsigned long *p; unsigned long y = 80; // number of cells to take colour p = &y; FillConsoleOutputAttribute(GetStdHandle(STD_OUTPUT_HANDLE), BACKGROUND_INTENSITY | BACKGROUND_GREEN,y,locate,p); locate.X = 0; locate.Y = 1; Sleep(20); FillConsoleOutputAttribute(GetStdHandle(STD_OUTPUT_HANDLE), BACKGROUND_INTENSITY | BACKGROUND_RED,y,locate,p); DrawText("SAM91",0,1,BACKGROUND_INTENSITY| BACKGROUND_RED| FOREGROUND_INTENSITY|FOREGROUND_GREEN ); DrawText("SAM91",33,1,BACKGROUND_INTENSITY| BACKGROUND_RED| FOREGROUND_INTENSITY|FOREGROUND_GREEN ); DrawText("SAM91",75,1,BACKGROUND_INTENSITY| BACKGROUND_RED| FOREGROUND_INTENSITY|FOREGROUND_GREEN ); locate.X = 0; locate.Y = 2; Sleep(20); FillConsoleOutputAttribute(GetStdHandle(STD_OUTPUT_HANDLE), BACKGROUND_INTENSITY | BACKGROUND_GREEN,y,locate,p); Sleep(20); printf("\n\n"); RESETCOLOUR Sleep(20); }
void clearscreen() { cls(GetStdHandle(STD_OUTPUT_HANDLE)); }
void setTitle(char* title) { char buffer[29]; strcpy(buffer,title); SetConsoleTitle(buffer); }
void displayTime(char* title) { char* currentTime = getTime(); SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), BACKGROUND_INTENSITY |BACKGROUND_GREEN| FOREGROUND_INTENSITY | FOREGROUND_RED); printf("%s started at %s\n",title, currentTime); RESETCOLOUR }
void drawIntro() { // set cursor position COORD cursor; cursor.X = 12; cursor.Y = 13; SETCURSOR puts(" BATTLESHIPS\n"); cursor.X = 12; cursor.Y = 15; SETCURSOR puts("Aircraft Carriers"); cursor.X = 12; cursor.Y = 17; SETCURSOR puts("Cruisers"); cursor.X = 12; cursor.Y = 19; SETCURSOR puts("Destroyers"); cursor.X = 12; cursor.Y = 21; SETCURSOR puts("Submarines"); hideCursor(); // TO FILL CELLS OF CONSOLE WITH COLOUR COORD locate; // COORD defined in wincon.h locate.X = 10; locate.Y = 5; unsigned long *p; unsigned long y = 21; // number of cells to take colour p = &y; DRAWGREEN locate.X = 10; locate.Y = 6; DRAWGREEN cursor.X = 12; cursor.Y = 5; SETCURSOR puts("Sam91 Battleships"); for (int i = 11; i < 21; i++) { locate.Y = i; DRAWBLUE for (int j = 12; j < 22; j++) { locate.Y = j; DRAWRED } } cursor.X = 42; cursor.Y = 5; SETCURSOR puts("SELECT OPTION"); cursor.X = 42; cursor.Y = 7; SETCURSOR puts("(P)LAY"); cursor.X = 42; cursor.Y = 9; SETCURSOR puts("(I)NSTRUCTIONS"); cursor.X = 42; cursor.Y = 11; SETCURSOR puts("(H)IGH SCORES"); cursor.X = 42; cursor.Y = 13; SETCURSOR puts("(Q)UIT"); }
// draw all ships for intro void drawShips() { Ship ShipAC; ShipAC.X = 42; ShipAC.Y = 15; Ship* shipPtr; shipPtr = &ShipAC; drawAC(shipPtr ); COORD cursor; cursor.X = 50; cursor.Y = 15; SETCURSOR puts("AIRCRAFT CARRIER"); ShipAC.X = 42; ShipAC.Y = 17; drawCruiser(shipPtr ); cursor.X = 50; cursor.Y = 17; SETCURSOR puts("CRUISER"); ShipAC.X = 42; ShipAC.Y = 19; drawDestroyer(shipPtr ); cursor.X = 50; cursor.Y = 19; SETCURSOR puts("DESTROYER"); ShipAC.X = 42; ShipAC.Y = 21; drawSub(shipPtr ); cursor.X = 50; cursor.Y = 21; SETCURSOR puts("SUBMARINE"); }
void drawAC(Ship* ShipAC ) // aircraft carrier { COORD locate; locate.X = ShipAC->X; locate.Y = ShipAC->Y; unsigned long *p; unsigned long y = ACLENGTH; // number of cells to take colour p = &y; DRAWRED }
void drawCruiser(Ship* Cruiser ) // aircraft carrier { COORD locate; locate.X = Cruiser->X; locate.Y = Cruiser->Y; unsigned long *p; unsigned long y = CLENGTH; // number of cells to take colour p = &y; DRAWGREEN }
void drawDestroyer(Ship* Destroyer ) { COORD locate; locate.X = Destroyer->X; locate.Y = Destroyer->Y; unsigned long *p; unsigned long y = DLENGTH; // number of cells to take colour p = &y; DRAWPURPLE }
void drawSub(Ship* Submarine ) { COORD locate; locate.X = Submarine->X; locate.Y = Submarine->Y; unsigned long *p; unsigned long y = SLENGTH; // number of cells to take colour p = &y; DRAWBEIGE }
// for player to select cell void drawGrid() { COORD cursor; cursor.X = 5 ; cursor.Y =6; for(int i =65; i<65+25; i++) // generate char labels using ASCII { if (i%5 == 0) {cursor.Y+=2; cursor.X =5;} // move to next line CELLBORDER cursor.X++; char label[1]; sprintf(label,"%c",i); DrawText(label, CELLDETAILS); // see battle.h cursor.X++; CELLBORDER cursor.X++; } }
void assignToGrid(int letter, int* pAttempts) { bool sunk = false; bool *pSunk = &sunk; if (*pAttempts == 0) {gMaxAttempts[0] = letter;} else { gMaxAttempts[*pAttempts] = letter; } COORD cursor; cursor.X = 6 ; cursor.Y =8; // A position int status =0; if ( letter < 65 || letter > 89) {return;} // up to Y not Z for(int i =65; i<65+25; i++) { if (i%5 == 0 && i != 65) {cursor.Y+=2; cursor.X = 6;} if (letter == i) { status = CheckForShip(cursor.X,cursor.Y, pSunk); switch(status) { case 0: DrawText("*", CELLDETAILS_MISS); cursor.X = 5; cursor.Y = 19; DrawText("MISS ",cursor.X,cursor.Y, FOREGROUND_INTENSITY|FOREGROUND_RED); DrawText("",cursor.X,cursor.Y+1, FOREGROUND_INTENSITY|FOREGROUND_RED); // get rid of 2nd line carrier Sleep(500); DrawText("",cursor.X,cursor.Y, FOREGROUND_INTENSITY|FOREGROUND_RED); break; case 1: DrawText(" ", CELLDETAILS_AC); if (sunk == true) { cursor.X = 5; cursor.Y = 19; DrawText("AIRCRAFT CARRIER SUNK",cursor.X,cursor.Y, FOREGROUND_INTENSITY|FOREGROUND_RED); cursor.X = 50; cursor.Y = 15; SETCURSOR puts("AIRCRAFT CARRIER SUNK!"); sunk = false; } break; case 2: DrawText(" ", CELLDETAILS_CRUISER); if (sunk == true) { cursor.X = 5; cursor.Y = 19; DrawText("CRUISER SUNK",cursor.X,cursor.Y, FOREGROUND_INTENSITY|FOREGROUND_RED); cursor.X = 50; cursor.Y = 17; SETCURSOR puts("CRUISER SUNK!"); sunk = false; } break; case 3: DrawText(" ", CELLDETAILS_DESTROYER); if (sunk == true) { cursor.X = 5; cursor.Y = 19; DrawText("DESTROYER SUNK",cursor.X,cursor.Y, FOREGROUND_INTENSITY|FOREGROUND_RED); cursor.X = 50; cursor.Y = 19; SETCURSOR puts("DESTROYER SUNK!"); sunk = false; } break; case 4: DrawText(" ", CELLDETAILS_SUB); if (sunk == true) { cursor.X = 5; cursor.Y = 19; DrawText("SUBMARINE SUNK",cursor.X,cursor.Y, FOREGROUND_INTENSITY|FOREGROUND_RED); cursor.X = 50; cursor.Y = 21; SETCURSOR puts("SUBMARINE SUNK!"); sunk = false; } break; } } cursor.X+=3; } *pAttempts = (*pAttempts) + 1; // only updates calling func if letter chosen // in range cursor.X = 5; cursor.Y = 21; int ammoLeft = AMMO - *pAttempts; char ammo[22]; itoa(ammoLeft,ammo,10); strcat(ammo, " shots remaining "); DrawText(ammo,cursor.X,cursor.Y,BACKGROUND_INTENSITY |BACKGROUND_BLUE| FOREGROUND_INTENSITY|FOREGROUND_BLUE | FOREGROUND_RED|FOREGROUND_GREEN); }
int CheckForShip(int x,int y, bool *pSunk) { COORD cursor; cursor.X= 5; cursor.Y = 19; // for text writing Ship check; check.X = x; check.Y = y; int ship = searchShipList(check); // pass coords to be compared against list // and return the type of ship (0 if miss) switch(ship) { case 1: // clear truncated sentances DrawText("",cursor.X,cursor.Y, FOREGROUND_INTENSITY|FOREGROUND_GREEN); DrawText(" HIT! AIRCRAFT ",cursor.X,cursor.Y, FOREGROUND_INTENSITY|FOREGROUND_GREEN); DrawText("CARRIER ",cursor.X,cursor.Y+1, FOREGROUND_INTENSITY|FOREGROUND_GREEN); printf("\7\7\7"); Sleep(500); DrawText("",cursor.X,cursor.Y, // to mask out message FOREGROUND_INTENSITY|FOREGROUND_RED); DrawText("",cursor.X,cursor.Y+1, FOREGROUND_INTENSITY|FOREGROUND_RED); gHits.totalHits++; gHits.acHits++; // function to black out each hit on ship drawing sinkingShip(1); if(gHits.acHits == 4) { *pSunk = true; } return 1; break; case 2: // clear truncated sentances DrawText("",cursor.X,cursor.Y, FOREGROUND_INTENSITY|FOREGROUND_GREEN); DrawText("HIT! CRUISER",cursor.X,cursor.Y, FOREGROUND_INTENSITY|FOREGROUND_GREEN); printf("\7\7"); Sleep(500); DrawText("",cursor.X,cursor.Y, FOREGROUND_INTENSITY|FOREGROUND_GREEN); gHits.totalHits++; gHits.cHits++; sinkingShip(2); if(gHits.cHits == 3) { *pSunk = true; } return 2; break; case 3: // clear truncated sentances DrawText("",cursor.X,cursor.Y, FOREGROUND_INTENSITY|FOREGROUND_GREEN); DrawText("HIT! DESTROYER",cursor.X,cursor.Y, FOREGROUND_INTENSITY|FOREGROUND_GREEN); printf("\7"); Sleep(500); DrawText("",cursor.X,cursor.Y, FOREGROUND_INTENSITY|FOREGROUND_RED); gHits.totalHits++; gHits.dHits++; if(gHits.dHits ==2) { *pSunk = true; } sinkingShip(3); return 3; break; case 4: // clear truncated sentances DrawText("",cursor.X,cursor.Y, FOREGROUND_INTENSITY|FOREGROUND_GREEN); DrawText("HIT! SUBMARINE",cursor.X,cursor.Y, FOREGROUND_INTENSITY|FOREGROUND_GREEN); printf("\7"); Sleep(500); DrawText("",cursor.X,cursor.Y, FOREGROUND_INTENSITY|FOREGROUND_GREEN); gHits.totalHits++; gHits.subHits++;{ *pSunk = true; } sinkingShip(4); return 4; break; default: return 0; } }
int searchShipList(Ship check) // pass coords (Ship check) of calling func { Ship* current = gShipNode; check.X-=6; check.X/=3; // Ignore Margins check.Y-=8; check.Y/=2; int Length; while ( current != NULL ) { Length = 4 - current->ShipType; // Check Intersections - Much easier though b/c only point if(current->direction == 1) // horzontal { if(check.Y == current->Y) { if(check.X >= current->X && check.X<=current->X+Length) { return current->ShipType; } } } else // directinal { if(current->X == check.X) { if(check.Y >= current->Y && check.Y<=current->Y+Length) { return current->ShipType; } } } current = current->next; } return 0; }
void showCursor() { _CONSOLE_CURSOR_INFO hideCursor; hideCursor.bVisible = 1; // if false,not visible hideCursor.dwSize = 20; // needs a size - % of normal _CONSOLE_CURSOR_INFO* cursorPtr; cursorPtr = &hideCursor; SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), cursorPtr); }
void hideCursor() { _CONSOLE_CURSOR_INFO hideCursor; hideCursor.bVisible = 0; // if false,not visible hideCursor.dwSize = 100; // needs a size - % of normal _CONSOLE_CURSOR_INFO* cursorPtr; cursorPtr = &hideCursor; SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), cursorPtr); }
void setScreenSize() { COORD size; // COORD defined in wincon.h size.X = 80; size.Y = 25; SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), size); }
void menu() { char choice; int valid = 0; do { choice = getch(); choice = toupper(choice); switch(choice) { // P. I , H all need sparate function to proceed case 'P': // play valid = 1; letsPlay(); break; case 'I': // instructions valid = 1; instructions(); break; case 'H': // hi scores valid = 1; highScores(); break; case 'Q': exit(0); // exit program break; default: //puts("Please try again"); valid = 0; } } while (valid != 1); }
void instructions() { clearscreen(); puts("HOW TO PLAY"); puts("-----------"); puts("Four ships are hidden within the grid.\n"); puts("Aircraft carrier: four cells long"); puts("Cruiser: three cells long"); puts("Destroyer: two cells long"); puts("Submarine: one cell long.\n"); puts("The ships may be horizontal or vertical."); puts("Press one of the matching alphabet keys to select your target."); puts("Once all the ships are hit then the game is over."); puts("You only get 20 shots and you lose if you run"); puts("out of ammo before sinking all ships."); drawShips(); puts("Press to continue"); getch(); clearscreen(); drawIntro(); drawShips(); menu(); }
void highScores() { clearscreen(); HISCORE HiScore[NUMHISCORES]; FILE *fptr; int i; char choice = 'Q'; // initialise array for (i = 0; i < NUMHISCORES; i++) { *(HiScore[i].name) = NULL; HiScore[i].points = 0; } if ( (fptr = fopen( "hiscores.txt", "r" )) != NULL ) { fread(&HiScore;, sizeof( HiScore ), NUMHISCORES, fptr ); fclose(fptr); } else { puts("No high scores yet"); } puts(" \n\n********************************** HIGH SCORES *********************************"); puts("\n\n"); if (HiScore[0].points == 0) { puts("No high scores yet"); } for (i = 0; i < NUMHISCORES; i++) { printf("\t\t\t\t%-15s\t%d\n",HiScore[i].name, HiScore[i].points); // -15s makes field width 15 left align(-) } puts("\n\n\tPress Q to clear list, anything else to go to menu."); choice = getch(); choice = toupper(choice); // clear hi scores if ( choice == 'Q') { puts("\tSure? (Y)es / (N)o"); choice = getch(); choice = toupper(choice); if (choice == 'Y') { for (i = 0; i < NUMHISCORES; i++) { *(HiScore[i].name) = NULL; HiScore[i].points = 0; } fptr = fopen("hiscores.txt","w"); fwrite(&HiScore;,sizeof(HISCORE),NUMHISCORES,fptr); fclose(fptr); } } clearscreen(); drawIntro(); drawShips(); menu(); }
void letsPlay() { clearscreen(); drawGrid(); gShipNode = drawAllShips(); // sets up linked list of Ship structures drawShips(); int nAttempts = 0; // --- returns ptr to list int *pAttempts = &nAttempts; COORD cursor; cursor.X = 5 ; cursor.Y = 4; bool flag = true; char choice; char string[12]; int count =0; int k; DrawText(" Select a cell ",CELLDETAILS); while(gHits.totalHits !=10 && nAttempts < 20) { choice = getch(); choice = toupper(choice); // check if pressed already if (count != 0) // not first key press { for (k = 0; k < NUMCELLS; k++) { if (gMaxAttempts[k] == choice) { cursor.X = 5 ; cursor.Y = 19; DrawText(" ",cursor.X ,cursor.Y, BACKGROUND_BLUE & BACKGROUND_GREEN &BACKGROUND;_RED); DrawText("Already tried!",CELLDETAILS); Sleep(700); DrawText("",cursor.X,cursor.Y, FOREGROUND_INTENSITY|FOREGROUND_RED); flag = false; break; } } } cursor.X = 5 ; cursor.Y = 5; sprintf(string,"%c",choice); DrawText(" You chose ",CELLDETAILS); cursor.X = 16; strcat(string," "); DrawText(string,CELLDETAILS); if (flag == true) // first attempt at letter { assignToGrid(choice,pAttempts); } count++; flag = true; } cursor.X = 5; cursor.Y = 19; DrawText("",cursor.X,cursor.Y, FOREGROUND_INTENSITY|FOREGROUND_RED); if(gHits.totalHits==NUMSHIPCELLS) { if(nAttempts <=MAXATTEMPTS) { DrawText("ALL SHIPS SUNK",cursor.X,cursor.Y, FOREGROUND_INTENSITY|FOREGROUND_RED); } } cursor.X = 35 ; cursor.Y = 4; if (nAttempts >MAXATTEMPTS+1) { if(gHits.totalHits != NUMSHIPCELLS) { DrawText("YOU LOSE! PRESS ANY KEY for MENU",CELLDETAILS); } else { DrawText("YOU WIN!",CELLDETAILS); doHiScore(nAttempts);} } else { DrawText("YOU WIN!",CELLDETAILS); doHiScore(nAttempts);} getch(); resetGlobals(); clearscreen(); drawIntro(); drawShips(); menu(); }
// link list stuff void push(Ship** headPtr, int x,int y, int direction, int ShipType) { Ship* newnode = (Ship*)malloc(sizeof(Ship)); newnode->X = x; newnode->Y = y; newnode->direction = direction; newnode->ShipType = ShipType; newnode->next = *headPtr; *headPtr = newnode; }
// collision detection to avoid ships ov // erlapping bool Intersect(int sx,int sy,int sd,int sl,int dx,int dy,int dd,int dl) { if(sd == 1) // Facing Horzontally { if(dd==1) // dest facing horz { // if both horzontal, collision can only occur if in same row if(sy != dy){return false;} if(dx > sx+sl || dx+dl < sx){return false;} return true; } else // dest vertical { if(dy+dl < sy || dy > sy){return false;} if(dx < sx || dx > sx+sl){return false;} return true; } } else // Facing Vertically { if(dd==1) // dest facing horz { if(sy+sl < dy || sy > dy){return false;} if(sx < dx || sx > dx+dl){return false;} return true; } else { if(sx != dx){return false;} if(dy > sy+sl || dy+dl < sy){return false;} return true; } } return false; }
Ship* drawAllShips() { srand( unsigned (time(NULL)) ); // Set Random Seed Once SHIP* head = NULL; COORD cell; int Direction; int ShipType=1; bool collision = false; while(true) // Loop for Infinity Till Everything slots in { cell.X = rand()%5; // gives in range 0 - 4 (ignore cell margins at this stage) cell.Y = rand()%5; Direction = (rand()%2) + 1; // Check It Doesn't Go Off Map if(Direction == 1){if( (cell.X + (4 - ShipType)) > 4){continue;}} else{if(cell.Y + (4 - ShipType) > 4){continue;}} // Loop Through List Checking for Collsion collision = false; for(SHIP* it=head;it!=NULL;it=it->next) { int dstLength = 5 - ShipType; int srcLength = 5 - it->ShipType; if(Intersect(it->X,it->Y,it->direction,srcLength,cell.X,cell.Y,Direction,dstLength)) { collision = true; break; } } if(!collision) { push(&head;,cell.X,cell.Y,Direction,ShipType); ShipType++; if(ShipType == 5){break;} } } return head; }
void sinkingShip(int ShipType) { COORD sinkingShip; unsigned long y; unsigned long *ptr; ptr = &y; switch(ShipType) { case 1: y = gHits.acHits; sinkingShip.X = 42; sinkingShip.Y = 15; FillConsoleOutputAttribute(GetStdHandle(STD_OUTPUT_HANDLE), BACKGROUND_INTENSITY | BACKGROUND_GREEN & BACKGROUND_BLUE & BACKGROUND_RED ,y,sinkingShip,ptr); break; case 2: y = gHits.cHits; sinkingShip.X = 42; sinkingShip.Y = 17; FillConsoleOutputAttribute(GetStdHandle(STD_OUTPUT_HANDLE), BACKGROUND_INTENSITY | BACKGROUND_GREEN & BACKGROUND_BLUE & BACKGROUND_RED ,y,sinkingShip,ptr); break; case 3: y = gHits.dHits; sinkingShip.X = 42; sinkingShip.Y = 19; FillConsoleOutputAttribute(GetStdHandle(STD_OUTPUT_HANDLE), BACKGROUND_INTENSITY | BACKGROUND_GREEN & BACKGROUND_BLUE & BACKGROUND_RED ,y,sinkingShip,ptr); break; case 4: y = gHits.subHits; sinkingShip.X = 42; sinkingShip.Y = 21; FillConsoleOutputAttribute(GetStdHandle(STD_OUTPUT_HANDLE), BACKGROUND_INTENSITY | BACKGROUND_GREEN & BACKGROUND_BLUE & BACKGROUND_RED ,y,sinkingShip,ptr); break; } }
void resetGlobals() { // reset global for next game int k; for (k = 0; k < NUMCELLS; k++) { gMaxAttempts[k] = 0; } gHits.totalHits = 0; gHits.acHits = 0; gHits.cHits = 0; gHits.dHits = 0; gHits.subHits = 0; }
void doHiScore(int nAttempts) { COORD cursor; cursor.X = 35 ; cursor.Y = 8; char buffer[3]; HISCORE HiScore[10]; FILE *fptr; char name[10]; int i, scoreToBeat; char ch; // initialise array for (i = 0; i < NAMELENGTH; i++) { *(HiScore[i].name) = NULL; HiScore[i].points = 0; } if ( (fptr = fopen( "hiscores.txt", "r" )) != NULL ) { fread(&HiScore;, sizeof( HiScore ), NAMELENGTH, fptr ); fclose(fptr); } else { puts("No high scores yet"); } sortScores(HiScore); // previous hi scores on file scoreToBeat = (21 - nAttempts)*10; // max poss score is 100 ie no misses itoa(scoreToBeat,buffer,10); DrawText("YOUR SCORE IS: ",CELLDETAILS); cursor.X = 50; DrawText(buffer,CELLDETAILS); // if new hi score if (scoreToBeat > HiScore[NAMELENGTH-1].points) // add new hi score at end - will need sorting { cursor.X = 35 ; cursor.Y = 2; DrawText("NEW HIGH SCORE! ",CELLDETAILS); HiScore[9].points = scoreToBeat; cursor.X = 35; cursor.Y = 3; DrawText("Enter name:",CELLDETAILS); cursor.X = 48; cursor.Y = 3; SETCURSOR // sets cursor for entering name // limit name to 10 chars for( i = 0; (i < 10) && ((ch = getchar()) != EOF) && (ch != '\n'); i++ ) { name[i] = ch; } name[i] = '\0'; flushall(); // flushes all buffers - keyboard buffer will hold chars // if name > 10 then use in next hiscore otherwise - definitely works strcpy(HiScore[NAMELENGTH-1].name,name); sortScores(HiScore); clearscreen(); puts(" \n\n********************************** HIGH SCORES *********************************"); puts("\n\n"); for (i = 0; i < NUMHISCORES; i++) { printf("\t\t\t\t%-15s\t%d\n",HiScore[i].name, HiScore[i].points); } fptr = fopen("hiscores.txt","w"); if (fptr == (FILE*)NULL) { printf("Error = no file\n"); return; } fwrite(&HiScore;,sizeof(HISCORE),NUMHISCORES,fptr); fclose(fptr); } cursor.X = 30; cursor.Y = 23; DrawText("PRESS ANY KEY for MENU",CELLDETAILS); }
void sortScores(HISCORE* HiScore) { int i; HISCORE temp[NUMHISCORES]; int status = UNSORTED; while( status == UNSORTED) { status = SORTED; // now show it isn't for(i = 0; i < NUMHISCORES - 1; i++) { if (HiScore[i].points < HiScore[i+1].points ) { strcpy(temp[i].name, HiScore[i].name); temp[i].points = HiScore[i].points; strcpy(HiScore[i].name, HiScore[i+1].name); HiScore[i].points = HiScore[i+1].points; strcpy( HiScore[i+1].name, temp[i].name); HiScore[i+1].points = temp[i].points; status = UNSORTED; } } } }
int gMaxAttempts[25]; // max number of attempts gHITS gHits; // struct of hits for all ships Ship* gShipNode; // global ptr to linked list of ships void main() { char* title = "Battleships"; setScreenSize(); displayProgramStart(title); drawIntro(); drawShips(); menu(); }

 
Report Bad Submission
Use this form to notify us if this entry should be deleted (i.e contains no code, is a virus, etc.).
Reason:
 
Your Vote!

What do you think of this code(in the Beginner category)?
(The code with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor See Voting Log
 
Other User Comments

 There are no comments on this submission.
 
Add Your Feedback!
Note:Not only will your feedback be posted, but an email will be sent to the code's author in your name.

NOTICE: The author of this code has been kind enough to share it with you.  If you have a criticism, please state it politely or it will be deleted.

For feedback not related to this particular code, please click here.
 
Name:
Comment:

 

Categories | Articles and Tutorials | Advanced Search | Recommended Reading | Upload | Newest Code | Code of the Month | Code of the Day | All Time Hall of Fame | Coding Contest | Search for a job | Post a Job | Ask a Pro Discussion Forum | Live Chat | Feedback | Customize | C/ C++ Home | Site Home | Other Sites | About the Site | Feedback | Link to the Site | Awards | Advertising | Privacy

Copyright© 1997 by Exhedra Solutions, Inc. All Rights Reserved.  By using this site you agree to its Terms and Conditions.  Planet Source Code (tm) and the phrase "Dream It. Code It" (tm) are trademarks of Exhedra Solutions, Inc.