Simple Dungeon Crawl

This is my second project using c++, Dungeon Crawl. The aim of the game is to reach the treasure ‘X’ without touching a trap. I have diy-ed the game a little and increased the number of traps with each turn.

Using:

  • variables, data types, and numerical operators
  • basic input/output
  • logic (if statements, switch statements)
  • loops (for, while, do-while)
  • arrays
  • functions

#include <iostream>
#include <string>
//GLOBAL VARIABLES
char board[8][10];
//FUNCTIONS
void buildboard();
void initialize();
int moveplayer(char userinput);
bool checkwin(int row, int col);
void settrap();
bool checklose(int row, int col);
void ClearScreen();
int main()
{
 //INITIALIZE
 char userinput;
 initialize();
 settrap();
 bool stop = false;

 //DO WHILE NO WINNER OR LOSER
 while(stop == false){

 buildboard();
 settrap();

 std::cout << "\n Player move up, down, left, right (w,s,a,d)?\n\n\n\n";
 std:: cout << " ";
 std::cin >> userinput;
 bool quit = false;
 while (!quit){

 switch(userinput){
 case 'w':
 case 's':
 case 'a':
 case 'd':
 quit = true;
 break;
 default:
 std::cout << "\n Invalid move, try again(w,s,a,d)\n";
 std:: cout << " ";
 std::cin >> userinput;
 }
 }

 stop = moveplayer(userinput);
 userinput = '.'; //RESET
 }
}

void initialize()
{
 int col = 0,row = 0;
 //GIVES ALL SPACES NULL VALUE
 for(int i=0; i<8; i++)
 {
 for(int j=0; j<10; j++)
 {
 board[i][j] = '.';
 }
 }

 //TREASURE RANDOM
 while(col+row == 0){
 srand(time(0));
 col = rand() % 10;
 row = rand() % 8;
 board[row][col] = 'X';
 }

 //PLAYER AT 0,0.
 board[0][0] = 'G';

}

void buildboard()
{
 ClearScreen();
 std::cout << "\n DUNGEON CRAWL \n";
 std::cout << "\n Hurry they're multiplying... \n\n";

 for(int row=0; row<8; row++)
 {
 std::cout << "\t ";
 for(int col=0; col<10; col++)
 {
 std::cout << board[row][col];
 }
 std::cout << "\n";
 }
}

int moveplayer(char userinput)
{
 int col,row;
 //need to set m,n to player's position
 for(int i=0; i<10; i++){
 for(int j=0; j<8; j++){
 if(board[j][i] == 'G'){
 col = i;
 row = j;
 break;
 }
 }
 }

 //W UP, S DOWN, A LEFT, D RIGHT;
 //DOES NOT LET PLAYER MOVE OFF BOARD
 board[row][col] = '.';
 if(userinput =='w' && row!=0){
 row--;
 }
 else if(userinput =='s' && row!=7){
 row++;
 }
 else if(userinput =='a' && col!=0){
 col--;
 }
 else if(userinput =='d' && col!=9){
 col++;
 }
 //before reassigning G check for treasure or trap!!******
 //if win
 if (checkwin(row,col) == true){
 std::cout << "\n WINNER!\n\n\n";
 return true;
 }
 //if lose
 else if(checklose(row,col) == true){
 std::cout << "\n Sorry you LOSE!\n\n\n";
 return true;
 }
 else{
 board[row][col] ='G';
 return false;
 }
}

void settrap()
{
 //TRAP RANDOM
 int col, row;
 bool ok = false;
 while(ok == false){
 col = rand() % 10;
 row = rand() % 8;
 if(board[row][col]=='.'){
 board[row][col] = 'T';
 ok=true;
 }
 }
}

bool checkwin(int row, int col)
{
 //IF PLAYER G FINDS TREASURE X
 if(board[row][col] == 'X'){
 return true;
 buildboard();
 }
 else
 {
 return false;
 }
}
bool checklose(int row, int col)
{
 //IF PLAYER G FINDS TRAP
 if(board[row][col] == 'T'){
 return true;
 buildboard();
 }
 else
 {
 return false;
 }
}
void ClearScreen()
{
 std::cout << std::string( 100, '\n' );
}

