Design an algorithm for guessing a card number - c#

I am making a card guessing game.there are 100 cards place in 10rows and 10 columns each card with a number and user have to find a number he is thinking of. i want to devise an algorithm to determine whether a given number is written on one of the cards by turning up less than 20 cards.I hav created the buttons dynamically, now im having hard time making a logic to search through them.This is my code.
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
int rememberlast = 0, move = 0;
object savelastobject;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
int sizee = 50, where = 0;
this.Height = 0;
this.Width = 0;
var generatedNum = new List<int>();
var random = new Random();
while (generatedNum.Count < 100)
{
var tempo = random.Next(0, 100);
if (generatedNum.Contains(tempo)) continue;
generatedNum.Add(tempo);
}
char[] text2 = text.ToCharArray();
for (int x = 0; x < 10; x++)
{
for (int y = 0; y < 10; y++)
{
Button ta = new Button();
ta.Name = x.ToString()+y.ToString();
ta.Width = sizee;
ta.Height = sizee;
ta.Tag = generatedNum[where];
where++;
ta.BackColor = Color.Red;
ta.Location = new Point(70 * y, 70 * x);
Controls.Add(ta);
ta.Click += new System.EventHandler(this.button_Click);
this.Width += 90 * x / 13;
this.Height += 90 * x / 8;
}
}
}
private void button_Click(object sender, EventArgs e)
{
Control me = (Control)sender;
rememberlast = int.Parse(me.Tag.ToString());
savelastobject = me;
me.Text = me.Tag.ToString();
me.Enabled = true;
me.BackColor = Color.Gray;
move++;
label2.Text = move.ToString();
me.Enabled = true;
me.Text = me.Tag.ToString();
me.BackColor = Color.Gray;
me.Refresh();
Thread.Sleep(1000);
if (move == 20)
{
MessageBox.Show("Total Moves Consumed");
Application.Restart();
}
if (me.Tag.ToString() == textBox1.Text)
{
//Control him = (Control)savelastobject;
//him.BackColor = Color.LightBlue;
me.BackColor = Color.LightBlue;
MessageBox.Show("You Win");
Application.Restart();
}
}
}
}

Related

Can't make a win checker in c# connect four game using windows forms

This is my code so far,im trying to make a c# connect four game but i cant seem to get the win checker to work! I'd like for my game to be able to check for four in a row, horizontally, vertically and diagonally and show a message telling you the winner. I have checked and everything else works as it should.
namespace ConnectFour
{
public partial class Form1 : Form
{
Button[] gameButtons = new Button[42]; //array of buttons for markers(red and blue)
bool blue = true; //blue is set to true if the next marker is to be a blue
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.Text = "Connect 4";
this.BackColor = Color.BlanchedAlmond;
this.Width = 500;
this.Height = 500;
for (int i = 0; i < gameButtons.Length; i++)
{
int index = i;
this.gameButtons[i] = new Button();
int x = 50 + (i % 7) * 50;
int y = 50 + (i / 7) * 50;
this.gameButtons[i].Location = new System.Drawing.Point(x, y);
this.gameButtons[i].Name = "btn" + (index + 1);
this.gameButtons[i].Size = new System.Drawing.Size(50, 50);
this.gameButtons[i].TabIndex = i;
//this.gameButtons[i].Text = Convert.ToString(index);
this.gameButtons[i].UseVisualStyleBackColor = true;
this.gameButtons[i].Visible = true;
gameButtons[i].Click += (sender1, ex) => this.buttonHasBeenPressed(sender1, index);
this.Controls.Add(gameButtons[i]);
}
}
private void buttonHasBeenPressed(object sender, int i)
{
if (((Button)sender).BackColor == Color.BlanchedAlmond)
{
if (blue == true)
{
((Button)sender).BackColor = Color.Red;
}
else
{
((Button)sender).BackColor = Color.Blue;
}
blue = !blue;
}
}
private void fourInARow(int a, int b, int c,int d)
{
if (gameButtons[a].BackColor == gameButtons[b].BackColor && gameButtons[a].BackColor == gameButtons[c].BackColor && gameButtons[a].BackColor==gameButtons[d].BackColor)
{
if (gameButtons[a].BackColor == Color.Blue)
{
MessageBox.Show("the winner is player 1");
}
else
{
MessageBox.Show("the winner is player 2");
}
}
}
}
Why do you use Index?
int index = I;
will stay at "0" - because its an initializer and only called once in for-loop.
But it makes no sense for me at all to have an index var.

How to use properties of text boxes outside of the current context in visual studio [duplicate]

I have created WinForm App in which user can set how many textboxes he want (Range 1-99)
I am using this code to create Textboxes during runtime
for (int i = 0; i < Calculation.Num; i++)
{
TextBox txtRun = new TextBox();
txtRun.Name = "txtBox" + i;
txtRun.Location = new System.Drawing.Point(35, 50 + (20 * i) * 2);
txtRun.Size = new System.Drawing.Size(75, 25);
this.Controls.Add(txtRun);
}
Suppose user create 2 textboxes and then enter data in each textbox and click calculate button
Now i want to get the textboxes data and divide it by 100
See The Picture I want txtbox1 and txtbox2 data
EDIT 3:
This is the Whole Code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GPA_Calculatior__New_
{
public partial class Form1 : Form
{
int j = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//Label + Marks Obtained Textbox
for (int i = 0; i < Calculation.Num; i++)
{
Label lblCount = new Label();
lblCount.Name = "lblCount" + i;
lblCount.Location = new System.Drawing.Point(5, 55 + (20 * i) * 2);
lblCount.Size = new System.Drawing.Size(20, 30);
lblCount.Text = (i + 1).ToString();
this.Controls.Add(lblCount);
TextBox txtRun = new TextBox();
txtRun.Name = "txtBox" + i;
txtRun.Location = new System.Drawing.Point(35, 50 + (20 * i) * 2);
txtRun.Size = new System.Drawing.Size(75, 25);
this.Controls.Add(txtRun);
}
//Creating Textbox which is for total marks
for (j = 0; j < Calculation.Num; j++)
{
TextBox txtRun = new TextBox();
txtRun.Name = "TotaltxtBox" + j;
txtRun.Location = new System.Drawing.Point(160, 50 + (20 * j) * 2);
txtRun.Size = new System.Drawing.Size(50, 25);
txtRun.Text = "100";
txtRun.Enabled = false;
this.Controls.Add(txtRun);
}
// Creating 2 Buttons (Calculate and Back)
for (int k = 0; k < 2; k++)
{
Button Btn = new Button();
Btn.Name = "btn" + k;
Btn.Location = new System.Drawing.Point(20 + (k *110), 60 + (20 * j) * 2);
Btn.Size = new System.Drawing.Size(90, 30);
if (k == 0)
Btn.Text = "Back";
else
Btn.Text = "Calculate";
Btn.Click += button_Click;
this.Controls.Add(Btn);
}
//Just for Giving free space in last
Label lbl = new Label();
lbl.Name = "lbl" + j;
lbl.Location = new System.Drawing.Point(30, 90 + (20 * j) * 2);
lbl.Size = new System.Drawing.Size(90, 30);
lbl.Text = "";
this.Controls.Add(lbl);
//**********************************************
}
//Caculate and back button function
private void button_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
if (btn.Name.Equals("btn1"))
{
for (int i = 0; i < Calculation.Num; i++)
{
}
}
else
{
GPA_Calculator mainForm = new GPA_Calculator();
mainForm.Show();
this.Hide();
}
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
for (j = 0; j < 10; j++)
{
}
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
Application.Exit();
}
}
}
var sum = this.Controls.OfType<TextBox>()
.Where(t => char.IsDigit(t.Name.Reverse().Take(1).FirstOrDefault())
&& t.Enabled)
.Select(t =>
{
double i;
if (!double.TryParse(t.Text, out i)) { return 0d; }
return i / 100d;
})
.Sum();
This may work, I built a separate class to store the control and its value, then you can work out the values independently from the rest of the form. You need to trigger the calculations though:
private List<InfoTextBox> activeTextBoxes = new List<InfoTextBox>();
public Form1()
{
for (int i = 0; i < Calculation.Num; i++)
{
TextBox txtRun = new TextBox();
txtRun.Name = "txtBox" + i;
txtRun.Location = new System.Drawing.Point(35, 50 + (20 * i) * 2);
txtRun.Size = new System.Drawing.Size(75, 25);
this.Controls.Add(txtRun);
InfoTextBox iBox = new InfoTextBox();
iBox.textbox = txtRun;
activeTextBoxes.Add(iBox);
}
}
public class InfoTextBox
{
private double _textboxValue;
public TextBox textbox { get; set; }
public double TextBoxValue { get { return _textboxValue; } set { _textboxValue = setValue(value); } }
private double setValue(double invalue)
{
return invalue / 100;
}
}

C# Form does not refresh

I have a problem with my program (Minesweeper game)
this is my Board class (mines board)
class Board
{
private Cell[,] MinesBoard;
private int maxrow, maxcol;
private int numOfMines;
public bool isLose;
private List<Point> MinesLocation;
private Random rnd;
private List<Point> randomPoint;
public delegate void OnClickEventHandler(object sender, CellClickEventArgs e);
public event OnClickEventHandler OnCellClick;
public int NumOfMines
{
get { return numOfMines; }
}
public int Column
{
get { return maxcol; }
}
public int Row
{
get { return maxrow; }
}
private void GetRandomPoints(int maxr, int maxc)
{
Point t = new Point();
t.X = rnd.Next(0, maxr);
t.Y = rnd.Next(0, maxc);
if (!randomPoint.Contains(t))
randomPoint.Add(t);
}
public Board(int _row, int _col, int _mines)
{
isLose = false;
maxrow = _row;
maxcol = _col;
numOfMines = _mines;
rnd = new Random(DateTime.Now.Ticks.GetHashCode());
randomPoint = new List<Point>();
MinesBoard = new Cell[_row, _col];
MinesLocation = new List<Point>();
for (int i = 0; i < maxrow; ++i)
for (int j = 0; j < maxcol; ++j)
{
MinesBoard[i, j] = new Cell();
//MinesBoard[i, j].button = new Button();
//MinesBoard[i, j].IsMine = false;
//MinesBoard[i, j].IsOpen = false;
//MinesBoard[i, j].MineAround = 0;
}
for (int i = 0; i < numOfMines; ++i)
GetRandomPoints(maxrow, maxcol);
foreach (Point p in randomPoint)
{
if (MinesBoard[p.X, p.Y].IsMine == false)
{
MinesBoard[p.X, p.Y].IsMine = true;
MinesLocation.Add(p);
}
}
}
public void DrawBoard(Form frm)
{
int id = 0;
for (int i = 0; i < maxrow; ++i)
for (int j = 0; j < maxcol; ++j)
{
frm.Controls.Remove(MinesBoard[i, j].button);
MinesBoard[i, j].button.Name = "btnCell" + id.ToString();
++id;
MinesBoard[i, j].button.Size = new Size(25, 25);
MinesBoard[i, j].button.Location = new Point(j * 25, 60 + i * 25);
//MinesBoard[i, j].button.FlatStyle = FlatStyle.Flat;
//CellClickEventArgs args = new CellClickEventArgs(new Point(i, j));
MinesBoard[i, j].button.Click += new System.EventHandler(CellClick);
MinesBoard[i, j].button.MouseDown += new MouseEventHandler(CellMouseDown);
//=========
MinesBoard[i, j].button.Tag = new Point(i, j);
//MinesBoard[i, j].button.Tag = MinesBoard[i, j].button;
//=========
if (MinesBoard[i, j].IsMine)
MinesBoard[i, j].button.Text = "z";
else
MinesBoard[i, j].button.Text = "";
frm.Controls.Add(MinesBoard[i, j].button);
}
}
when I change number of mines, it doesn't change correctly. But the rows and columns is OK
this is my Form1 class
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
private Board board;
private void frmMain_Load(object sender, EventArgs e)
{
board = new Board(8, 10, 15);
board.DrawBoard(this);
}
private void optionToolStripMenuItem_Click(object sender, EventArgs e)
{
frmOption option = new frmOption(board.Row, board.Column, board.NumOfMines);
if (option.ShowDialog() == DialogResult.OK)
{
board = new Board(option.Rows, option.Columns, option.Mines);
this.Size = new Size(board.Column * 25 + 5, board.Row * 25 + 88);
board.DrawBoard(this);
}
}
here is the picture:
8x10 15 mines
5x5 5 mines
when I set number of mines is 5, but it shows only 3 (1 z letter is 1 mine)
could you give me any solutions, thank you very much.!!!
When you click on the tool strip menu item, you're creating a new board, which will cause the old buttons to stay on the form (resize the form to see all of the old buttons). You will notice, that the mines are placed on the same buttons as before. This is caused by the old buttons staying in front of the new ones. Therefore, you need to clear the old board before creating a new one. Example:
public void Clear(Form frm)
{
for (int i = 0; i < maxrow; ++i)
{
for (int j = 0; j < maxcol; ++j)
{
frm.Controls.Remove(MinesBoard[i, j].button);
}
}
}
Call this directly before creating the new board:
private void optionToolStripMenuItem_Click(object sender, EventArgs e)
{
if (board != null)
{
board.Clear(this);
}
board = new Board(5, 5, 5);
this.Size = new Size(board.Column * 25 + 5, board.Row * 25 + 88);
board.DrawBoard(this);
}
Be sure to fix the bug mentioned by #AndersJH as well :)
I hope I don't misunderstand the question here. But the method GetRandomPoints does not guarantee to add a point to the list of random points. If the point exists, it will not be added.
I would suggest something like this:
while(randomPoint.Count < numOfMines)
{ GetRandomPoints(maxrow, maxcol); }

Reversi game color detection

I am recreating the classic game Reversi using c# in order to improve my skills at programming
but I have a problem when I check the colors. So far I have managed to revers colors from left and from top but it doesn't work correctly it only reverses the colors when I hit the last square on the board.
Any help would be much appreciated
Here is an image that may explain what I mean (the code is below) mean
The code that I have:
namespace praprevers
{
public partial class Form1 : Form
{
private Button[,] squares;
//private Button[,] r0;
public Form1()
{
InitializeComponent();
squares = new Button[4, 4];
squares = new Button[,] {
{btn_0_0, btn_0_1, btn_0_2, btn_0_3},
{btn_1_0, btn_1_1, btn_1_2, btn_1_3},
{btn_2_0, btn_2_1, btn_2_2, btn_2_3},
{btn_3_0, btn_3_1, btn_3_2, btn_3_3}
};
}
int _turn = 0;
private void DrawColor(object sender, EventArgs e)
{
Button b = sender as Button;
string[] btnData = b.Name.Split('_');
int x = int.Parse(btnData[1]);
int y = int.Parse(btnData[2]);
//check for possible combinations
int top = x - 3;
int botton = x +3;
int left = y - 3;
int right = y + 3;
for (int l = 0; l < 4; ++l)
{
if (top >= 0 && squares[top, y].BackColor == Color.Black)
{
squares[top + l, y].BackColor = Color.Black;
}
else if (left >= 0 && squares[x, left].BackColor == Color.Black)
{
squares[x, left + l].BackColor = Color.Black;
}
}
if (_turn == 0)
{
_turn = 1;
b.BackColor = Color.Black;
}
else
{
_turn = 0;
b.BackColor = Color.Red;
}
}
private void Form1_Load(object sender, EventArgs e)
{
foreach (Button sqrr in squares)
{
sqrr.Click += new System.EventHandler(this.DrawColor);
}
}
}
}

Trying to create a new page when horizontal pos. of i extends past right margin

I am trying add a page when horizontal or the x position is greater than a counter in order to keep a right side margin. When I run the code I end up in an infinate loop of hundreds of pages all displaying the same first page graphics. Thinking it might have to do with my lack of understanding HasMorePages. I could use some help. Thanks.
public static class PrintWave
{
public static void PrintPreWave()
{
PrintDocument pd = new PrintDocument();
if (WaveTools.MySettings == null)
{
pd.DefaultPageSettings.Landscape = true;
}
else
{
pd.DefaultPageSettings = WaveTools.MySettings;
}
pd.OriginAtMargins = true;
pd.PrintPage += new PrintPageEventHandler(OnPrintPage);
PrintDialog dlg = new PrintDialog();
PrintPreviewDialog printPreviewDlg = new PrintPreviewDialog();
printPreviewDlg.Document = pd;
Form p = (Form)printPreviewDlg;
p.WindowState = FormWindowState.Maximized;
printPreviewDlg.ShowDialog();
}
private static void OnPrintPage(object sender, PrintPageEventArgs e)
{
string MyTag = string.Empty;
MyTag = WaveActions.ActiveId;
Wave MyWave = WaveHolder.FindWave(MyTag);
int MyCount = 0;
int xOffset = e.MarginBounds.Location.X;
int yOffset = e.MarginBounds.Location.Y;
if (MyWave != null)
{
Graphics g = e.Graphics;
g.SetClip(e.PageBounds);
Pen MyPen = new Pen(WaveTools.WaveColor, WaveTools.PenWidth);
float dx = (float)e.PageBounds.Width / MyWave.NumSamples;
float dy = (float)e.PageBounds.Height / 255;
if (MyWave.Normal == false)
{
g.ScaleTransform(dx, dy);
}
for (int i = 0; i < MyWave.NumSamples - 1; i++)
{
g.DrawLine(MyPen, i, MyWave.Data[i], i + 1, MyWave.Data[i + 1]);
MyCount = MyCount + 1;
if (MyCount > e.MarginBounds.Width)
{
e.HasMorePages = true;
MyCount = 0;
return;
}
else
{
e.HasMorePages = false;
return;
}
}
}
}
}
}
for (int i = 0; i < MyWave.NumSamples - 1; i++)
That's the core problem statement, you start at 0 every time PrintPage gets called. You need to resume where you left off on the previous page. Make the i variable a field of your class instead of a local variable. Implement the BeginPrint event to set it to zero.
The else clause inside the loop need to be deleted.

Categories