Formatting Issue with for loop c# - c#

I'm trying to create a game called 'NIM' (See code introduction if you aren't familiar). When I output the 'blocks' they aren't spaced out evenly. I may be missing the obvious, but can someone point out where I'm going wrong.
using System;
using System.Threading;
namespace NIM
{
class Program
{
static void Main(string[] args)
{
Introduction();
InitialBoardSetUp();
}
static void Introduction()
{
Console.WriteLine("\t\t\t\tWelcome to NIM!\n");
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");
Console.WriteLine("Initialising the board:\n");
Thread.Sleep(2000);
}
static void InitialBoardSetUp()
{
for (int i = 1; i <= 7; i++)
{
Console.Write(" " + i + "\t");
}
Console.Write("\n\n");
for (int i = 1; i <= 7; i++)
{
Console.Write(" "+ i);
for (int j = 1; j <= 7; j++)
{
Console.Write(" ███\t");
}
Console.Write("\n");
}
}
}
}

The code below is your code with some minor modifications. \t has been removed and replaced with spaces. Spaces added before writing the column headers. Added comments.
Try the following:
using System;
using System.Threading;
namespace NIM
{
class Program
{
static void Main(string[] args)
{
Introduction();
InitialBoardSetUp();
}
static void Introduction()
{
Console.WriteLine("\t\t\t\tWelcome to NIM!\n");
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");
Console.WriteLine("Initialising the board:\n");
//Thread.Sleep(2000);
}
static void InitialBoardSetUp()
{
//add space for row numbers
Console.Write(" ");
//print column headers
for (int i = 1; i <= 7; i++)
{
Console.Write(" " + i + " ");
}
Console.Write("\n\n");
for (int i = 1; i <= 7; i++)
{
//print row numbers
Console.Write(" " + i);
for (int j = 1; j <= 7; j++)
{
//print blocks
Console.Write(" ███ ");
}
Console.Write("\n");
}
}
}
}

Related

How to make a game move continuously

