Tic-Tac-Toe programming - c#

I'm trying to create a program for homework that displays a Tic-Tac-Toe board, and when the user clicks the button it displays a random number in all of the boxes. The number 1 = "X" and 0 = "O". I created 9 labels labeled "label1, label2...etc". Once the labels are full, I need to display who won, the letter X or O. I'm using arrays for this but am kinda of lost at this point. what do I need to do to display the random numbers into the labels. Here is the code I've written for the click event handler so far.
Random rand = new Random(2);
int click;
click = rand.Next(2);
const int ROWS = 3;
const int COLS = 3;
int[,] letters = new int[ROWS,COLS];
int ROW = ROWS;
int COL = COLS;
for (int row = 0; row < ROWS; ROW ++) {
for (int col = 0; col < COLS; COL ++) {
letters[row, col] = rand.Next(2);
int X = 1;//???
int O = 0;//???
label1.Text = [ROW,COL].ToString();//???
}
}

Here an attempt at an explanation:
first, you have the data to represent your problem:
const int ROWCOUNT = 3;
const int COLCOUNT = 3;
private int[,] letters = new int[ROWCOUNT,COLCOUNT];
Random rand = new Random(DateTime.Now.Ticks);
then you want to randomly fill that data:
private void randomize()
{
for( int row = 0; row < ROWCOUNT; row++ ){ //start with row=0, do row=row+1 until row no longer < ROWCOUNT
for( int col = 0; col < COLCOUNT; col++ ){
letters[row,col] = rand.nextInt(2);
}
}
}
finally, you want to display the array somewhere (in your case labels):
//These need to be added to a GridLayoutManager
private JLabel[,] labels = new JLabel[ROWCOUNT,COLCOUNT];
private void updateView(){
for( int row = 0; row < ROWCOUNT; row++ ){ //start with row=0, do row=row+1 until row no longer < ROWCOUNT
for( int col = 0; col < COLCOUNT; col++ ){
var current = letters[row,col];
var labelText = "O";
if( current > 0 )
labelText = "X";
labels[row,col].Text = labelText;
}
}
}
so, when the user clicks the button, you call:
randomize();
updateView();
hope it helps
from your comments, it seems setting the Label Text needs more explanation:
var labelText = "O";
if( current > 0 )
labelText = "X";
labels[row,col].Text = labelText;
maybe, i should have written it more like this:
String textForLabel = "O"; //0 represents O, 1 represents X
//test to see, if it really is a 0, not a 1
if( current != 0 ){
//oh, it is not a zero, therefore, set
textForLabel = "X";
}
JLabel labelAtRowAndCol = labels[row,col];
labelAtRowAndCol.Text = textForLabel;

I refuse to provide you the exact answer since you learning how to dot his is the entire point of this excerise.
Before I started the game I would randomly choose the first move: X or O.
I would then do the following:
1) I would place all the Labels into a collection.
2) I would randomly choose one of the Labels within the collection and change the Text property.
3) I would then remove the same Label from the collection
4) Rinse and Repeat.
You DO NOT need a two diminsional array for this.
In order to figure out the winner...I would keep track of the moves of each player. There is only a static number of winning moves in this game. Would be a simple task to determine if there were three X's in the top row or not.

