How to create the second player/Computer - c#

I am working to create a two player dice game, where the player can either play with another user or the computer. i am having a hard time figuring out how to create a two player game. I am not sure if i have to create separate classes for each user and then create an object of that class to have two separate players or if i just have to create a variable like
static int player = 1;
and assign it to specific areas and use modulus to figure out which player is up.
Also, under my roll_Btn method you will see that i am trying to get it to switch to the next user when the dice rolls a "1" and clear the specified fields, which it does, but the then program ends on me once i try and roll the dice again. See below for my code. thank you for your help and guidance.
public partial class Game : Form
{
public Game()
{
InitializeComponent();
}
static int player = 1;
private void Game_Load(object sender, EventArgs e)
{
oneNameTxt.Text = diceFrm.player1.ToUpper();
twoNameTxt.Text = diceFrm.player2.ToUpper();
}
private void endBtn_Click(object sender, EventArgs e)
{
diceFrm end = new diceFrm();
end.Show();
this.Hide();
}
private void standBtn_Click(object sender, EventArgs e)
{
oneScoreTxt.Text = totalTxt.Text;
}
private void rollBtn_Click(object sender, EventArgs e)
{
int t1 = Convert.ToInt32(turnsTxt.Text);
int t2 = t1 + 1;
turnsTxt.Text = t2.ToString();
Random rand = new Random();
int dice = rand.Next(1, 7);
rollTxt.Text = dice.ToString();
int d1 = Convert.ToInt32(totalTxt.Text);
int d2 = d1 + dice;
totalTxt.Text = d2.ToString();
if(dice == 1)
{
player++;
rollTxt.Text = String.Empty;
turnsTxt.Text = String.Empty;
totalTxt.Text = String.Empty;
}
}
private void oneScoreTxt_TextChanged(object sender, EventArgs e)
{
int score1 = Convert.ToInt32(oneScoreTxt.Text);
int score2 = Convert.ToInt32(twoScoreTxt.Text);
if (score1 >= 100 || score2 >= 100)
{
whatLbl.Text = "Winner";
}
else
{
whatLbl.Text = "Turn";
}
}

As Ogul Ozgul said,
private void rollBtn_Click(object sender, EventArgs e)
{
...
if (dice == 1)
{
...
turnsTxt.Text = String.Empty;
...
}
}
When you roll a 1, your turnsTxt.Text = String.Empty, hence when the next time you roll,
private void rollBtn_Click(object sender, EventArgs e)
{
int t1 = Convert.ToInt32(turnsTxt.Text); // program crash
...
}
your program will crash horribly.
Solution: I will recommend you use TryParse instead of Convert throughout your code. It will be much more robust.
Eg.
private void rollBtn_Click(object sender, EventArgs e)
{
int t1 = 0;
int.TryParse(turnsTxt.Text, out t1)
int t2 = t1 + 1;
turnsTxt.Text = t2.ToString();
...
//rest of your code
}

Related

How do I transfer data from a textbox to a data grid view in another winform via a button?

I have two forms, form1 and credentials. I want the data in my textbox (can be filled by user) to be transferred to the data grid view in form1.
Also, in form1, I want the data in my labels to be also transferred into the data grid view, which is also in form1. The labels I want to be transferred are: score, timer, level
I have tried and research for multiple solutions, yet none can really solve my problem. however, I tried to combine the solutions from websites and here is what i can do that kind of make sense to me. following are the codes for form1 and credentials.
form1 source code:
public partial class Form1 : Form
{
Snake mySnake;
Board mainBoard;
Rewards apples;
string mode;
Timer clock;
int duration; //How long the game has been running
int speed = 500; //500ms
int score;
int highscore;
int level;
public Form1()
{
InitializeComponent();
//button2.Text = Char.ConvertFromUtf32(0x2197);
//You don't have to worry about the auto-size
this.AutoSize = true; //The size of the Form will autoadjust.
boardPanel.AutoSize = true; //The size of the panel grouping all the squares will auto-adjust
//Set up the main board
mainBoard = new Board(this);
//Set up the game timer at the given speed
clock = new Timer();
clock.Interval = speed; //Set the clock to tick every 500ms
clock.Tick += new EventHandler(refresh); //Call the refresh method at every tick to redraw the board and snake.
duration = 0;
score = 0;
highscore = 0;
level = 1;
modeLBL.Text = mode;
gotoNextLevel(level);
scoresDGV.ColumnCount = 4;
scoresDGV.Columns[0].HeaderText = "Name";
scoresDGV.Columns[1].HeaderText = "Level";
scoresDGV.Columns[2].HeaderText = "Score";
scoresDGV.Columns[3].HeaderText = "Timer";
scoresDGV.AllowUserToAddRows = false;
scoresDGV.AllowUserToDeleteRows = false;
scoresDGV.MultiSelect = false;
scoresDGV.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
scoresDGV.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
}
private void refresh(Object myObject, EventArgs myEventArgs)
{
//increment the duration by amount of time that has passed
//this method is called every speed millisecond
duration += speed;
timerLBL.Text = Convert.ToString(duration / 1000); //Show time passed
//Check if snke is biting itself. If so, call GameOver.
if (mySnake.checkEatItself() == true)
{
GameOver();
}
else if (apples.checkIFSnakeHeadEatApple( mySnake.getHeadPosition()) == true)
{
score += apples.eatAppleAtPostion(mySnake.getHeadPosition());
scoreLBL.Text = Convert.ToString(score);
if (apples.noMoreApples() == true)
{
clock.Stop();
level++;
levelLBL.Text = Convert.ToString(level);
gotoNextLevel(level);
MessageBox.Show("Press the start button to go to Level " + level, "Congrats");
}
else
{
//Length the snake and continue with the Game
mySnake.extendBody();
}
}
if (score > highscore)
{
highscoreLBL.Text = Convert.ToString(highscore);
}
}
private void startBTN_Click(object sender, EventArgs e)
{
clock.Start();
}
private void pauseBTN_Click(object sender, EventArgs e)
{
clock.Stop();
}
private void restartBTN_Click(object sender, EventArgs e) //snapBTN
{
duration = 0;
mySnake.draw();
}
private void backBTN_Click(object sender, EventArgs e)
{
// hides the form from the user. in this case, the program hides the HowToPlay form
this.Hide();
MainMenu mM = new MainMenu();
mM.ShowDialog();
this.Close();
}
private void GameOver()
{
clock.Stop();
MessageBox.Show("Your time taken is " + duration/1000 + " seconds. Bye Bye", "Game Over");
this.Close();
addCurrentScoresToDatabase();
//updateScoreBoard();
}
private void modeLBL_Click(object sender, EventArgs e)
{
}
private void addCurrentScoresToDatabase()
{
Credentials c = new Credentials();
c.ShowDialog();
}
}
credentials source code:
public partial class Credentials : Form
{
public static string SetValueForName = "";
public Credentials()
{
InitializeComponent();
}
private void saveBTN_Click(object sender, EventArgs e)
{
SetValueForName = enternameTB.Text;
Form1 frm1 = new Form1();
frm1.Show();
}
private void cancelBTN_Click(object sender, EventArgs e)
{
}
}
Because part of your code is made in the designer (and not shown here in your post) it is difficult to understand how it works. I assume you have a simple dialog form which is shown in your form1
Credentials is shown modal. So if you have some properties in your credentials dialog, you may data transfer via the properties.
private void addCurrentScoresToDatabase()
{
Credentials c = new Credentials();
// initialize c here
c.ShowDialog();
// read data from c here
}
If you want get data from the credential dialog while it is shown, you should use events.
https://learn.microsoft.com/en-us/dotnet/standard/events/
If you want to transfer score, timer, level to datagridview and transfer Name from credentials to datagridview, you can refer to the following code:
Code in Form1:
int index;
public void AddScore_Click(object sender, EventArgs e)
{
index = scoresDGV.Rows.Add();
scoresDGV.Rows[index].Cells[1].Value = label1.Text;
scoresDGV.Rows[index].Cells[2].Value = label2.Text;
scoresDGV.Rows[index].Cells[3].Value = label3.Text;
Credentials c = new Credentials();
c.FormClosed += c_FormClosed;
c.Show();
}
void c_FormClosed(object sender, FormClosedEventArgs e)
{
scoresDGV.Rows[index].Cells[0].Value = Credentials.SetValueForName;
}
Code in Credentials:
public partial class Credentials : Form
{
public static string SetValueForName = "";
public Credentials()
{
InitializeComponent();
}
private void saveBTN_Click(object sender, EventArgs e)
{
SetValueForName = enternameTB.Text;
this.Close();
}
}
Here is the test result:

How to use check a Button in another Button statement? c#

I am having a problem . I want to use if statement to check if a button is clicked. For Example:
public void button1_Click(object sender, EventArgs e)
{
while (1)
{
...
...
...
if (Button2 == clicked)
{
break;
}
}
}
But it's not working like this, because the ".click" can only be on the left side of "+=" or "-=". Any idea how i can check if Button2 is clicked?
the code is loking like this: and i want to check button2 to stop the "programm".
the check for the Button2 is nearly at the end of the code ;)
public void button1_Click(object sender, EventArgs e)
{
Random rnd = new Random();
int EmFilterPos;
int ExFilterPos;
string String1;
int[] EmLB = new int[126];
int[] ExLB = new int[126];
int LBEmAnzahl = 0;
int LBEmTot = 0;
int LBExAnzahl = 0;
int LBExTot = 0;
UInt32 C_Zyklen;
UInt32 Zyklen;
Roche.DetectionControl2.Device_Filterwheels.ELBPowerState LB_On = Roche.DetectionControl2.Device_Filterwheels.ELBPowerState.LBOn;
Roche.DetectionControl2.Device_Filterwheels.ELBPowerState LB_Off = Roche.DetectionControl2.Device_Filterwheels.ELBPowerState.LBOff;
Roche.DetectionControl2.Device_Filterwheels.fiweGetLBResponse LightBarrier;
string Text = String.Format("Filterrad-Dauertest\r\nGestart am {0:d} um {0:t}\r\n\r\n", DateTime.Now);
System.IO.File.WriteAllText(#"TestLogFile\Filterrad_Dauertest1.txt", Text);
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweInitFilter();
System.Threading.Thread.Sleep(50);
while (Zyklen <= 20)
{
for (int q=1;q<8;q++)
{
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweMove(q,q);
System.Threading.Thread.Sleep(50);
Zyklen++;
}
for (int w=0;w<7;w++)
{
ExFilterPos = rnd.Next(1,8);
EmFilterPos = rnd.Next(1,8);
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweMove(ExFilterPos,EmFilterPos);
System.Threading.Thread.Sleep(50);
Zyklen++;
}
C_Zyklen = Zyklen;
if ((C_Zyklen % 2) < 14)
{
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweInitFilter();
System.Threading.Thread.Sleep(50);
using (System.IO.StreamWriter file = new System.IO.StreamWriter (#"TestLogFile\Filterrad_Dauertest1.txt", true))
{
file.Write("Init bei: ");
String1 = String.Format("{0,7}",Zyklen);
file.Write(String1);
file.Write(file.NewLine);
}
ExFilterPos = 60;
EmFilterPos = 60;
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweRawMove(ExFilterPos,EmFilterPos);
System.Threading.Thread.Sleep(50);
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweSetLB(LB_On);
while (EmFilterPos != -60)
{
LightBarrier = Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweGetLB();
if (LightBarrier.LBEm == Roche.DetectionControl2.Device_Filterwheels.ELBState.LBbright)
{
LBEmAnzahl++;
LBEmTot += EmFilterPos;
}
if (LightBarrier.LBEx == Roche.DetectionControl2.Device_Filterwheels.ELBState.LBbright)
{
LBExAnzahl++;
LBExTot += ExFilterPos;
}
ExFilterPos--;
EmFilterPos--;
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweRawMove(ExFilterPos,EmFilterPos);
}
EmFilterPos = LBEmTot / LBEmAnzahl;
ExFilterPos = LBExTot / LBExAnzahl;
using (System.IO.StreamWriter file = new System.IO.StreamWriter (#"TestLogFile\Filterrad_Dauertest1.txt", true))
{
file.Write("Nullstelle Mittelposition Em-Filter: ");
file.Write(EmFilterPos);
file.Write(file.NewLine);
file.Write("Nullstelle Mittelposition Ex-Filter: ");
file.Write(ExFilterPos);
file.Write(file.NewLine);
file.Write(file.NewLine);
}
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweSetLB(LB_Off);
}
if (Button2 == clicked) // or something like this
break;
}
using (System.IO.StreamWriter file = new System.IO.StreamWriter (#"TestLogFile\Filterrad_Dauertest1.txt", true))
{
file.Write("Beendet am {0:d} um {0:t}\r\n", DateTime.Now);
}*/
}
Hm...
bool b1clicked = false, b2clicked = false;
public void button2_Click(object sender, EventArgs e)
{
b2clicked = true;
}
public void button1_Click(object sender, EventArgs e)
{
b1clicked = true;
if (b1clicked && b2clicked)
{
//...
}
}
Beside the weird behavior you want..and since you are not using Threads, you have the following options:
Local functions (.Net > 4.7)
private void B_Click(object sender, EventArgs e)
{
bool clickFlag = false;
void Click(object sender2, EventArgs e2)
{
clickFlag = true;
}
b2.Click += Click;
while (!clickFlag)
{
Thread.Sleep(1);
}
b2.Click -= Click;
//Continue with your stuff
}
Threads
Thread newThread;
private void Button1_Click()
{
newThread = new Thread(YourBreakableProcess);
newThread.Start();
}
private void Button2_Click()
{
newThread.Join();
}
private void YourBreakableProcess()
{
//Your breakable process
}
Async methods.
I hope you find a solution. Cheers.
Edit:
Since what you want is to interrupt the process of whatever you are doing, the only option you have is Local fuctions as shown above, if you are not tied to a specific framework version.
BackgroundWorker and check in every step if the button 2 was pressed with the flag thing mentioned in other answer.
Threads, and make a thread.Join when the button 2 is pressed.
Edit 2:
Updated answer with Threads, I will recommend that if you go with this option it is much better to use a BackgroundWorker instead as you will have the whole control of the process breaking it only in the place where it would be fine to break it.
You can achieve this using a flag variable. Declare and initialize flag value to false.On button2 click change flag value to true as follows,
private bool flag= false;
private void button2_Click(object sender, EventArgs e)
{
flag= true;
}
public void button1_Click(object sender, EventArgs e)
{
//Use flag to check whether button 2 has clicked or not
if (flag)
{
}
else
{
}
}

C# How to move element on WFA in direction of mouse click controlling speed with timer

I have been trying to solve this problem for a really long time.
Is it possible to move button on Windows Forms application in C# in direction of click event, but controlling the speed of the movement by a timer function?
Here is my code. Can someone please tell me what am I doing wrong?
namespace juriKlik
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
int otkucaj = 1;
MrdajDugme(otkucaj);
}
private void MrdajDugme(int otkucaj)
{
int a = Convert.ToInt32(label1.Text);
int b = Convert.ToInt32(label2.Text);
int c = Convert.ToInt32(label7.Text);
int d = Convert.ToInt32(label8.Text);
Point p = new Point(c + otkucaj, d);
button1.Location = p;
}
private void panel1_MouseClick(object sender, MouseEventArgs e)
{
label1.Text = Convert.ToString(e.X);
label2.Text = Convert.ToString(e.Y);
label7.Text = Convert.ToString(button1.Location.X);
label8.Text = Convert.ToString(button1.Location.Y);
int a = e.X;
int b = e.Y;
int c = button1.Location.X;
int d = button1.Location.Y;
if(a > c)
{
timer1.Start();
}
}
}
}

visual studio timer ticks displayed?

This is my code for my drag race but I am wondering, I have my timer but how do I place it on a label?
private void tmrRaceTimerNamo_Tick(object sender, EventArgs e)
{
//car speed
pcbCar1Namo.Left = pcbCar1Namo.Left + 10;
pcbCar2Namo.Left = pcbCar2Namo.Left + 4;
pcbCar3Namo.Left = pcbCar3Namo.Left + 5;
pcbCar4Namo.Left = pcbCar4Namo.Left + 7;
//car stops at finish
AllCarsOnFinishNamo();
}
private void AllCarsOnFinishNamo()
{
if (pcbCar1Namo.Left > pcbFininshNamo.Right)
{
pcbCar1Namo.Left = pcbFininshNamo.Right;
}
if (pcbCar2Namo.Left > pcbFininshNamo.Right)
{
pcbCar2Namo.Left = pcbFininshNamo.Right;
tmrRaceTimerNamo.Enabled = false;
}
if (pcbCar3Namo.Left > pcbFininshNamo.Right)
{
pcbCar3Namo.Left = pcbFininshNamo.Right;
}
if (pcbCar4Namo.Left > pcbFininshNamo.Right)
{
pcbCar4Namo.Left = pcbFininshNamo.Right;
}
}
private void btnGoNamo_Click(object sender, EventArgs e)
{
//start of timer
tmrRaceTimerNamo.Enabled = true;
}
You can simply set the label to the value on each tick or update. For example in your tmrRaceTimerNamo_Tick(object sender, EventArgs e) method, you can set the labels text property to the time.
I dont exactly know what you want to show but i think you want to see the fps you are getting while playing your drag race game so here is a function for afps counter
private static int lastTick;
private static int lastFrameRate;
private static int frameRate;
public static int CalculateFrameRate()
{
label.Text = CalculateFrameRate().ToString();
if (System.Environment.TickCount - lastTick >= 1000)
{
lastFrameRate = frameRate;
frameRate = 0;
lastTick = System.Environment.TickCount;
}
frameRate++;
return lastFrameRate;
}

increment how many times an image is displayed in a picturebox

I'm trying to display an image using a button click and increment a variable when a certain image is shown, but with the code below the variable num is always 0.
my code
int num = 0;
int i = 0;
int x = 0;
PictureBox[] pictureBoxs = new PictureBox[4];
Random rnd = new Random();
public UserControl1()
{
InitializeComponent();
pictureBoxs[0] = pbimg1;
pictureBoxs[1] = pbimg2;
pictureBoxs[2] = pbimg3;
pictureBoxs[3] = pbimg4;
x = rnd.Next(2);
}
public void displaypics()
{
pictureBoxs[i].Image = imageList1.Images[x];
}
private void btn2_Click(object sender, EventArgs e)
{
i=1;
displaypics();
if (pictureBoxs[i].Image == imageList1.Images[1])
{
num++;
}
if (num == 2)
{
tb1.Visible = true;
tb1.Text = "GAME OVER!" + num;
}
}
The reason is most likely that num is being instantiated to zero everytime the class is being instantiated
What happens when you set breakpoints and step through the code? Is the int set as 0, or does it contain the updated value?
I'm not sure what the context is in which that piece of code is used. So I guess what should solve this would be adding x = rnd.Next(2) to the btn2_Click method. Making it look like this:
private void btn2_Click(object sender, EventArgs e)
{
x = rnd.Next(2);
displaypics();
if (pictureBoxs[i].Image == imageList1.Images[1])
{
num++;
}
if (num == 2)
{
tb1.Visible = true;
tb1.Text = "GAME OVER!" + num;
}
i++;
}
Maybe you could give some more details on what that control should do/how it's used.

Categories