I'm trying to program a game called NIM (https://plus.maths.org/content/play-win-nim). I've got halfway through, however, when a player makes a move, the board will simply reset to normal for the next move. Any thoughts on how I can make another move to the board and it takes into account the previous move?
static string underline = "\x1B[4m";
static string reset = "\x1B[0m";
static string firstMove;
static bool gameStatus = true;
static void Main(string[] args)
{
Introduction();
InitialBoardSetUp();
PlayingGame();
}
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 InitialBoardSetUp()
{
Console.WriteLine(underline + "This is how the board is formatted:\n" + reset);
Thread.Sleep(750);
Console.Write(" ");
for (int i = 1; i <= 7; i++)
{
Console.Write(" " + i + " ");
}
Console.Write("\n\n");
for (int i = 1; i <= 7; i++)
{
Console.Write(" " + i + " ");
for (int j = 1; j <= 7; j++)
{
Console.Write("███ ");
}
Console.Write("\n");
}
Console.Write("\n\n");
Thread.Sleep(1000);
}
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 ComputerMove()
{
Random CompStack = new Random();
int CompStackSelection = CompStack.Next(1, 8);
Random CompRemoved = new Random();
int CompRemovedSelection = CompRemoved.Next(1, 8);
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, CompStackSelection);
Thread.Sleep(1000);
Console.Write(" ");
for (int i = 1; i <= 7; i++)
{
Console.Write(" " + i + " ");
}
Console.Write("\n\n");
for (int i = 1; i <= 7; i++)
{
Console.Write(" " + i + " ");
for (int j = 1; j <= 7; j++)
{
if (j == CompStackSelection && i <= CompRemovedSelection)
{
Console.Write(" ");
}
else
{
Console.Write("███ ");
}
}
Console.Write("\n");
}
Console.Write("\n\n");
Thread.Sleep(1000);
}
static void PlayerMove()
{
Console.Write("Which stack do you wish to remove from?: ");
int PlayerStackSelection = Convert.ToInt32(Console.ReadLine());
// Exception Handling - Can't be greater than 7 or less than 1.
Console.Write("How many blocks do you wish to remove?: ");
int PlayerRemovedSelection = Convert.ToInt32(Console.ReadLine());
// Exception Handling - Can't be greater than 7 or less than 1.
Console.WriteLine();
Console.Write(" ");
for (int i = 1; i <= 7; i++)
{
Console.Write(" " + i + " ");
}
Console.Write("\n\n");
for (int i = 1; i <= 7; i++)
{
Console.Write(" " + i + " ");
for (int j = 1; j <= 7; j++)
{
if (j == PlayerStackSelection && i <= PlayerRemovedSelection)
{
Console.Write(" ");
}
else
{
Console.Write("███ ");
}
}
Console.Write("\n");
}
Console.Write("\n\n");
Thread.Sleep(1000);
}
static void PlayingGame()
{
int gameNumber = 1;
while (gameStatus == true)
{
Console.WriteLine(underline + "Round " + gameNumber+ ":\n" + reset);
WhoGoesFirst();
if (firstMove == "Computer")
{
ComputerMove();
}
else
{
PlayerMove();
}
gameNumber += 1;
playAgain();
}
}
static void playAgain()
{
Console.Write("Do you wish to play again? (Y/N): ");
char playAgain = Convert.ToChar(Console.ReadLine());
Console.WriteLine();
if (playAgain == 'Y')
{
gameStatus = true;
}
else if (playAgain == 'N')
{
gameStatus = false;
}
}
In PlayingGame() you need to create a game loop.
static void PlayingGame()
{
int turn = // randomly choose 0 or 1 (whose turn is it)
bool finished = false;
while(!finished)
{
if(turn==0)
{
ComputerMove();
} else {
PlayerMove();
}
finished = CheckForEndOfGame();
turn = 1 - turn;
}
}
I do strongly suggest to create a Game class that handles the logic of the game and separate the UI (like messages etc) from the game mechanics. This is C# after all, and object oriented approaches are strongly encouraged.
You need to keep track of that game board and whose turn it is and what has been played in this Game class and display on the screen things based on the values (the state) of the game.

breaks while loop when all die rolls the same number

using System;
using System.Collections.Generic;
namespace AnyDice
{
class Program
{
static void Main(string[] args)
{
int diceSides;
int rollDie;
int count = 0;
bool keepRolling = true;
List<int> num = new List<int>();
Random random = new Random();
Console.Write("Write the number of sides of your die: ");
diceSides = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Type the numbers of the die");
for (int i = 0; i < diceSides; i++)
{
int rank = 1 + i;
Console.Write(rank + "~~> ");
num.Add(Convert.ToInt32(Console.ReadLine()));
}
num.Sort();
Console.WriteLine("\nHere's the die and its contents");
for (int i = 0; i < num.Count; i++)
{
Console.Write("[");
Console.Write(num[i]);
Console.Write("]");
}
Console.WriteLine("\nHow many times do you want to roll at once");
rollDie = Convert.ToInt32(Console.ReadLine());
while (keepRolling)
{
for (int i = 0; i < rollDie; i++)
{
Console.Write("[");
Console.Write(num[random.Next(num.Count)]);
Console.Write("]");
count++;
}
Console.ReadLine();
}
Console.WriteLine("It took you " + count + " attempts");
Console.ReadLine();
}
}
}
For example if (4,4,4,4) is rolled or (2,2) in any "n" number of column the while loop breaks.
I thought of storing each die rolled value in another arraylist and comparing each value in it. If its all equal then it breaks.. but I have no clue on how to implement it.
We have Linq. It lives in the System.Linq namespace and this might help you.
I'll should two ways of checking if all die are the same:
int first = dies.First();
if (dies.All(i => i == first))
{
// break if all are equals to the first die
}
Or using Distinct we can filter out any copies.
if (dies.Distinct().Count() == 1)
{
// if we only have unique items and the count is 1 every die is the same
}
I am not 100% sure I understand your requirement, but in any case, you should write a separate function that returns a flag indicating whether the array is in a state that should trigger a break.
bool KeepRolling(int[] num)
{
for (int i=0; i<num.Length; i++)
{
if (num[i] >= i) return false;
}
return true;
}
Then just call it from within your loop:
keepRolling = KeepRolling(num);
while (keepRolling)
{
rolls.Clear();
for (int i = 0; i < rollDie; i++)
{
var firstRoll = num[random.Next(num.Count)];
rolls.Add(firstRoll);
Console.Write(firstRoll + " ");
count++;
}
if (rolls.Distinct().Count() == 1)
{
Console.WriteLine("It took you " + count + " attempts");
keepRolling = false;
break;
}
Console.ReadLine();
}