#include<iostream>
#include<iomanip>
#include<set>
using namespace std;
char s[3][3] = {{'*','*','*'},{'*','*','*'},{'*','*','*'}};
void show(char os[3][3]);
int def[9];
void changeo(int n);
void changex(int n);
int stop();
set<int> cset;
int search (int n){
}
int main(){
int n; show(s);
int ss = 2;
cout<<endl;
while (stop()){
if (ss%2==0){
cout<<"player One(O) : enter n "; cin>>n;
if (!cset.count(n) && n<10){
cset.insert(n);
changeo(n);
show(s);
ss++;
}
else{
cout<<"invalid move"<<endl;
}
}
else{
cout<<"player Two(X) : enter n "; cin>>n;
if (!cset.count(n)&& n<10){
cset.insert(n);
changex(n);
show(s);
ss++;
}
}
}
cout<<"\nyou can see the winner"<<endl;
cout<<"your moves are "<<ss;
return 0;
}
void show(char s[3][3]){
cout<< setw(7)<< "1: " <<s[0][0]<<setw(5)<<"2: " <<s[0][1]<<setw(5)<<"3: " <<s[0][2]<<endl;
cout<< setw(7)<< "4: " <<s[1][0]<<setw(5)<<"5: " <<s[1][1]<<setw(5)<<"6: " <<s[1][2]<<endl;
cout<< setw(7)<< "7: " <<s[2][0]<<setw(5)<<"8: " <<s[2][1]<<setw(5)<<"9: " <<s[2][2]<<endl;
cout<<endl;
}
void changeo(int n){
switch(n){
case 1:
s[0][0] = 'O';
break;
case 2:
s[0][1] = 'O';
break;
case 3:
s[0][2] = 'O';
break;
case 4:
s[1][0] = 'O';
break;
case 5:
s[1][1] = 'O';
break;
case 6:
s[1][2] = 'O';
break;
case 7:
s[2][0] = 'O';
break;
case 8:
s[2][1] = 'O';
break;
case 9:
s[2][2] = 'O';
break;
}
}
void changex(int n){
switch(n){
case 1:
s[0][0] = 'X';
break;
case 2:
s[0][1] = 'X';
break;
case 3:
s[0][2] = 'X';
break;
case 4:
s[1][0] = 'X';
break;
case 5:
s[1][1] = 'X';
break;
case 6:
s[1][2] = 'X';
break;
case 7:
s[2][0] = 'X';
break;
case 8:
s[2][1] = 'X';
break;
case 9:
s[2][2] = 'X';
break;
}
}
int stop(){
int m=0;
for (int i=0; i<3; i++){
for (int j=0; j<3; j++){
if(s[i][j]=='*'){
m=1;
break;
}
}
}
return m;
}

Related

Function with changing labels

I am building a function in C# that will slice a frame and then count the white pixels in that slice. I want to be able to uses this function on multiple frames/pictureBoxs, so I need to change the name of label.Text to the correct label. How should I go about this? I'll be using mergedImage, mergedImage2, and BinaryImage. Each Image will also have outerRight, innerRight, Cent, innerLeft, outerLeft.
private void Slicing(Mat inputFrame)
{
Mat frame = inputFrame.Clone();
//count the number of white pixels
int whitePixelsExtendedOutterLeft = 0;
int whitePixelsExtendedInnerLeft = 0;
int whitePixelsExtendedCent = 0;
int whitePixelsExtendedInnerRight = 0;
int whitePixelsExtendedOutterRight = 0;
Image<Gray, byte> img = frame.ToImage<Gray, byte>();
//Calculates the outter left slice
for (int i = 0; i <= 4; i++)
{
for (int x = i; (frame.Width / 5) * i < (frame.Width / 5) * (i+1) ; x++)
{
for (int y = 0; y < frame.Height; y++)
{
switch (i)
{
case 0:
if (img.Data[y, x, 0] == 255) whitePixelsExtendedOutterLeft++;
break;
case 1:
if (img.Data[y, x, 0] == 255) whitePixelsExtendedInnerLeft++;
break;
case 2:
if (img.Data[y, x, 0] == 255) whitePixelsExtendedCent++;
break;
case 3:
if (img.Data[y, x, 0] == 255) whitePixelsExtendedInnerRight++;
break;
case 4:
if (img.Data[y, x, 0] == 255) whitePixelsExtendedOutterRight++;
break;
}
}
}
}
//displays their respective white pixel count to form1
Invoke(new Action(() =>
{
mergedImage.Text = $"{whitePixelsExtendedOutterLeft} Outter Left ";
//whitePixelsExtendedOutputLIL.Text = $"{whitePixelsExtendedInnerLeft} Inner Left ";
//whitePixelsExtendedOutputLCent.Text = $"{whitePixelsExtendedCent} Center ";
//whitePixelsExtendedOutputLIR.Text = $"{whitePixelsExtendedInnerRight} Inner Right ";
//whitePixelsExtendedOutputLOR.Text = $"{whitePixelsExtendedOutterRight} Outter Right ";
}));
}
I have tried concatenation of the of the label like: "mergedImage" ++ i .Text . of course this did not work.

