I am building an ascii version of TicTacToe as a class asigment and I ran into a problem.The cursor doverwrites the board and the signs.
while (pressed == false)
{
ConsoleKeyInfo cki;
cki = Console.ReadKey();
switch (cki.Key)
{
case ConsoleKey.RightArrow:
if(sides+1>Console.WindowWidth)
break;
if(sides+1==17||sides+1==8)
sides+=2;
else
sides += 1;
Console.SetCursorPosition(sides, ver);
break;
case ConsoleKey.LeftArrow:
if (sides - 1 < 0)
break;
if (sides -1 == 17 || sides -1 == 8)
sides -= 2;
else
sides -= 1;
Console.SetCursorPosition(sides, ver);
break;
case ConsoleKey.DownArrow:
if (ver + 1 > Console.WindowHeight)
break;
if (ver+1==8||ver+1==17)
ver += 2;
else
ver += 1;
Console.SetCursorPosition(sides, ver);
break;
case ConsoleKey.UpArrow:
if (ver - 1 < 0 )
break;
if (ver - 1 == 8 || ver - 1 == 17)
ver-=2;
else
ver -= 1;
Console.SetCursorPosition(sides, ver);
break;
case ConsoleKey.X:
case ConsoleKey.O:
br.PutSign(ver,sides,ch);
pressed = true;
break;
default:
break;
}
}
}
I fixed the problme that the cursor overwrites the board But I still cant find a way to protect the sings(the X and the O)
Thats the board class for refernce:
public char[,] board = new char[27, 27];
public Board()
{
for (int i = 0; i < board.GetLength(0); i++)
{
for (int j = 0; j < board.GetLength(1); j++)
{
if (i==8||i==17)
board[i, j] = '_';
if (j==8||j==17)
board[i, j] = '|';
}
}
}
public void PrintB()
{
for (int i = 0; i < board.GetLength(0); i++)
{
for (int j = 0; j < board.GetLength(1); j++)
{
Console.Write(board[i, j]);
}
Console.WriteLine("");
}
}
public void PutSign(int row, int col, char ch)
{
board[row, col] = ch;
}
Related
I am trying to program a game called NIM (https://plus.maths.org/content/play-win-nim). The subroutine 'ComputerMove();' does not execute for some reason, why is that? I am yet to finish but it is the ComputerMove subroutine that I am confused with. Apologies in advance if I am missing something obvious.
(Edit: There is no error message, just a blank console)
using System;
using System.Threading;
namespace THE_NIM
{
class Program
{
static char[,] Board = new char[7, 12];
static string underline = "\x1B[4m";
static string reset = "\x1B[0m";
static bool GameStatus = false;
static string firstMove;
static void Introduction()
{
Console.WriteLine("\t\t\t\t\t" + underline + "Welcome to NIM!\n" + reset);
Thread.Sleep(1000);
Console.WriteLine(underline + "The rules are as follows:\n" + reset);
Thread.Sleep(1000);
Console.WriteLine(" - Each player takes their turn to remove a certain number of 'blocks' from a stack, of which there are 7.");
Console.WriteLine(" - This happens until there is only 1 'block' remaining. With the winner being the one to remove the last 'block'.\n");
Thread.Sleep(1500);
}
static void PrintBoard()
{
Console.WriteLine();
Console.WriteLine();
for (int i = 0; i <= 6; i++)
{
Console.Write(" ");
for (int j = 0; j <= 11; j++)
{
Console.Write(Board[i, j]);
}
Console.WriteLine();
Console.WriteLine();
}
}
static void WhoGoesFirst()
{
string[] PossibleChoices = { "Computer", "You" };
Random WhoGoesFirst = new Random();
int WGFIndex = WhoGoesFirst.Next(0, 2);
firstMove = PossibleChoices[WGFIndex];
Console.WriteLine("Randomly selecting who goes first...");
Thread.Sleep(1000);
Console.WriteLine("{0} will go first!\n", firstMove);
Thread.Sleep(1000);
}
static void PlayerMove()
{
Console.Write("Which stack do you wish to remove from?: ");
int PlayerStackSelection = Convert.ToInt32(Console.ReadLine());
switch (PlayerStackSelection)
{
case(1):
PlayerStackSelection = 0;
break;
case (2):
PlayerStackSelection = 2;
break;
case (3):
PlayerStackSelection = 4;
break;
case (4):
PlayerStackSelection = 6;
break;
case (5):
PlayerStackSelection = 8;
break;
case (6):
PlayerStackSelection = 10;
break;
}
Console.Write("How many blocks do you wish to remove?: ");
int PlayerRemovedSelection = Convert.ToInt32(Console.ReadLine());
int spaces = 0;
int nearestBlock = 0;
for (int i = 0; i < 7; i++)
{
if (Board[i, PlayerStackSelection] == ' ')
{
spaces += 1;
}
}
for (int i = 0; i < 7; i++)
{
if (Board[i, PlayerStackSelection] == '█')
{
nearestBlock = i;
break;
}
}
if (spaces != 7)
{
for (int i = nearestBlock; i < (nearestBlock + PlayerRemovedSelection); i++)
{
Board[i, PlayerStackSelection] = ' ';
}
}
PrintBoard();
CheckIfBoardEmpty();
}
static void ComputerMove()
{
Random CompStack = new Random();
int CompStackSelection = CompStack.Next(1, 7);
int PreChangeStack = CompStackSelection;
switch (CompStackSelection)
{
case (1):
CompStackSelection = 0;
break;
case (2):
CompStackSelection = 2;
break;
case (3):
CompStackSelection = 4;
break;
case (4):
CompStackSelection = 6;
break;
case (5):
CompStackSelection = 8;
break;
case (6):
CompStackSelection = 10;
break;
}
Random CompRemoved = new Random();
int CompRemovedSelection = CompRemoved.Next(1, 7);
int spaces = 0;
int nearestBlock = 0;
for (int i = 0; i < 7; i++)
{
if (Board[i, CompStackSelection] == ' ')
{
spaces += 1;
}
}
while (spaces == 7)
{
CompRemovedSelection = CompRemoved.Next(1, 7);
CompStackSelection = CompStack.Next(1, 7);
switch (CompStackSelection)
{
case (1):
CompStackSelection = 0;
break;
case (2):
CompStackSelection = 2;
break;
case (3):
CompStackSelection = 4;
break;
case (4):
CompStackSelection = 6;
break;
case (5):
CompStackSelection = 8;
break;
case (6):
CompStackSelection = 10;
break;
}
for (int i = 0; i < 7; i++)
{
if (Board[i, CompStackSelection] == ' ')
{
spaces += 1;
}
}
}
for (int i = 0; i < 7; i++)
{
if (Board[i, CompStackSelection] == '█')
{
nearestBlock = i;
break;
}
}
if ((nearestBlock + CompRemovedSelection) !< 8)
{
while ((nearestBlock + CompRemovedSelection) !< 8)
{
CompRemovedSelection = CompRemoved.Next(1, 7);
}
}
if (spaces != 7)
{
for (int i = nearestBlock; i < (nearestBlock + CompRemovedSelection); i++)
{
Board[i, CompStackSelection] = ' ';
}
}
Console.WriteLine("Computer is making its move... ");
Thread.Sleep(1000);
Console.WriteLine("Computer has decided to remove {0} blocks from stack number {1}.\n", CompRemovedSelection, PreChangeStack);
Thread.Sleep(1000);
PrintBoard();
CheckIfBoardEmpty();
}
static void CheckIfBoardEmpty()
{
bool keepGoing = false;
for (int i = 0; i <= 6; i++)
{
for (int j = 0; j <= 11; j++)
{
if (Board[i,j] == '█')
{
GameStatus = false;
keepGoing = true;
break;
}
}
}
if (keepGoing != true)
{
Console.Write("BOARD EMPTY");
GameStatus = true;
}
}
static void Main(string[] args)
{
Introduction();
WhoGoesFirst();
for (int i = 0; i <= 6; i++)
{
for (int j = 0; j <= 11; j++)
{
if (j % 2 == 0)
{
Board[i, j] = '█';
}
else
{
Board[i, j] = ' ';
}
}
}
if (firstMove == "You")
{
while (GameStatus == false)
{
PlayerMove();
ComputerMove();
}
}
else
{
while (GameStatus == false)
{
ComputerMove();
PlayerMove();
}
}
}
}
}
So the user has a choice of 3 possible outputs:
- Draw a triangle
- Draw a rectangle
- Draw a house
I can draw all three but the output is not quiet right.
As you see in the code it draws a triangle but I need it to move more to the right.
if (keuze == 1)
{
int n = 4;
int i, j, k = 0;
for (i = 1; i <= n; i++)
{
for (j = i; j < n; j++)
{
Console.Write(" ");
}
while (k != (2 * i - 1))
{
if (k == 0 || k == 2 * i - 2)
Console.Write("*");
else
Console.Write(" ");
k++;
;
}
k = 0;
Console.WriteLine();
}
for (i = 0; i < 2 * n - 1; i++)
{
Console.Write("*");
}
Console.WriteLine();
}
Try This:
if (true)
{
int n = 4;
int i, j, k = 0;
for (i = 1; i <= n; i++)
{
for (j = i; j < n; j++)
{
Console.Write(" ");
}
while (k != (2 * i - 1))
{
if (k == 0) Console.Write(" "); //Added
if (k == 0 || k == 2 * i - 2)
Console.Write("*");
else
Console.Write(" ");
k++;
}
k = 0;
Console.WriteLine();
}
Console.Write(" "); //Added
for (i = 0; i < 2 * n - 1; i++)
{
Console.Write("*");
}
Console.WriteLine();
}
I am new at programming and I'm trying to understand why the methods call inside a switch statement is not working. Basically I have a main menu and a submenu. Whem I press the Animal submenu , the switch statement is meant to call the methods for a CRUD (insert new, visualize by Id, update, etc) but none of these options are working. Is the method call/structure correct?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace menu_clinica_veterinaria
{
class Program
{
public static int id = 1;
enum animalHeader { id, name, client_name, type_animal };
enum clientHeader { id, name, client_surname, adrress };
static void Main(string[] args)
{
string[,] animal = new string[20, 4];
string[,] client = new string[20, 6];
do { MenuOptions(animal); } while (true);
}
static void MenuOptions(string[,] animal)
{
int userChoice;
do
{
Console.Clear();
Console.WriteLine("\nChoose one of the following options:\n");
Console.WriteLine("[ 1 ] Animals");
Console.WriteLine("[ 2 ] Clients");
Console.WriteLine("[ 0 ] Quit application\n");
} while (!int.TryParse(Console.ReadLine(), out userChoice) || userChoice < 0 || userChoice > 2);
Console.Clear();
switch (userChoice)
{
case 1:
menuAnimal(animal);
break;
case 2:
//menuClient(client);
break;
case 0:
Environment.Exit(0);
break;
default:
Console.WriteLine("Try again!!");
break;
}
}
static void menuAnimal(string[,] animal)
{
int optAnimal;
while (true)
{
do
{
Console.Clear();
Console.WriteLine("\nInsert one of the following options:\n");
Console.WriteLine("[ 1 ] Insert animal");
Console.WriteLine("[ 2 ] See animal");
Console.WriteLine("[ 3 ] Alter animal");
Console.WriteLine("[ 4 ] Erase animal");
Console.WriteLine("[ 5 ] List animals");
Console.WriteLine("[ 0 ] Return to main menu\n");
} while (!int.TryParse(Console.ReadLine(), out optAnimal) || optAnimal < 0 || optAnimal > 5);
Console.Clear();
bool goBack = false;
switch (optAnimal)
{
case 1:
insertData(animal);
break;
case 2:
visualizeByid(animal);
break;
case 3:
updateById(animal);
break;
case 4:
deleteByid(animal);
break;
case 5:
listData(animal);
break;
case 0:
goBack = true;
break;
}
if (goBack) return;
}
}
static void mainMenu()
{
Console.Clear();
Console.ReadKey();
}
static void menuReturn(string[,] animal)
{
Console.Clear();
do { menuAnimal(animal); } while (true);
}
static int generateId()
{
return id++;
}
static int getInsertIndex(string[,] matrix)
{
for (int j = 0; j < matrix.GetLength(0) - 1; j++)
{
if (string.IsNullOrEmpty(matrix[j, 0])) return j;
}
return -1;
}
static void insertData(string[,] matrix)
{
int id = generateId();
int n = getInsertIndex(matrix);
matrix[n, 0] = Convert.ToString(id);
for (int j = 1; j < matrix.GetLength(1); j++)
{
do
{
Console.Write($"Insert {Enum.GetName(typeof(animalHeader), j)}: ");
matrix[n, j] = Console.ReadLine();
} while (String.IsNullOrEmpty(matrix[n, j]));
}
}
static int searchId(string[,] matrix)
{
int choosenId, index = -1;
do
{
Console.Write("Insert ID to continue: ");
} while (!int.TryParse(Console.ReadLine(), out choosenId));
for (int i = 0; i < matrix.GetLength(0); i++)
{
if (Convert.ToString(choosenId) == matrix[i, 0])
{
index = i;
}
}
return index;
}
static void visualizeByid(string[,] matrix)
{
int pos = searchId(matrix);
if (pos != -1)
{
for (int i = pos; i < pos + 1; i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
Console.Write($"{matrix[i, j]}\t");
}
Console.WriteLine();
}
}
else { Console.WriteLine("Wrong Id"); }
}
static void updateById(string[,] matrix)
{
int pos = searchId(matrix);
if (pos != -1)
{
for (int i = pos; i < pos + 1; i++)
{
for (int j = 1; j < matrix.GetLength(1); j++)
{
Console.Write($"Insert {Enum.GetName(typeof(animalHeader), j)}: ");
matrix[i, j] = Console.ReadLine();
}
Console.WriteLine();
}
}
else { Console.WriteLine("Id does not exist"); }
}
static void deleteByid(string[,] matrix)
{
int pos = searchId(matrix);
if (pos != -1)
{
for (int i = pos; i < pos + 1; i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
matrix[i, j] = null;
}
}
}
else { Console.WriteLine("Id does not exist"); }
}
static void listData(string[,] matrix)
{
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
Console.Write($"\t{matrix[i, j]}\t");
}
Console.WriteLine("\n\t");
}
}
}
}
It's a nifty little program for what it is.
However, you can't see an animal because:
searchId
for (var i = 0; i < matrix.GetLength(0); i++)
{
if (Convert.ToString(choosenId) == matrix[i, 0])
{
index = i;
// Though it's not the problem you could break here
// you could also just return from here
break;
}
}
Also, you'll need to Console.ReadKey() somewhere as your menu refreshes and overwrites the see animal routine.
menuAnimal
visualizeByid(animal);
// if you don't do something like this as the menu refreshes the animal away
Console.ReadKey();
The only other thing I'd suggest is to use lists and well-typed classes, instead of multidimensional arrays of strings; they are easier to work with, and you can use Linq.
Update
In regards to comments, given this:
private static string GetHeader<T>(int i) => Enum.GetName(typeof(T), i);
You could do something like this:
static void updateById<T>(string[,] matrix)
{
int pos = searchId(matrix);
if (pos != -1)
{
for (int i = pos; i < pos + 1; i++)
{
for (int j = 1; j < matrix.GetLength(1); j++)
{
Console.Write($"Insert {GetHeader<T>(j)}: ");
...
Usage:
updateById<animalHeader>(animal);
Basically this is some generics to reuse the updateById method and using your HeaderType.
Your program working Fine. You are using Console.Clear(). It will clear the screen which is displayed previously on the screen. Remove Console.Clear() in the program or Add Console.ReadKey() immediately after Switch block. I think it will work fine.
I want to make the x row- a,b,c,d,e,f,g,h,i,j and y row- 1,2,3,4,5,6,7,8,9,10
but I seriously can't figure out how it's done... here is the code I currently have:
namespace BattleShip.UI
{
public class Boards
{
public void DrawBoard()
{
char[,] Hi = new char[11, 11];
for (int i = 0; i < 11; i++)
{
for (int j = 0; j < 11; j++)
{
Hi[i, j] = 'A';
}
}
Console.WriteLine("\n");
for (int i = 0; i < 11; i++)
{
Console.Write($" {Hi[0, i]} ");
}
Console.WriteLine("\n");
for (int i = 0; i < 10; i++)
{
Console.WriteLine();
Console.Write(" ");
for (int j = 0; j < 10; j++)
{
Console.Write(" - - - ");
}
Console.WriteLine();
Console.Write($" {Hi[i, 0]} ");
for (int j = 0; j < 10; j++)
{
Console.Write($" - {Hi[i, j]} - ");
}
Console.WriteLine();
Console.Write(" ");
for (int j = 0; j < 10; j++)
{
Console.Write(" - - - ");
}
Console.WriteLine("\n");
}
}
}
}
It sounds like you want to make a 2D array but pre define your lables for the axis. When you create a 2D array you are just going to hold values based on the index of the array.
The way you are currently doing it is going to be difficult however, using a 2D array is a good idea for a BattleShip type game since the array will always be square.
If I where you I would create the array, then in each index put a 1 or a 0 depending if a ship exists on that "square". When a user types a location like "A3" I would convert the letter (with a method) and check the array at that location. If there's a 1 its a hit! If there a 0 its a miss!
I am currently struggling with building battleship but was able to print the boards for the two users playing.
Here is my code for adding the 1 2 3 ... and A B C D ... on the outside of the users boards.
namespace BattleShip.UI
{
public class PrintBoard
{
public static void printboard(Board board)
{
Console.WriteLine(" 1 2 3 4 5 6 7 8 9 10");
for (int i = 1; i <= 10; i++)
{
Console.Write($"{LetterToWrite(i)}");
for (int y = 1; y <= 10; y++)
{
Coordinate coordinate = new Coordinate(i, y);
ShotHistory ValShotHist = board.CheckCoordinate(coordinate);
switch (ValShotHist)
{
case ShotHistory.Unknown:
Console.Write(" ! ");
break;
case ShotHistory.Miss:
Console.Write(" M ");
break;
case ShotHistory.Hit:
Console.Write(" H ");
break;
default:
Console.Write(" ! ");
break;
}
}
Console.WriteLine("");
}
}
public static char LetterToWrite(int i)
{
switch (i)
{
case 1:
return 'A';
case 2:
return 'B';
case 3:
return 'C';
case 4:
return 'D';
case 5:
return 'E';
case 6:
return 'F';
case 7:
return 'G';``
case 8:
return 'H';
case 9:
return 'I';
default:
return 'J';
}
}
}
}
Ok for my program I am trying to get it so that when I have a Key press on my program and say I Press L and it moves in the 4x4 2d array and I get to pit which I designated as P on the array I want it to know it hit the P and print out you have a hit a Pit or if I reach where it has G on the array I want it to print out you have found gold. Any help is appreciated.
using System;
namespace DragonCave
{
public struct DragonPlayer
{
public int X, Y;
public string CurrentMove;
}
public class DragonGameboard
{
public string[,] GameboardArray;
public DragonPlayer Player;
private Random r;
public DragonGameboard(){
GameboardArray = new string[4,4];
Player.CurrentMove = "";
r = new Random();
Player.X = r.Next(0, 4);
Player.Y = r.Next(0, 4);
GenerateRandomBoard();
}
private void GenerateRandomBoard()
{
//Put a dot in every spot
int row;
int col;
for (row = 0; row < 4; row++)
{
for (col = 0; col < 4; col++)
{
Console.Write(GameboardArray[row, col] = ".");
}
//Console.WriteLine();
}
//Randomly Places the entrance, dragon, pit and gold.
GameboardArray[r.Next(0,4), r.Next(0, 4)] = "E";
GameboardArray[r.Next(0,4), r.Next(0,4)] = "D";
GameboardArray[r.Next(0, 4), r.Next(0, 4)] = "P";
GameboardArray[r.Next(0, 4), r.Next(0, 4)] = "P";
GameboardArray[r.Next(0, 4), r.Next(0, 4)] = "P";
GameboardArray[r.Next(0, 4), r.Next(0, 4)] = "G";
}
public void PrintBoard()
{
int row;
int col;
for (row = 0; row < 4; row++)
{
for (col = 0; col < 4; col++)
{
Console.Write(GameboardArray[row, col] + "\t");
}
Console.WriteLine();
}
Console.WriteLine("Cheat you are in" + Player.X + "," + Player.Y);
//fill with room numbers
}
public void ProcessMove(string move)
{
switch (move)
{
case "F":
Console.WriteLine("You chose forward");
break;
case "L":
Player.X--;
Player.Y--;
//Console.WriteLine("You chose Left");
Console.WriteLine("A Breeze is in the air");
break;
case "R":
Player.X++;
Player.Y++;
if (GameboardArray)
Console.WriteLine("You chose Right");
break;
case "G":
Console.WriteLine("You chose Grab gold");
break;
case "S":
Console.WriteLine("You chose Shoot arrow");
break;
case "C":
Console.WriteLine("You chose Climb");
break;
case "Q":
Console.WriteLine("You chose Quit");
break;
case "X":
Console.WriteLine("You chose Cheat");
PrintBoard();
break;
default:
Console.WriteLine("Invalid move!!!!!!!!!!1");
break;
}
}
}
Just check what the string is at GameboardArray[player.x, player.y].
public void ProcessTileEvent()
{
if( Player.X >= 0 && Player.X < 4 && Player.Y >= 0 && Player.Y < 4 )
{
switch( GameboardArray[Player.X, Player.Y] )
{
case "G":
Console.WriteLine( "You found gold!" );
break;
case "P":
Console.WriteLine( "You fell in a pit!" );
break;
}
}
}
You'd probably want to do this every time the player moves.