How do I not exceed the bounds of the array in Vigenere cipher?

After a 4th char, my program crashes, returning this error:
Index was outside the bounds of the array. at
System.String.get_Chars(Int32 index) at
Caesar_Cipher.Program.Main(String[] args)
I have really no idea how to fix it.
Here's the code:
using System;
using System.Collections.Generic;
using System.Text;
namespace vigenere_Cipher {
class Program {
static void Main(string[] args) {
string text = string.Empty;
string key = string.Empty;
Console.Write("Enter the keyword: ");
key = Console.ReadLine();
for(int i = 0; i < key.Length; i++)
{
if(char.IsLetter(key[i]))
{
}
else
{
Console.WriteLine("a key must be alphabetical!");
}
}
Console.Write("Enter plaintext: ");
text = Console.ReadLine();
int counter = 0;
for(int j = 0; j <= text.Length; j++)
{
if(counter <= text.Length)
{
counter ++;
}
if(char.IsLetter(text[j]))
{
if(char.IsUpper(text[j]))
{
Console.Write("Encrypted string: " + Convert.ToChar(((text[j] + key[counter] -65)% 26) + 65));
}
if(char.IsLower(text[j]))
{
Console.Write("Encrypted string: " + Convert.ToChar(((text[j] + key[counter]-97)%26) + 97));
}
Console.Write("\n");
}
Console.ReadKey();
}
}
}
}

How to print star like below in console application? I/p 5 O/p like = 1 212 32123 4321234 543212345 [duplicate]

My question is how to make a pyramid using * and 'space' in C#? The output will be like this.
*
* *
* * *
* * * *
* * * * *
We only need to use "for loop" for this program. I only know how to make this one.
*
**
***
****
*****
I made a program like this:
static void Main(string[]args)
{
int i=o;
int j=o;
for(i=5;1>=1;i--)
for(j=1;j<=5;j++)
{
Console.Write("*");
}
Console.WriteLine(" ");
}
I'm confused when it comes to pyramid because it includes spaces. Thanks for your help!
think about how you'd print the pyramid manually.
suppose 5 levels deep.
1st line: 4 spaces, 1 star,
2nd line: 3 spaces, star, space, star
3rd line: 2 spaces, star space star space star
etc.
doesn't matter whether you print spaces after the last star or not - won't make a difference to how it looks.
what do we see?
if we have a total of X levels
line 1: (x-1) spaces, (star space)
line 2: (x-2) spaces, (star space) twice
line 3: (x-3) spaces, (star space) three times
line 4: (x-4) spaces, (star space) four times
that's the pattern. I'll leave the coding to you.
using System;
class Program
{
static void Main(string[] args)
{
int num, i, j, k;
Console.Write("enter the level:");
num=Convert.ToInt32(Console.ReadLine());
for (i = 1; i <= num; i++)
{
for (j = 1; j < num-i+1; j++)
{
Console.Write(" ");
}
for (k = 1; k <= i; k++)
{
Console.Write(i);
Console.Write(" ");
}
Console.WriteLine();
}
}
}
Your problem is spaces, therefore I suggest you think about the spaces. Tell me this: how many spaces are on each row to the left of the first star? You'll likely be able to solve your own problem if you think about this.
Try to think of it as a grid or a matrix and see where you want the '*' in each row and how it relates to your loop index.
sorry I missed this was homework... will give a strategy ... instead
it helps if you do it in notepad and think about what you are doing... you will start to understand the relationship between the line you are on and the spaces and what not...
Post my answer after 3 hours. I think now you have almost finished it under #iluxa's advice?
int height = 20;
for (int level = 1; level <= height; level++)
{
string text = string.Join(" ", Enumerable.Repeat("*", level));
Console.WriteLine(text.PadLeft(height - level + text.Length));
}
I used some build-in methods e.g. Enumerable.Repeat and String.PadLeft, not the pure C-language way. The purpose is that I want to tell you since you have chosen C# as the programming language(not C/Java/etc), you should resolve problems in the C# way.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace pyramid_star
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("enter a number:");
int n = Convert.ToInt32(Console.ReadLine());
for (int i = 1; i <= n; i++)
{
for (int x = i; x <= n; x++)
{
Console.Write(" ");
}
for (int j = 1; j <= i; j++)
{
Console.Write("*"+" ");
}
Console.WriteLine();
}
Console.ReadLine();
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace Star_Pyramid
{
class Program
{
static void Main(string[] args)
{
Program o = new Program();
o.show();
Console.ReadKey();
}
void show()
{
for (int i = 1; i <= 12; i++)
{
for (int j = 1; j <= 9 - i / 2; j++)
{
Console.Write(" ");
}
for (int k = 1; k <= i; k++)
{
Console.Write(" * ");
Console.Write(" ");
}
Console.WriteLine();
}
}
}
}
class Program
{
static void Main(string[] args)
{
int num;
Console.WriteLine("enter level");
num = Int32.Parse(Console.ReadLine());
int count = 1;
for (int lines = num; lines >= 1; lines--)
{
for (int spaces = lines - 1; spaces >= 1; spaces--)
{
Console.Write(" ");
}
for (int star = 1; star <= count; star++)
{
Console.Write("*");
Console.Write(" ");
}
count++;
Console.WriteLine();
}
Console.ReadLine();
}
}
Try this and follow this same logic in c, c++, php, java
using System;
class pyramid {
static void Main() {
/** Pyramid stars Looking down
Comment this if u need only a upside pyramid **/
int row, i, j;
// Total number of rows
// You can get this as users input
//row = Int32.Parse(Console.ReadLine());
row = 5;
// To print odd number count stars use a temp variable
int temp;
temp = row;
// Number of rows to print
// The number of row here is 'row'
// You can change this as users input
for ( j = 1 ; j <= row ; j++ ) {
// Printing odd numbers of stars to get
// Number of stars that you want to print with respect to the value of "i"?
for ( i = 1 ; i <= 2*temp - 1 ; i++ )
Console.Write("*");
// New line after printing a row
Console.Write("\n");
for ( i = 1 ; i <= j ; i++ )
Console.Write(" ");
// Reduce temp value to reduce stars count
temp--;
}
/** Pyramid stars Looking up
Comment this if u need only a downside pyramid **/
int rowx, k, l;
// Total number of rows
// You can get this as users input
// rowx = Int32.Parse(Console.ReadLine());
rowx = 5;
// To print odd number count stars use a temp variable
int tempx;
tempx = rowx;
//Remove this if u use
Console.Write("\n");
// Number of rows to print
// The number of row here is 'rowx'
for ( l = 1 ; l <= rowx ; l++ ) {
// Leaving spaces with respect to row
for ( k = 1 ; k < tempx ; k++ )
Console.Write(" ");
// Reduce tempx value to reduce space(" ") count
tempx--;
// Printing stars
for ( k = 1 ; k <= 2*l - 1 ; k++ )
Console.Write("*");
// New line after printing a row
Console.Write("\n");
}
}
}
The following code might help:
public static void print(int no)
{
for (int i = 1; i <= no; i++)
{
for (int j = i; j <= no; j++)
{
Console.Write(" ");
}
for (int k = 1; k < i * 2; k++)
{
if(k % 2 != 0)
{
Console.Write("*");
}
else
{
Console.Write(" ");
}
}
Console.WriteLine();
}
Console.ReadLine();
}
Here I have created a number pyramid:
using System;
public class Program
{
public static void Main()
{
Console.WriteLine("This is a number pyramid....");
var rows = 5;
for(int i = 1; i <= rows; i++)
{
for(int lsc = (-rows); lsc <= -2; lsc ++)
{
if(lsc < (-1)*i)
{
//write left sided blank spaces
Console.Write(" ");
}
else
{
//write left sided numbers
Console.Write(-1*(lsc));
}
}
for(int rsc = 1; rsc <= rows; rsc++)
{
//write right sided blank spaces
Console.Write(" ");
}
else
{
//Write sided numbers
Console.Write(rsc);
}
}
Console.WriteLine();
}
}
}
I have described here https://utpalkumardas.wordpress.com/2018/04/20/draw-number-pyramid
Out put is:
The is a number pyramid....
1
212
32123
4321234
543212345
I know it's javascript but might help
let n = 6;
for (let i = 1; i <= n; i++) {
let spaces = n-i;
let str = '';
for (let j=0; j < spaces; j++) {
str+=' ';
}
for (let j=0; j < i; j++) {
str+='* ';
}
console.log(str)
}
I have found two approaches:
//1st approach
int n = 6;
for (int i = 0; i < n; i++)
{
// need to print spaces
for (int j = 0; j < n - i - 1; j++)
{
Console.Write(" ");
}
// need to print * with one space
for (int k = 0; k <= i; k++)
{
Console.Write("* ");
}
Console.WriteLine();
}
// 2nd Approach
int rows = 6;
int temp = 0;
bool toggle = false;
for (int j = 0; j < rows; j++)
{
int counter = 0;
for (int i = 0; i < 2 * rows - 1; i++)
{
if (i < rows - temp - 1)
{
Console.Write(" ");
}
else
{
if (counter <= j + temp)
{
if (!toggle)
{
Console.Write("*");
toggle = true;
}
else
{
Console.Write(" ");
toggle = false;
}
}
counter++;
}
}
Console.WriteLine();
temp++;
toggle = false;
}

The COntrol of the program does not enter the for loop

Here i am pasting the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace star1
{
class Program
{
static void Main(string[] args)
{
Myclass obj = new Myclass();
obj.getData();
obj.pattern();
}
}
class Myclass
{
int i, n, j;
public void getData()
{
Console.WriteLine("Program for displaying pattern of *.");
Console.Write("Enter the maximum number of *: ");
int n = Convert.ToInt32(Console.ReadLine());
}
public void pattern()
{
Console.WriteLine("\nPattern 1 - Left Aligned:\n");
for (i = 1; i <= n; i++) // The Control does not enter the for loop
{
for (j = 1; j <= i; j++)
Console.Write("*");
Console.WriteLine();
}
}
}
}
Looks like you're redeclaring n as a local variable in getData().
Try changing that line to:
n = Convert.ToInt32(Console.ReadLine());
i.e. remove the int.
well ...
as you are not using this...
class Myclass
{
int i, n, j;
public void getData()
{
Console.WriteLine("Program for displaying pattern of *.");
Console.Write("Enter the maximum number of *: ");
this.n = Convert.ToInt32(Console.ReadLine());
// OR
//n = Convert.ToInt32(Console.ReadLine());
}
public void pattern()
{
Console.WriteLine("\nPattern 1 - Left Aligned:\n");
for (i = 1; i <= n; i++) // The Control does not enter the for loop
{
for (j = 1; j <= i; j++)
Console.Write("*");
Console.WriteLine();
}
}
}
i would encourage you to use this to distinct between scope- and instance-variables!
If you try to assign n using Console.ReadLine() in getData(), you need to remove the "int" just before. Currently, you have 2 "n" variable in different scopes. That's why your loop doesn't work.

Categories