Turtle Graphics - Process terminated due to StackOverflowException

I am trying to prepare a Turtle graphics solution in C#. Everything is working fine but it ends in Process Terminated due to StackOverflowException. I checked this
and
this
where the issue is of getter setter or infinite loop. But I dont have any of this condition in my code. I am a newbie in C#.
Below is my code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TurtleGraphics
{
class Program
{/**
* Directions: 0 right, 1 down, 2 left, 3 up
*/
private static short direction = 0;
private static bool penDown;
private static int turtleX = 0, turtleY = 0;
private static int[,] floor = new int[20, 20];
public static void Main(String[] args)
{
initFloor(floor);
//Scanner in = new Scanner(System.in);
printMenu();
int nextCommand = int.Parse(Console.ReadLine());
while (nextCommand != 9)
{
switch (nextCommand)
{
case 1:
penDown = false;
break;
case 2:
penDown = true;
break;
case 3:
direction++;
break;
case 4:
direction--;
break;
case 5:
Console.WriteLine("How many steps do you want to move?");
int move = int.Parse(Console.ReadLine());
if (move <= 10)
while (--move != 0)
Moves();
break;
case 6:
printArray();
break;
default:
Console.WriteLine("Unknow command, please try again:\n");
break;
}
Moves();
Console.WriteLine("What's next?");
nextCommand = int.Parse(Console.ReadLine());
}
}
private static void initFloor(int[,] floor)
{
for (int i = 0; i < floor.GetLength(0); i++)
{
for (int j = 0; j < floor.GetLength(1); j++)
{
floor[i,j] = 0;
}
}
}
private static void printMenu()
{
Console.WriteLine("Commands List:\n\n\t1 Pen up\n"
+ "\t2 Pen down\n"
+ "\t3 Turn right\n"
+ "\t4 Turn left\n"
+ "\t5 to 10 Move forward 10 spaces (replace 10 for a different number of spaces)\n"
+ "\t6 Display the 20-by-20 array\n"
+ "\t9 End of data (sentinel)Please enter a command number:\n");
}
private static void printArray()
{
for (int i = 0; i < floor.GetLength(0); i++)
{
for (int j = 0; j < floor.GetLength(1); j++)
{
// Console.WriteLine(floor[i, j]);
// Console.WriteLine(" ");
if (floor[i, j] == 0)
Console.Write(".");
else if (floor[i, j] == 1)
Console.Write("*");
else if (floor[i, j] == 2)
Console.Write("T");
}
Console.WriteLine();
}
}
private static void Moves()
{
switch (direction)
{
case 0:
turtleX++;
break;
case 1:
turtleY++;
break;
case 2:
turtleX--;
break;
case 3:
turtleY--;
break;
default:
if (direction < 0)
direction = 3;
else
direction = 4;
Moves();
break;
}
if (penDown)
{
if (turtleX < 20 && turtleY < 20)
floor[turtleX, turtleY] = 1;
else
{
direction -= 2;
Moves();
}
}
}
}
}
Any quick help is appreciated. Thanks
There's one obvious situation where you end up looping endlessly. Imagine you're entering the Moves method and direction is 4:
private static void Moves()
{
switch (direction)
{
case 0:
//Nope
case 1:
//Nope
case 2:
//Nope
case 3:
//Nope
default:
if (direction < 0)
//Nope
else
direction = 4; //Okay, but it already was
Moves(); //And call myself again
The code cannot make any further progress and the call stack fills up with more and more calls to Moves() that are never going to finish.
I can't offer a correction because I don't understand what your code is meant to be doing. Break it down into smaller methods with clearer method names and XML documentation comments that describe what it does. Then makes sure that the code and comments agree.
I have no idea what the correct operation of a method called Moves is.
The default section of the switch statement in Moves should be this:
default:
if (direction < 0)
direction += 4;
else
direction -= 4;
Moves();
break;
since its purpose is to wrap the direction value such that it always remains in the range 0-3.

Console not printing lines and/or words

I have a simple code just to have fun, it was supposed to print the entire alphabet, each letter separated from each other with 100 empty lines... But this is not printing any line....
Note: Before I used code similar to this and it worked (obviously the other was real code and didn't have the 100 lines thingy)
"alfabeto" = "alphabet" (Portuguese word, I was not going to translate 26 lines if I could just say this)
namespace Alfabeto_das_100_linhas
{
class Inicial
{
static void Main(string[] args)
{
string[] alfabeto = new string[26];
alfabeto[0] = "A";
alfabeto[1] = "B";
alfabeto[2] = "C";
alfabeto[3] = "D";
alfabeto[4] = "E";
alfabeto[5] = "F";
alfabeto[6] = "G";
alfabeto[7] = "H";
alfabeto[8] = "I";
alfabeto[9] = "J";
alfabeto[10] = "K";
alfabeto[11] = "L";
alfabeto[12] = "M";
alfabeto[13] = "N";
alfabeto[14] = "O";
alfabeto[15] = "P";
alfabeto[16] = "Q";
alfabeto[17] = "R";
alfabeto[18] = "S";
alfabeto[19] = "T";
alfabeto[20] = "U";
alfabeto[21] = "V";
alfabeto[22] = "W";
alfabeto[23] = "X";
alfabeto[24] = "Y";
alfabeto[25] = "Z";
for (int i = 0; i <= alfabeto.Length; i++)
{
Console.WriteLine(alfabeto[i]);
for(int iii = 0; i != 100; iii++)
{
Console.Write("\n");
}
Console.WriteLine();
}
Console.Read();
}
}
}
Your inner loop is wrong:
for(int iii = 0; i != 100; iii++)
{
Console.Write("\n");
}
Depending on the the value of i this will either do nothing or loop forever.
It should be:
for(int iii = 0; iii < 100; iii++)
{
Console.Write(Environment.NewLine);
}
In addition to fixing your loop counter, you were outputting the string \n rather than the newline character. You could also just use WriteLine with an empty string.
Now I look again, I see that your outer loop is also wrong. It should be:
for (int i = 0; i < alfabeto.Length; i++)
If you loop to the count equal to the length you'll exceed the length of the array - a 26 element array has indices 0 to 25.
If you're not sure what the inner loop is doing I'd reduce the end test to something more manageable (5 for example) so you can see exactly how many lines are being inserted between each of your letters. You could also output the loop counter (as a debug measure) as an extra check
Also notice that you have 101 line, not 100. Should be:
for (int i = 0; i < alfabeto.Length; i++)
{
Console.WriteLine(alfabeto[i]);
for (int iii = 0; iii < 100; iii++)
{
Console.WriteLine();
}
}
Console.Read();
Or you can simplify:
string s = new string('\n', 100);
for (char ch = 'A'; ch <= 'Z'; ch++)
{
Console.WriteLine(ch);
Console.Write(s);
}
Console.Read();

drawing a simple hangman design linked to my incorrect guesses in c#

I wish to display a simple hangman design using characters from the keyboard based on the incorrect answers that a user inputs. These incorrect answers will draw a new piece to the hangman each time although i am unsure how to do this. I have made my program function to cycle through 10 guesses before displaying the right answer and looping back to a new word.
The question i am asking is i do not know how to make a visual representation of a hangman in c# and how to link this to my existing code to only draw specific parts of the hangman based on the incorrect guesses. How do i do this?
The code is below.
namespace ConsoleApplication9
{
class Program
{
static string RandomWord()
{
Random rnd = new Random();
int response = rnd.Next(1, 4);
string randWord = "";
switch (response)
{
case 1:
randWord = "dog";
break;
case 2:
randWord = "robot";
break;
case 3:
randWord = "fish";
break;
case 4:
randWord = "continue";
break;
}
return randWord;
}
static void Main(string[] args)
{
string value = "";
int count = 0;
int gameLoop = 0;
string inData;
Console.WriteLine("Welcome to Hangman here is the first word");
do
{
count = 0;
value = RandomWord();
char[] newValue = new char[value.Length];
for (int i = 0; i < newValue.Length; i++)
{
newValue[i] = '_';
}
for (int i = 0; i < newValue.Length; i++)
{
Console.Write(newValue[i] + " ");
}
do
{
count++;
Console.Write("\n\nPlease enter your guess : ");
char input = (Console.ReadLine().ToCharArray()[0]);
for (int i = 0; i < value.Length; i++)
{
if (value[i] == input)
{
newValue[i] = input;
}
}
for (int x = 0; x < newValue.Length; x++)
{
Console.Write(newValue[x] + " ");
}
string s = (value);
string t = new string(newValue);
int c = string.Compare(s, t);
if (c == 0)
{
count = 10;
Console.WriteLine("\n\nCongratulations you guessed the word {0}", value);
}
} while (count < 10);
string Wrong = (value);
string Wrong2 = new string(newValue);
int gameOver = string.Compare(Wrong, Wrong2);
if (gameOver != 0)
{
Console.WriteLine("\n\nGame Over! the correct word was {0}", value);
}
Console.WriteLine("Would you like to go again? if so press 1 or 0 to exit");
inData = Console.ReadLine();
gameLoop = Convert.ToInt32(inData);
}
while (gameLoop == 1);
}
}
}
I am not quite sure how you plan to draw the hangman using ASCII art, but you could create a string array containing the 10 "pictures" as strings and then showing the corresponding one when appropriate.
You can create an array like so:
var pictures = new[]{":-)", ":-|", ":-(", "x.x", etc. };
and then
count++;
// display it here
Console.WriteLine(pictures[count]);
Console.Write("\n\nPlease enter your guess : ");

Three colors repeated

First i should mention that i am a beginner to C#.
This is the code i have done so far:
for (int row = 1; row <= 25; row++)
{
for (int col = 1; col <= 39; col++)
{
switch (row)
{
case 1:
Console.ForegroundColor = ConsoleColor.Yellow;
break;
case 2:
Console.ForegroundColor = ConsoleColor.Magenta;
break;
case 3:
Console.ForegroundColor = ConsoleColor.Green;
break;
}
Console.Write("* ");
}
Console.WriteLine();
I would really like that the three colors: Yellow, Magenta, Green to be repeated.
The three first sentence are ok, but the rest are green.
And have every other line one step to the right?
All help is appreciated
Thanks
Change your code in switch:
for (int row = 1; row <= 25; row++) {
for (int col = 1; col <= 39; col++)
{
switch (row%3)
{
case 1:
Console.ForegroundColor = ConsoleColor.Yellow;
break;
case 2:
Console.ForegroundColor = ConsoleColor.Magenta;
break;
case 0:
Console.ForegroundColor = ConsoleColor.Green;
break;
}
Console.Write("* ");
}
Console.WriteLine();
for (int row = 1; row <= 25; row++) {
for (int col = 1; col <= 39; col++)
{
int rowInd = row % 3;
switch (rowInd)
{
case 0:
Console.ForegroundColor = ConsoleColor.Yellow;
break;
case 1:
Console.ForegroundColor = ConsoleColor.Magenta;
break;
case 2:
Console.ForegroundColor = ConsoleColor.Green;
break;
}
Console.Write("* ");
}
Console.WriteLine();
giving just 1,2,3 rows will assign values for those only. So by using % sign, you will get remainder of row / 3. That is for 3 / 3, remainder = 0; for 4 / 3, remainder = 1; and for 5 / 3; remainder = 2; again 0 for 6 / 3;
Might try something like this:
ConsoleColor[] colors = new ConsoleColor[] {
ConsoleColor.Yellow,
ConsoleColor.Magenta,
ConsoleColor.Green
};
for (int row = 1; row <= 25; row++)
{
Console.ForegroundColor = colors[(row+1) % 3];
for (int col = 1; col <= 39; col++)
{
Console.Write("*");
}
Console.WriteLine();
}

Categories

Resources