Tic Tac Toe

Using:

  • variables, data types, and numerical operators
  • basic input/output
  • logic (if statements, switch statements)
  • loops (for, while, do-while)
  • arrays
  • functions

This is an example source code for Tic Tac Toe against a smart computer player. This took about a week to make in total. I had help from forums on cplusplus.com. Free to copy.


#include <iostream>
#include <vector>

using namespace std;

char square[10] = {'o', '1', '2', '3', '4', '5', '6', '7', '8', '9'};

void board();
int checkwin();
int cppmove();
int cppmovesmart();

int main()
{
 int win = 0;
 int tries = 0;
 int userinput;
 int player = 1;

 while (win == 0 && tries < 9)
 {
 board();

 if(player == 1){
 cout << "\tPlayer " << player << " choose a number: ";
 cin >> userinput;
 }
 else
 {
 userinput = cppmovesmart();
 cout << "\tPlayer cpp chooses number " << userinput << "...\n\n";
 system("PAUSE");
 }




 //Invalid move, doesn't use up tries.
 if(square[userinput] == 'X' || square[userinput] == '0')
 {
 cout << "INVALID MOVE";
 }
 else
 {
 square[userinput] = (player ==1) ? 'X' : 'O';

 //Check win
 win = checkwin();

 //Change player
 player = (player == 1) ? 2 : 1;

 //Add 1 to tries
 tries++;
 }
 }
 //Undo the changed player to output winner.
 player = (player == 1) ? 2 : 1;

 //Output result.
 if(win == 1){
 board();
 cout << "\n\n\tPlayer " << player << " WINS!!!\n\n";
 }
 else{
 cout << "\n\n\tDRAW\n\n";
 }
}
/* ########################################FUNCTIONS###############################################
###################################################################################################*/

//COMPUTER MOVIES SMART
int cppmovesmart()
{
 int s;

 if(square[1] == '1' && (square[2] == square[3] || square [4] == square[7] || square[5] == square[9]))
 {

 s = 1;
 }
 else if(square[2] == '2' && (square[1] == square[3] || square [5] == square[8]))
 {
 s = 2;
 }
 else if(square[3] == '3' && (square[1] == square[2] || square [6] == square[9] || square [5] == square[7]))
 {
 s = 3;
 }
 else if(square[4] == '4' && (square[5] == square[6] || square [1] == square[7]))
 {
 s = 4;
 }
 else if(square[5] == '5' && (square[4] == square[6] || square [2] == square[8] || square [1] == square[9] || square[7] == square[3]))
 {
 s = 5;
 }
 else if(square[6] == '6' && (square[4] == square[5] || square [3] == square[9]))
 {
 s = 6;
 }
 else if(square[7] == '7' && (square[8] == square[9] || square [1] == square[4] || square [5] == square[3]))
 {
 s = 7;
 }
 else if(square[8] == '8' && (square[7] == square[9] || square [2] == square[5]))
 {
 s = 8;
 }
 else if(square[9] == '9' && (square[7] == square[8] || square [3] == square[6] || square [1] == square[5]))
 {
 s = 9;
 }
 else
 {
 s = cppmove();
 }
 return s;
}

//COMPUTER MOVES RANDOMLY
int cppmove()
{
 int r;
 vector<int> newvector(0);

 for(int i=1; i<10; i++)
 {
 if(square[i] != 'X' && square[i] != 'O')
 {
 newvector.push_back(i);
 }
 }

 srand(time(0));
 r = newvector.at(rand() % newvector.size());

 return r;
}

&nbsp;

//BUILD BOARD
void board()
{
 system("cls"); //Clears screen.
 cout << "\n\n\tTic Tac Toe\n\n";

 //builds a 3*3 board with numbers 123,456,789.
 for (int i = 1; i < 10; i = i + 3)
 {
 cout << "\t" << square[i] << " " << square[i+1] << " " << square[i+2] << endl << endl;
 }
}

int checkwin()
{
 int win = 0;

 //Horizontal Lines
 for (int i = 1; i < 10; i = i + 3)
 {
 if(square[i] == square[i+1] && square[i+1] == square[i+2])
 {
 win = 1;
 }
 }
 //Vertical Lines
 for (int i=1; i<4; i++){
 if(square[i] == square[i+3] && square[i] == square[i+6]){
 win = 1;
 }
 }
 //Diagonal Lines
 if((square[1] == square[5] && square[1] == square[9])||
 (square[3] == square[5] && square[3] == square[7])){
 win = 1;
 }
 //Return 1 if win, else return 0.
 if(win == 1){
 return 1;
 }
 else{
 return 0;
 }
}

Insertion Sort

Insertion Sort is more efficient than the simple Bubble sort.

It begins by only comparing the first element, and the one to it’s right. If the one on it’s right is smaller, they swap. Step 2, compares the second element and the one on it’s right. If the element on it’s right is smaller, it swaps; and does step 1 again. However, if the second element and it’s right hand side partner don’t swap, step 2 finishes. Step 3 compares the third element and the one of it’s right…. etc. Unless the list is in complete reverse order, it will make less comparisons than the Bubble sort.

It’s better with a picture.

Example of the insertion sort.

Example of the insertion sort.

Here’s an example in code:


#include <iostream>
void InsertionSort(int a[], int length)
{
 for (int i=0; i<length - 1; i++)
 {
 int j = i;
 while (j>=0 && a[j]>a[j+1])
 {
 int temp = a[j];
 a[j] = a[j+1];
 a[j+1] = temp;
 j= j-1;
 }
 }
}

int main(){

int a[] = {8,5,7,6,2,3};
 int size = sizeof(a) / sizeof(*a);
 InsertionSort(a, size);

 for (int i=0; i<size; i++)
 {
 std::cout << a[i];
 }

}

 

While User Guilible

This is another simple project using while loops and if statements.

The program continues to ask the user to input a number other than the number equal to the number of tries they’re had. If the user does, they lose. If they are patient for ten tries, they win.


#include <iostream>

using namespace std;

int main() {
 int i = 0;
 int x;

while (i<10 && x!=i-1){
 cout << "Please enter a number!\nAny number...\nNOT "<< i << "!!!\n";
 cin >> x;
 i += 1;
 }

 if (i==10){
 cout << "Wow, you're more patient then I am, you win.";
 }
 else{
 cout << "Hey! you weren't supposed to enter " << i-1 << "!";
 }


 }

Pancake Glutton

This is a simple project that uses logic (if statements) and loops (for).

The user inputs the number of pancakes ten people have eaten. It sorts the list and outputs in order.

#include <iostream>

using namespace std;

int main() {
 int numberOfPancakes[10];

 int person[10] = {1,2,3,4,5,6,7,8,9,10};
 int minPancakes = 100000;

 cout << "How many pancakes did you eat this morning?\n";

 //iterates from 0-9
 for (int i=0; i<10; i++){

 cout << "Person " << i+1 << "?";
 cin >> numberOfPancakes[i];

 }

 //SORTING USING BUBBLE SORT
 for (int i=0; i<10; i++){
 for(int j=0; j<9; j++){
 if(numberOfPancakes[j]>numberOfPancakes[j+1]){

 int temp = numberOfPancakes[j+1];
 int temp2 = person[j+1];

 numberOfPancakes[j+1] = numberOfPancakes[j];
 person[j+1] = person[j];

 numberOfPancakes[j] = temp;
 person[j] = temp2;
 }
 }
 }

 for(int i=0; i<10; i++){
 cout << "Person " << person[i];
 cout << " ate " << numberOfPancakes[i] << " pancakes." << endl;
 }

}

Bubble Sort Algorithm

After first sort. The highest number has bubbled to the end of the array.

After first sort. The highest number has bubbled to the end of the array.

The Bubble Sort arranges the numbers in ascending order. To do this first it compares the first element with the element on it’s right; if the first element is larger; the two elements swap. It then moves onto the second element and repeats the comparing process. It continues this until the (n-1)th element; by this time, the largest number should be in the nth element. The largest number bubbles to the top! See Image above for a more visual explanation.

Now the largest number is in the nth element, we can say it has been sorted. Now we have a slightly smaller array to sort.

The second sort begins with the first element, compares, swaps if necessary, up to the (n-2)th element. It doesn’t need to check the last element because it’s already sorted. The third sort begins with the first element, compare, swaps if necessary, up to the (n-3)th element. The fourth, fifth, sixth sort continue in the same way until the array is sorted.

The total number of comparisons is equal to n(n-1)/2. This can be simplified to n^2/2 – n/2, where n^2 dominates. The bubble sort is simple and effective for small arrays, but this is a very long process as n increases.

Here’s an example of using it in a program:

</pre>
int main(){

 //Array I want to sort.
 int a[7] = {1,5,9,6,2,3,8};

 //Finding size of array
 int s = sizeof(a)/sizeof(*a);

 //Bubble Sort
 for (int i=0; i<s; i++)
 {
 for (int j=0; j<s-1; j++)
 {
 if (a[j]>a[j+1])
 {
 int temp = a[j+1];
 a[j+1] = a[j];
 a[j] = temp;
 }
 }
 }
 for (int i=0; i<s; i++){
 cout << a[i];
 }
}
<pre>

Strings

A String is an array of characters; like a word or a sentence.

Here’s an example:


#include <iostream>

using namespace std;

int main()
{
 //Declare string size 100.
 char string[100];

 //Prompt user to input a word.
 cout << "Please enter a word." << endl;

 //Reads input, store in string, \n waits for user to push enter.
 cin.getline(string, 100, '\n');

 //Outputs first character in string.
 cout << "Your word started with a: " << string[0] << endl;
 cin.get();
}

Arrays

I just finished a course in Python which I used lists for everything. So I couldn’t wait to learn arrays.

But C++ does not make it easy… where’s my .sort function?

An Array is a list of elements, each with it’s own index; kind of like a set of shelves.

Here’s a simple example:


#include <iostream>

 using namespace std;
 int main()
{
 //DECLARED A NEW ARRAY, TYPE INT, SIZE 8.
 int array[8];

 //ASSIGNING VALUES 0-7 TO MY EIGHT ELEMENTS
 for(int x=0; x<8; X++)
 cin>> ;

 //OUTPUT ARRAY TO SCREEN ONE ELEMENT AT A TIME
 for(int x = 0; x<8; x++)
 cout<<array[x];

 return 1;
}

Note: I have only used type int here, and I can use other numerical types easily. I will write another post on using characters to make words. For now, I don’t need them.

Note II: Next post, how to sort!

Note III: Just for fun, here’s a 2D array.


//DECLARING A 2D ARRAY

int twodimensionalarray[8][8];

//HOW TO ACCESS EACH ELEMENT

twodimensionalarray[arrayindexnumber1][arrayindexnumber2] = someInt;

Switch Case

At university I was lazy when it came to programming, and relied on IFs, FORs and WHILEs, and didn’t get much further.

Here’s a switch statement. It’s kind of like a IF statement.


int a;

int b;

int c;

switch (a) {

case b:

//code

break;

case c:

//code

break;

default:

//code

break;

}

A quick explanation:

If a is equal to Case b do the code, etc. The breaks are there to exit the loop, otherwise the program will fall to the next one, and eventually output the default too. The default is like else.

A good example of using the Switch Case is a cola machine; the user has to input the number assigned to the drink.


#include <iostream>

using namespace std;

int main()
{
 int input;

 cout<<"1 Coke\n";
 cout<<"2 Water\n";
 cout<<"3 Sprite\n";
 cout<<"4 Fanta\n";
 cout<<"5 Pocari Sweat\n";
 cin>> input;
 switch (input) {
 case 1:
 cout<<"Your Coke is ready!";
 break;
 case 2:
 cout<<"Your Water is ready!";
 break;
 case 3:
 cout<<"Your Sprite is ready!";
 break;
 case 4:
 cout<<"Your Fanta is ready!";
 break;
 case 5:
 cout<<"Your Pocari Sweat is ready!";
 break;
 default:
 cout <<"Error. choice was not valid, here is your money back.\n";
 break;
 }
 cin.get();

}