Results 1 to 5 of 5
  1. #1
    Join Date
    Aug 2008
    Posts
    54

    Newbish having trouble Creating battleships in console

    I have just started to try create from what I have learned from books and Uni, I have been on and off with C# for about a year as maya and 3D apps are my 1st love. But I am trying though:)

    But anyway these are the prblems I am having?

    1. for some reason my grid is missing a row/col which is why some of my ships are not being displayed not sure what to do as I have tried but...knowing me it is most probably something really simple??

    2.I am also having problems validating a direct hit of a ship,not quite sure what I need to do next....most my code makes sense have a look to see what you think :)

    Anyhelp would be greatful

    UPDATE

    Just an update- While the responses was awfully silent on my topic manage to fulfill my answers by digging really deep in text book and a little guidance from another board , just wanted to show what I have so far on my battleship game in c-sharp, i know it is very simple but it is the best I could do with what knowledge I have obtained so far, the only snag it crashes when i enter a string anybody got any advice or guidance on this ??? I have tried sometime of vildation in the validate input method but to no joy :(


    J.T.

    Code:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    
    namespace Jasons_BattleShip_game1 //Jason,s attempt at a Battleship game :).
    {
        class Program
        {
    
    
            enum SeaState // decides on the various types of the board state.
            {
    
                Battleship,
                Cruiser,
                Submarine,
                RowingBoat,
                EmptySea,
                Attack,
                Miss
            };
            const int SEA_WIDTH_X = 11;// Sets board height and width to the required size 
            const int SEA_HEIGHT_Y = 11;
            static int numberOfHits = 0;
            static int numberOfShips = 7;
            static int compHits = 0;
            static bool GameOver = false;
            static int compX = 0;
            static int compY = 0;
            static SeaState[,] sea = new SeaState[SEA_HEIGHT_Y, SEA_WIDTH_X];
    
    
            static void ClearSea()//Sets all spaces on board to hidden.
            {
                for (int ROW = 0; ROW < SEA_HEIGHT_Y; ROW = ROW + 1)
                {
                    for (int COL = 0; COL < SEA_WIDTH_X; COL = COL + 1)
                    {
                        sea[ROW, COL] = SeaState.EmptySea;
                    }
                }
            }
            static void PlaceShips() //Set co-ordinates for Ships.
            {
                sea[0, 5] = SeaState.Battleship;
                sea[2, 7] = SeaState.Battleship;
                sea[0, 0] = SeaState.Cruiser;
                sea[2, 0] = SeaState.Cruiser;
                sea[4, 3] = SeaState.Cruiser;
                sea[5, 6] = SeaState.Submarine;
                sea[8, 8] = SeaState.RowingBoat;
    
            }
            static int ValidateInput()
            {
    
                bool Valid = false;
                int num = 0;
                while (!Valid)
                {
                    Valid = int.TryParse(Console.ReadLine(), out num);
                    Console.WriteLine("invalid coordinate...pls select between [0-9]");
                }
                return num;
            }
            static void displaySea() //This will display the board,and will also change the colour of the board being displayed.
            {
    
                {
                    Console.WriteLine("\n");
                    Console.WriteLine("<<<<<<Welcome To BattleShips>>>>>>");// Game tiltle
                    Console.WriteLine("\n");
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Why Not Expand Your Console Window?");
                    Console.WriteLine("\n");
                    Console.WriteLine("Let Battle Commence!");
                    Console.WriteLine("\n");
                    Console.ForegroundColor = ConsoleColor.White;
                    Console.WriteLine("0 : Empty Space");
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("1 : Attack");
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("2 : Miss");
                    Console.WriteLine("\n");
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.Write(" 0");
    
    
                    for (int COL = 0; COL < SEA_WIDTH_X; COL = COL + 1)
                    {
                        Console.ForegroundColor = ConsoleColor.Yellow;
                        Console.Write("{0,2}", COL);
                        Console.ForegroundColor = ConsoleColor.White;
                    }
                }
    
                Console.WriteLine("\n");
                for (int ROW = 0; ROW < SEA_HEIGHT_Y; ROW = ROW + 1)
                {
                    for (int COL = 0; COL < SEA_WIDTH_X; COL = COL + 1)
                    {
                        if (COL == 0)
                        {
                            Console.ForegroundColor = ConsoleColor.Yellow;
                            Console.Write("{0,2}", ROW);
                            Console.ForegroundColor = ConsoleColor.White;
                        }
    
                        {
                            SeaState seastate = sea[ROW, COL];// This will display the board evenly
                            switch (seastate)
                            {
                                case SeaState.EmptySea:
                                    Console.ForegroundColor = ConsoleColor.White;
                                    Console.Write("{0,2}", "0");
                                    break;
                                case SeaState.Attack:
                                    Console.ForegroundColor = ConsoleColor.Red;
                                    Console.Write("{0,2}", "1");
                                    break;
                                case SeaState.Miss:
                                    Console.ForegroundColor = ConsoleColor.Green;
                                    Console.Write("{0,2}", "2");
                                    break;
                                case SeaState.Battleship:
                                    Console.ForegroundColor = ConsoleColor.White;
                                    Console.Write("{0,2}", "0");
                                    break;
                                case SeaState.Cruiser:
                                    Console.ForegroundColor = ConsoleColor.White;
                                    Console.Write("{0,2}", "0");
                                    break;
                                case SeaState.Submarine:
                                    Console.ForegroundColor = ConsoleColor.White;
                                    Console.Write("{0,2}", "0");
                                    break;
                                case SeaState.RowingBoat:
                                    Console.ForegroundColor = ConsoleColor.White;
                                    Console.Write("{0,2}", "0");
                                    break;
                                default:
                                    break;
                            }
    
                        }
    
                    }
                    Console.WriteLine("\n");
                }
            }
    
            static void getPlayerMove()// This will let the player decide were he wants to move using the x,y co-ordinate and then let them decide if there is a Enemy Ship there.
            {
                int xCoOrdinate;
                int yCoOrdinate;
                bool invalid = false;
                
                do
                {
                    Console.WriteLine(" Please Select x co-ordinate");// Selection of the x coordinate
                    xCoOrdinate = int.Parse(Console.ReadLine());
                    Console.WriteLine("Please Select y co-ordinate"); //Selection of the y coordinate
                    yCoOrdinate = int.Parse(Console.ReadLine());
    
                    if (yCoOrdinate < 0 || xCoOrdinate < 0 || yCoOrdinate >= SEA_HEIGHT_Y || xCoOrdinate >= SEA_WIDTH_X)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("InvalidInput - Please try again");
                        invalid = true;
                    }
                    else
                    {
                        invalid = false;
                    }
                }
                while(invalid == true);
    
                if (sea[yCoOrdinate, xCoOrdinate] == SeaState.EmptySea)
                {
                    Console.WriteLine("You Missed!");
                    sea[yCoOrdinate, xCoOrdinate] = SeaState.Miss; // Declares A miss
                }
                else if (sea[yCoOrdinate, xCoOrdinate] == SeaState.Attack || sea[yCoOrdinate, xCoOrdinate] == SeaState.EmptySea)
                {
                    Console.WriteLine("Shot Wasted"); // Declares A Wasted Shot
                }
                else
                {
                    Console.WriteLine("HIT!"); // Declares A Hit 
                    sea[yCoOrdinate, xCoOrdinate] = SeaState.Attack;
                    numberOfHits++;
                    if (numberOfHits == numberOfShips)
                    {
                        GameOver = true;
    
                    }
                }
            }
            static void getComputermove()//This will let the computer/player attack co-ordinates set
            {
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("Computer attacks coordinates: ");
                Console.WriteLine(compX + "," + compY);
                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine("Has the computer hit y/n");
                string yes = Console.ReadLine();
                if (yes == "y")
                {
                    compHits++;// If the computer/player hits the set number of ships the it wins.
                    if (compHits == numberOfShips)
                    {
                        GameOver = true;
                    }
    
                }
                compX++;//Simple A.I. player-the computer will check every square in numerical order row by row
                if (compX == SEA_WIDTH_X)
                {
                    compX = 0;
                    compY++;
                }
       
               
            }
                
    
            static void Main()
            {
                numberOfHits = 0;//sets the number of ships that have been attacked to 0
                GameOver = false;//game continue until game is true
                ClearSea();//call the clearSea method to set all spaces to Empty
                PlaceShips();//places Ships on board
                do
                {
                    displaySea();//display board
                    getPlayerMove();//takes x,y co-ordinates from player to move
                    getComputermove();//takes x,y co-ordinates from comp/player to move
                }
                while (GameOver == false);
                if (numberOfHits == 7)
                {
                    Console.WriteLine("Congratulations you win"); //player wins
                }
                else
                {
                    Console.WriteLine("You have lost the game");//computer wins
                }
                Console.WriteLine("press y if you would like to play again \n or any other key to exit");
                string playAgain = Console.ReadLine();
                if (playAgain.ToUpper() == "Y")
                {
                    Main();
                }
            }
        }
    }
    Last edited by silverspawn; 12-05-2010 at 08:13 AM.

  2. #2
    Join Date
    Aug 2008
    Posts
    54
    Cannot beleive I have not had an inkling of a response not even a coment on my code, as a newbie trying to learn a different language even a different hobby, I thought some of the more experienced board members may have been a little more vocal. Guess I came to the wrong place for advice and guidance.

  3. #3
    Join Date
    Dec 2003
    Location
    3dbuzzmania
    Posts
    4,064
    That is the first time I see this thread, you know people do miss threads. Instead of being all hostile you should simply "Bump" your thread.

    I don't see much wrong with your code, other than it should be a bit more scalable, for example have a config class that sets up the game or even better let the user create the size of the board and number of ships. Also add some random functionality.

    Also in the main method instead put this as first line
    Code:
    Console.SetWindowSize(80,42);
    Instead of asking the user to resize their console window, that is an instant turn off.

    Your validation seems OK, now move that into your validate method instead of putting it all in the Do ... While loop. And lastly please use ROW++ instead of ROW = ROW + 1 that is just plain ugly.

    Nice job so far.

  4. #4
    Join Date
    Jun 2008
    Posts
    1,088
    Sorry for the lack of responses but it could be due to the little knowledge we have of your project. Really hard to determine your issue just from this section of code. Is there any warnings or errors in your compiler? I am assuming your using vs. Have you tried stepping through the code to see what line is the culprit?

    -Dane

  5. #5
    Join Date
    Jun 2005
    Location
    Phoenix, Arizona
    Posts
    2,076
    Quote Originally Posted by silverspawn View Post
    the only snag it crashes when i enter a string anybody got any advice or guidance on this ??? I have tried sometime of vildation in the validate input method but to no joy
    When you say a string do you mean characters other than a number?

    I also don't see where you are calling your ValidateInput method.

    This line int.Parse(Console.ReadLine()); would throw an exception if you pass it a value other than an integer. The Parse and TryParse methods handle parsing a bit differently.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •