I am working on a Windows form, I have two lists: one for the names of players, and one for the numbers which the players have guessed. With this code I get in listbox name of all players, but the problem is I can get only number from last player which are same with numbers which are generated from system and the numbers which player has guessed, but I need to know how to get numbers which are same from two lists for every players, example:
Player 1:
2, 3 , 28 // has three numbers same from the lists
Player 2:
1
etc..
I wrote this code:
namespace LojaFatitForm
{
public partial class Loja_e_Fatit : Form
{
public Loja_e_Fatit()
{
InitializeComponent();
}
int player = 1;
int Guessed=0;
int ticket = 1;
string t = "-------------------------------------------------------------------------------------";
List<string> nameOfPlayers = new List<string>();
List<string> choosedNumbers = new List<string>();
List<string> winningNumbers = new List<string>();
List<string> guessedNumbers = new List<string>();
private void Loja_e_Fatit_Load(object sender, EventArgs e)
{ }
private void bntGenerateNr_Click(object sender, EventArgs e)
{
int Mosha;
Int32.TryParse(txtMosha.Text, out Mosha);
if (Mosha < 18)
{
MessageBox.Show("Lojtari duhet te jete ne moshen madhore!");
txtMosha.Text = "";
}
if (string.IsNullOrWhiteSpace(txtMosha.Text) || string.IsNullOrWhiteSpace(txtEmri.Text) || string.IsNullOrWhiteSpace(txtMbiemri.Text) || string.IsNullOrWhiteSpace(txtQyteti.Text)
|| string.IsNullOrWhiteSpace(txtNr1.Text) || string.IsNullOrWhiteSpace(txtNr2.Text) || string.IsNullOrWhiteSpace(txtNr3.Text) || string.IsNullOrWhiteSpace(txtNr4.Text)
|| string.IsNullOrWhiteSpace(txtNr5.Text)|| string.IsNullOrWhiteSpace(txtNr6.Text) || string.IsNullOrWhiteSpace(txtNr7.Text))
{
MessageBox.Show("Ju lutemi jepni te dhenat/Numrat tuaja!");
}
else
if(txtNr2==txtNr1 || txtNr2==txtNr3 )
{
MessageBox.Show("Ky numur edhe dhene, jepni nje numer tjeter!");
txtNr2.Text = "";
}
else
if (txtNr3 == txtNr2 || txtNr3==txtNr1)
{
MessageBox.Show("Ky numur edhe dhene, jepni nje numer tjeter!");
txtNr3.Text = "";
}else
if (txtNr4 == txtNr1 || txtNr4==txtNr3 || txtNr4==txtNr2)
{
MessageBox.Show("Ky numur edhe dhene, jepni nje numer tjeter!");
txtNr4.Text = "";
}else
if (txtNr5 == txtNr1 || txtNr5==txtNr2 || txtNr5==txtNr3 || txtNr5==txtNr4)
{
MessageBox.Show("Ky numur edhe dhene, jepni nje numer tjeter!");
txtNr5.Text = "";
}
else
if (txtNr6 == txtNr1 || txtNr6==txtNr2 || txtNr6==txtNr3 || txtNr6==txtNr4 || txtNr6==txtNr5)
{
MessageBox.Show("Ky numur edhe dhene, jepni nje numer tjeter!");
txtNr6.Text = "";
}else
if (txtNr7 == txtNr1 || txtNr7==txtNr2 || txtNr7==txtNr3 || txtNr7==txtNr4 || txtNr7==txtNr5 || txtNr7==txtNr6)
{
MessageBox.Show("Ky numur edhe dhene, jepni nje numer tjeter!");
txtNr7.Text = "";
}
else
{
Random r = new Random();
int Nr1, Nr2, Nr3, Nr4, Nr5, Nr6, Nr7;
Int32.TryParse(txtNr1Gen.Text, out Nr1);
Nr1 = r.Next(1, 39);
txtNr1Gen.Text = Nr1.ToString();
if ((txtNr1Gen.Text == txtNr1.Text) || (txtNr1Gen.Text == txtNr2.Text) || (txtNr1Gen.Text == txtNr3.Text) ||
(txtNr1Gen.Text == txtNr4.Text) || (txtNr1Gen.Text == txtNr5.Text) || (txtNr1Gen.Text == txtNr6.Text) || (txtNr1Gen.Text == txtNr7.Text))
{
winningNumbers.Add(txtNr1Gen.Text);
Guessed++;
}
Int32.TryParse(txtNr2Gen.Text, out Nr2);
nr2: Nr2 = r.Next(1, 39);
if (Nr2 == Nr1)
{
goto nr2;
}
else
{
txtNr2Gen.Text = Nr2.ToString();
if ((txtNr2Gen.Text == txtNr1.Text) || (txtNr2Gen.Text == txtNr2.Text) || (txtNr2Gen.Text == txtNr3.Text) ||
(txtNr2Gen.Text == txtNr4.Text) || (txtNr2Gen.Text == txtNr5.Text) || (txtNr2Gen.Text == txtNr6.Text) || (txtNr2Gen.Text == txtNr7.Text))
{
winningNumbers.Add(txtNr2Gen.Text);
Guessed++;
}
}
Int32.TryParse(txtNr3Gen.Text, out Nr3);
nr3: Nr3 = r.Next(1, 39);
if (Nr3 == Nr2 || Nr3 == Nr1)
{
goto nr3;
}
else
{
txtNr3Gen.Text = Nr3.ToString();
if ((txtNr3Gen.Text == txtNr1.Text) || (txtNr3Gen.Text == txtNr2.Text) || (txtNr3Gen.Text == txtNr3.Text) ||
(txtNr3Gen.Text == txtNr4.Text) || (txtNr3Gen.Text == txtNr5.Text) || (txtNr3Gen.Text == txtNr6.Text) || (txtNr3Gen.Text == txtNr7.Text))
{
winningNumbers.Add(txtNr3Gen.Text);
Guessed++;
}
}
Int32.TryParse(txtNr4Gen.Text, out Nr4);
nr4: Nr4 = r.Next(1, 39);
if (Nr4 == Nr3 || Nr4 == Nr2 || Nr4 == Nr1)
{
goto nr4;
}
else
{
txtNr4Gen.Text = Nr4.ToString();
if ((txtNr4Gen.Text == txtNr1.Text) || (txtNr4Gen.Text == txtNr2.Text) || (txtNr4Gen.Text == txtNr3.Text) ||
(txtNr4Gen.Text == txtNr4.Text) || (txtNr4Gen.Text == txtNr5.Text) || (txtNr4Gen.Text == txtNr6.Text) || (txtNr4Gen.Text == txtNr7.Text))
{
winningNumbers.Add(txtNr4Gen.Text);
Guessed++;
}
}
Int32.TryParse(txtNr5Gen.Text, out Nr5);
nr5: Nr5 = r.Next(1, 39);
if (Nr5 == Nr4 || Nr5 == Nr3 || Nr5 == Nr2 || Nr5 == Nr1)
{
goto nr5;
}
else
{
txtNr5Gen.Text = Nr5.ToString();
if ((txtNr5Gen.Text == txtNr1.Text) || (txtNr5Gen.Text == txtNr2.Text) || (txtNr5Gen.Text == txtNr3.Text) ||
(txtNr5Gen.Text == txtNr4.Text) || (txtNr5Gen.Text == txtNr5.Text) || (txtNr5Gen.Text == txtNr6.Text) || (txtNr5Gen.Text == txtNr7.Text))
{
winningNumbers.Add(txtNr5Gen.Text);
Guessed++;
}
}
Int32.TryParse(txtNr6Gen.Text, out Nr6);
nr6: Nr6 = r.Next(1, 39);
if (Nr6 == Nr5 || Nr6 == Nr4 || Nr6 == Nr3 || Nr6 == Nr2 || Nr6 == Nr1)
{
goto nr6;
}
else
{
txtNr6Gen.Text = Nr6.ToString();
if ((txtNr6Gen.Text == txtNr1.Text) || (txtNr6Gen.Text == txtNr2.Text) || (txtNr6Gen.Text == txtNr3.Text) ||
(txtNr6Gen.Text == txtNr4.Text) || (txtNr6Gen.Text == txtNr5.Text) || (txtNr6Gen.Text == txtNr6.Text) || (txtNr6Gen.Text == txtNr7.Text))
{
winningNumbers.Add(txtNr6Gen.Text);
Guessed++;
}
}
Int32.TryParse(txtNr7Gen.Text, out Nr7);
nr7: Nr7 = r.Next(1, 39);
if (Nr7 == Nr6 || Nr7 == Nr5 || Nr7 == Nr4 || Nr7 == Nr3 || Nr7 == Nr2 || Nr7 == Nr1)
{
goto nr7;
}
else
{
txtNr7Gen.Text = Nr7.ToString();
if ((txtNr7Gen.Text == txtNr1.Text) || (txtNr7Gen.Text == txtNr2.Text) || (txtNr7Gen.Text == txtNr3.Text) ||
(txtNr7Gen.Text == txtNr4.Text) || (txtNr7Gen.Text == txtNr5.Text) || (txtNr7Gen.Text == txtNr6.Text) || (txtNr7Gen.Text == txtNr7.Text))
{
winningNumbers.Add(txtNr7Gen.Text);
Guessed++;
}
}
updateListbox("");
updateListbox("Random numbers generated are:" + txtNr1Gen.Text + " " + txtNr2Gen.Text + " " + txtNr3Gen.Text + " " + txtNr4Gen.Text + " " + txtNr5Gen.Text + " " + txtNr6Gen.Text + " " + txtNr7Gen.Text);
updateListbox(t);
}
bntGenerateNr.Enabled = false;
btnNewPlayer.Enabled = false;
btnSave.Enabled = false;
foreach (var i in choosedNumbers)
{
foreach (var j in winningNumbers)
{
if (i == j)
{
guessedNumbers.Add(i);
}
}
}
foreach (var i in nameOfPlayers)
{
if (Guessed < 1)
{
updateListbox("There are no winners in this round!");
}
else
{
updateListbox("Player: " + i + " has guessed " + Guessed + " Numbers: ");
updateListbox(string.Join(", ", guessedNumbers));
foreach (var j in guessedNumbers)
{
updateListbox(j);
}
}
}
}
private void updateListbox(string value)
{
Lista.Items.Add(value);
Lista.TabIndex = Lista.Items.Count - 1;
}
private void btnBack_Click(object sender, EventArgs e)
{
MainForm main = new MainForm();
this.Hide();
main.ShowDialog();
this.Close();
}
private void btnNewPlayer_Click(object sender, EventArgs e)
{
txtNr1.Text = null;
txtNr2.Text = null;
txtNr3.Text = null;
txtNr4.Text = null;
txtNr5.Text = null;
txtNr6.Text = null;
txtNr7.Text = null;
txtEmri.Text = "";
txtMbiemri.Text = "";
txtMosha.Text = "";
txtQyteti.Text = "";
txtId.Text = "";
player++;
ticket++;
}
private void btnSave_Click(object sender, EventArgs e)
{
updateListbox("Ticket: " + ticket);
// Validimet per numrat e dhene
if (string.IsNullOrWhiteSpace(txtNr1.Text) || string.IsNullOrWhiteSpace(txtNr2.Text) || string.IsNullOrWhiteSpace(txtNr3.Text) || string.IsNullOrWhiteSpace(txtNr4.Text)
|| string.IsNullOrWhiteSpace(txtNr5.Text) || string.IsNullOrWhiteSpace(txtNr6.Text) || string.IsNullOrWhiteSpace(txtNr7.Text))
{
MessageBox.Show("Give some number at any of 7 numbers");
}
else
if (txtNr1.Text == txtNr2.Text || txtNr1.Text == txtNr3.Text || txtNr1.Text == txtNr4.Text || txtNr1.Text == txtNr5.Text || txtNr1.Text == txtNr6.Text || txtNr1.Text == txtNr7.Text)
{
MessageBox.Show("Choose different number from the others at 1st!");
txtNr1.Text = "";
}
else
if (txtNr2.Text == txtNr3.Text || txtNr2.Text == txtNr4.Text || txtNr2.Text == txtNr5.Text || txtNr2.Text == txtNr6.Text || txtNr2.Text == txtNr7.Text)
{
MessageBox.Show("Choose different number from the others at 2nd!");
txtNr2.Text = "";
}
else
if (txtNr3.Text == txtNr4.Text || txtNr3.Text == txtNr5.Text || txtNr3.Text == txtNr6.Text || txtNr3.Text == txtNr7.Text)
{
MessageBox.Show("Choose different number from the others at 3d!");
txtNr3.Text = "";
}
else
if (txtNr4.Text == txtNr5.Text || txtNr4.Text == txtNr6.Text || txtNr4.Text == txtNr7.Text)
{
MessageBox.Show("Choose different number from the others at 4th!");
txtNr4.Text = "";
}
else
if (txtNr5.Text == txtNr6.Text || txtNr5.Text == txtNr7.Text)
{
MessageBox.Show("Choose different number from the others at 5th!");
txtNr5.Text = "";
}
else
if (txtNr6.Text == txtNr7.Text)
{
MessageBox.Show("Choose different number from the others at 6th!");
txtNr6.Text = "";
}
else
if (Convert.ToInt32(txtNr1.Text) < 1 || Convert.ToInt32(txtNr1.Text) > 39)
{
txtNr1.Text = "";
MessageBox.Show("Please write 1st numbers because is out of range!");
}
else
if (Convert.ToInt32(txtNr2.Text) < 1 || Convert.ToInt32(txtNr2.Text) > 39)
{
txtNr2.Text = "";
MessageBox.Show("Please write 2nd numbers because is out of range!!");
}
else
if (Convert.ToInt32(txtNr3.Text) < 1 || Convert.ToInt32(txtNr3.Text) > 39)
{
txtNr3.Text = "";
MessageBox.Show("Please write 3d numbers because is out of range!!");
}
else
if (Convert.ToInt32(txtNr4.Text) < 1 || Convert.ToInt32(txtNr4.Text) > 39)
{
txtNr4.Text = "";
MessageBox.Show("Please write 4th numbers because is out of range!!");
}
else
if (Convert.ToInt32(txtNr5.Text) < 1 || Convert.ToInt32(txtNr5.Text) > 39)
{
txtNr5.Text = "";
MessageBox.Show("Please write 5th numbers because is out of range!!");
}
else
if (Convert.ToInt32(txtNr6.Text) < 1 || Convert.ToInt32(txtNr6.Text) > 39)
{
txtNr6.Text = "";
MessageBox.Show("Please write 6th numbers because is out of range!!");
}
else
if ((Convert.ToInt32(txtNr7.Text) < 1 || Convert.ToInt32(txtNr7.Text) > 39))
{
txtNr7.Text = "";
MessageBox.Show("Please write 7th numbers because is out of range!!");
}
else
{
updateListbox("Player " + txtEmri.Text + " choosed :" + txtNr1.Text + " " + txtNr2.Text + " " + txtNr3.Text +
" " + txtNr4.Text + " " + txtNr5.Text + " " + txtNr6.Text + " " + txtNr7.Text);
choosedNumbers.Add(txtNr1.Text);
choosedNumbers.Add(txtNr2.Text);
choosedNumbers.Add(txtNr3.Text);
choosedNumbers.Add(txtNr4.Text);
choosedNumbers.Add(txtNr5.Text);
choosedNumbers.Add(txtNr6.Text);
choosedNumbers.Add(txtNr7.Text);
}
nameOfPlayers.Add(txtEmri.Text);
}
}
}
I am assuming, since we don't know what is the code of your updateListbox() method, that it replaces everything in the display box.
As such, you would need something like this:
foreach (var i in emrateLojtarve)
{
if (teQelluar < 1)
{
updateListbox("Ne kete gjiro nuk ka fituar asnje lojtar!");
}
else
{
updateListbox("Player: " + i + " ka te qelluara " + teQelluar + " Numra: ");
updateListbox(string.Join(", ", numrateQelluar));
}
}
Related
Here is my code
do
{
tLINError = HardwareManage.readMessages();
if (tLINError.Equals(TLINError.errOK))
{
TLINRcvMsg tLINRcvMsg = HardwareManage.GetTLINMsg();
if (tLINRcvMsg.Data != null && tLINRcvMsg.Type.Equals(TLINMsgType.mstStandard))
{
byteFrame = tLINRcvMsg.FrameId;
if (byteFrame == 0x3D && tLINRcvMsg.Data[0] != 0x7F
&& tLINRcvMsg.ChecksumType.Equals(TLINChecksumType.cstEnhanced)
)
{
///*
if (tLINRcvMsg.Data[0] == pMsg.Data[0])
{
int k;
bool verifica = true;
for (k = 0; k < LAST_BYTE_RESPONSE.Length && verifica; k++)
{
if (tLINRcvMsg.Data[k + 1] != LAST_BYTE_RESPONSE[k])
{
verifica = false;
}
}
if (verifica)
{
listAddress.Add(hexValue);
}
}
//*/
}
}
}
} while (tLINError.Equals(TLINError.errOK) && byteFrame != 0x3D);
My PLin-Usb Api is of Peak-System (developed in 2019).
I cannot manage to insert the address found in the list, but with the debug in that point i manage to do it. Any suggestion?
I usually know how to replace a do..while loop with a for loop, but in this case variable check2 is used 2 times for different loops with got me confused on how to correctly replace it with for loop.
public static void RelayChat(ref int con, ref string Message)
{
string temp_SubName = "relaychat";
WriteSub(ref temp_SubName);
int check2 = 0;
if (Message.Length == 0) return;
var check = UserConToCheck(con);
if (CheckMute(get_UserName(check)) || get_UserChat(check) > 4) return;
if (get_UserChat(check) < 8) set_UserChat(check, get_UserChat(check) + 1);
if (Message.Length > 100) Message = Message.Substring(0, 99);
if (Message[0] == '!')
{
if (UserCommand(con, Message.Substring(1).Split(" ".ToCharArray()))) return;
}
if (PlayerAdapter.get_Reference(check).get_IsAdmin(1))
{
if (Message.Substring(0, 1) == "#")
{
string[] temp_cmds = Message.Substring(1).Split(",".ToCharArray());
admin.AdminCommand(PlayerAdapter.get_Reference(check), ref temp_cmds);
return;
}
}
if (Message.StartsWith(":g::", true, null))
{
do
{
check2++;
var guild1 = get_UserGuild(check);
var guild2 = get_UserGuild(check2);
if (guild1 == null || guild2 == null || guild1.ToLower() != guild2.ToLower()) continue;
var thisuser = get_UserName(check);
var targetuser = get_UserName(check2);
var found = targetuser != null && thisuser != null &&
IgnoreUserList.ContainsKey(targetuser) &&
IgnoreUserList[targetuser].Contains(thisuser);
if (found == false)
{
Winsock.PrivMsg(get_UserCon(check2), "14,1,[ " + get_UserGuild(check2) + " ] Chat - " + get_UserName(check) + " : " + Message.Substring(4));
}
} while (check2 != UserMax);
return;
}
if (check <= 0) return;
do
{
check2++;
bool found = false;
var user = get_UserName(check2);
if (user != null && IgnoreUserList.ContainsKey(user))
{
found = Convert.ToBoolean(IgnoreUserList[get_UserName(check2)].Contains(get_UserName(check)));
}
if (found) return;
if (get_UserLanded(check2) != get_UserLanded(check)) return;
if (get_UserLanded(check2))
{
if (get_UserInBar(check2) == false &&
get_UserInUniversalBar(check2) == false) return;
if (get_UserInUniversalBar(check2) && get_UserInUniversalBar(check))
{
Winsock.PrivMsg(get_UserCon(check2), "13,0,[ " + get_UserName(check) + " ] : " + Message);
}
else if (get_UserInBar(check2) && get_UserInBar(check))
{
if (get_UserLastPlanet(check2) !=
get_UserLastPlanet(check)) return;
Winsock.PrivMsg(get_UserCon(check2), "13,0,[ " + get_UserName(check) + " ] : " + Message);
}
}
else if (get_UserLanded(check2) == false)
{
if (get_UserSector(check2) != get_UserSector(check)) return;
if (get_UserZone(check2) != get_UserZone(check)) return;
Winsock.PrivMsg(get_UserCon(check2), "13,0,[ " + get_UserName(check) + " ] : " + Message);
}
} while (check2 != UserMax);
}
I know that the function might be a lot complex, but please ignore that fact and focus on just the do..while loops. Thank you!
Just declare the for loop to use the existing variable.
int check2 = 0;
if (Message.StartsWith(":g::", true, null))
{
for (; check2 < UserMax; check2++)
{
// Do stuff
}
return;
}
if (check <= 0) return;
for (; check2 < 200; check2++)
{
// Do stuff
}
This question already has answers here:
Generating random, unique values C#
(17 answers)
Closed 5 years ago.
1.This is what i've got this so far
2.Its suppposed to randomize the numbers on the buttons when it starts. But it still generates duplicates (and i dont want duplicates).
I use Visual studio 2012 C# for this
Its only supposed to do it once i startup the program. So its a one time randomize
Random rand = new Random();
int RandomOne = rand.Next(0, 10);
int RandomTwo = rand.Next(0, 10);
int RandomThree = rand.Next(0, 10);
int RandomFour = rand.Next(0, 10);
int RandomFive = rand.Next(0, 10);
int RandomSix = rand.Next(0, 10);
int RandomSeven = rand.Next(0, 10);
int RandomEight = rand.Next(0, 10);
int RandomNine = rand.Next(0, 10);
int RandomZero = rand.Next(0, 10);
btnOneNgra.Text = Convert.ToString(RandomOne);
if ((RandomTwo == RandomOne) || (RandomTwo == RandomNine) || (RandomTwo == RandomThree) || (RandomTwo == RandomFour)
|| (RandomTwo == RandomFive) || (RandomTwo == RandomSix) || (RandomTwo == RandomSeven) || (RandomTwo == RandomEight) || (RandomTwo == RandomZero))
{
RandomTwo = rand.Next(0, 10);
}
else
{
btnTwoNgra.Text = Convert.ToString(RandomTwo);
}
if ((RandomThree == RandomOne) || (RandomThree == RandomTwo) || (RandomThree == RandomNine) || (RandomThree == RandomFour)
|| (RandomThree == RandomFive) || (RandomThree == RandomSix) || (RandomThree == RandomSeven) || (RandomThree == RandomEight) || (RandomThree == RandomZero))
{
RandomThree = rand.Next(0, 10);
}
else
{
btnThreeNgra.Text = Convert.ToString(RandomThree);
}
if ((RandomFour == RandomOne) || (RandomFour == RandomTwo) || (RandomFour == RandomThree) || (RandomFour == RandomNine)
|| (RandomFour == RandomFive) || (RandomFour == RandomSix) || (RandomFour == RandomSeven) || (RandomFour == RandomEight) || (RandomFour == RandomZero))
{
RandomFour = rand.Next(0, 10);
}
else
{
btnFourNgra.Text = Convert.ToString(RandomFour);
}
if ((RandomFive == RandomOne) || (RandomFive == RandomTwo) || (RandomFive == RandomThree) || (RandomFive == RandomFour)
|| (RandomFive == RandomNine) || (RandomFive == RandomSix) || (RandomFive == RandomSeven) || (RandomFive == RandomEight) || (RandomFive == RandomZero))
{
RandomFive = rand.Next(0, 10);
}
else
{
btnFiveNgra.Text = Convert.ToString(RandomFive);
}
if ((RandomSix == RandomOne) || (RandomSix == RandomTwo) || (RandomSix == RandomThree) || (RandomSix == RandomFour)
|| (RandomSix == RandomFive) || (RandomSix == RandomNine) || (RandomSix == RandomSeven) || (RandomSix == RandomEight) || (RandomSix == RandomZero))
{
RandomSix = rand.Next(0, 10);
}
else
{
btnSixNgra.Text = Convert.ToString(RandomSix);
}
if ((RandomSeven == RandomOne) || (RandomSeven == RandomTwo) || (RandomSeven == RandomThree) || (RandomSeven == RandomFour)
|| (RandomSeven == RandomFive) || (RandomSeven == RandomSix) || (RandomSeven == RandomNine) || (RandomSeven == RandomEight) || (RandomSeven == RandomZero))
{
RandomSeven = rand.Next(0, 10);
}
else
{
btnSevenNgra.Text = Convert.ToString(RandomSeven);
}
if ((RandomEight == RandomOne) || (RandomEight == RandomTwo) || (RandomEight == RandomThree) || (RandomEight == RandomFour)
|| (RandomEight == RandomFive) || (RandomEight == RandomSix) || (RandomEight == RandomSeven) || (RandomEight == RandomNine) || (RandomEight == RandomZero))
{
RandomEight = rand.Next(0, 10);
}
else
{
btnEightNgra.Text = Convert.ToString(RandomEight);
}
if ((RandomNine == RandomOne) || (RandomNine == RandomTwo) || (RandomNine == RandomThree) || (RandomNine == RandomFour)
|| (RandomNine == RandomFive) || (RandomNine == RandomSix) || (RandomNine == RandomSeven) || (RandomNine == RandomEight) || (RandomNine == RandomZero))
{
RandomNine = rand.Next(0, 10);
}
else
{
btnNineNgra.Text = Convert.ToString(RandomNine);
}
if ((RandomZero == RandomOne) || (RandomZero == RandomTwo) || (RandomZero == RandomThree) || (RandomZero == RandomFour)
|| (RandomZero == RandomFive) || (RandomZero == RandomSix) || (RandomZero == RandomSeven) || (RandomZero == RandomEight) || (RandomZero == RandomNine))
{
RandomZero = rand.Next(0, 10);
}
else
{
btnZeroNgra.Text = Convert.ToString(RandomZero);
}
The approach for this case should be to create ten numbers in a list and then take one by one to avoid duplication, something like the following:
List<int> nums = new List<int>(Enumerable.Range(0, 10));
private int getNumber(){
Random rand = new Random();
int index = rand.Next(0, nums.Count);
int num = nums[index];
nums.RemoveAt(index);
return num;
}
You might need to be careful though, it cannot be called more than 10 times... You might want to create little error handler like:
private int getNumber(){
if(nums.Count >= 0)
return -1; //means not available
Random rand = new Random();
int index = rand.Next(0, nums.Count);
int num = nums[index];
nums.RemoveAt(index);
return num;
}
Maybe you should try with HashSet:
HashSet<int> numbers = new HashSet<int>();
Random randomizer = new Random();
while (numbers.Count < 10)
{
numbers.Add(randomizer.Next(0, 10));
}
HashSet would make sure that all the values are unique.
I'm trying to make a basic noughts and crosses game in c#.
So far I've made the grid using buttons which's text changes when it is pressed depending which player's turn it is.
The part which I am stuck on is checking if any of the players has won, I've written this however it doesn't seem to do anything.
private void Form1_Load(object sender, EventArgs e)
{
if (button1.Text == "X" && button5.Text == "X" && button9.Text == "X")
{
MessageBox.Show("Player", player_turntxt.Text + " wins");
Application.Restart();
}
}
private void button1_Click(object sender, EventArgs e)
{
int Player_Turn = Convert.ToInt32(player_turntxt.Text);
if (Player_Turn == 1)
{
button1.Text = "X";
player_turntxt.Text = "2";
button1.Enabled = false;
return;
}
else
{
button1.Text = "O";
player_turntxt.Text = "1";
button1.Enabled = false;
return;
}
(The Application.Restart(); is just a temporary method of checking if it works.)
This is just one of 8 statements which I'll have to make as conditions for victory, any idea where I'm going wrong?
Update:
public void CheckForWinner(int x)
{
if (button1.Text == "X" && button5.Text == "X" && button9.Text == "X")
{
x = 1;
}
else if (button3.Text == "X" && button5.Text == "X" && button7.Text == "X")
{
x = 1;
}
else if (button1.Text == "X" && button4.Text == "X" && button7.Text == "X")
{
x = 1;
}
else if (button2.Text == "X" && button5.Text == "X" && button8.Text == "X")
{
x = 1;
}
else if (button3.Text == "X" && button6.Text == "X" && button9.Text == "X")
{
x = 1;
}
else if (button1.Text == "X" && button2.Text == "X" && button3.Text == "X")
{
x = 1;
}
else if (button4.Text == "X" && button5.Text == "X" && button6.Text == "X")
{
x = 1;
}
else if (button7.Text == "X" && button8.Text == "X" && button9.Text == "X")
{
x = 1;
}
if (button1.Text == "O" && button5.Text == "O" && button9.Text == "O")
{
x = 2;
}
else if (button3.Text == "O" && button5.Text == "O" && button7.Text == "O")
{
x = 2;
}
else if (button1.Text == "O" && button4.Text == "O" && button7.Text == "O")
{
x = 2;
}
else if (button2.Text == "O" && button5.Text == "O" && button8.Text == "O")
{
x = 2;
}
else if (button3.Text == "O" && button6.Text == "O" && button9.Text == "O")
{
x = 2;
}
else if (button1.Text == "O" && button2.Text == "O" && button3.Text == "O")
{
x = 2;
}
else if (button4.Text == "O" && button5.Text == "O" && button6.Text == "O")
{
x = 2;
}
else if (button7.Text == "O" && button8.Text == "O" && button9.Text == "O")
{
x = 2;
}
}
You should create a method to check if any player has won, and run it at the end of everyone of your "button clicks".
I algo suggest you to remove the "return"'s from your button clicks. They can introduce unexpected behaviors sometimes, like ending the function before you execute the line of code that calls the method to check if someone has won.
Something like this:
private void button1_Click(object sender, EventArgs e)
{
int Player_Turn = Convert.ToInt32(player_turntxt.Text);
if (Player_Turn == 1)
{
button1.Text = "X";
player_turntxt.Text = "2";
button1.Enabled = false;
}
else
{
button1.Text = "O";
player_turntxt.Text = "1";
button1.Enabled = false;
}
CheckIfSomeoneHasWon();
}
Let's discuss the implementation of CheckIfSomeoneHasWon. I figure that there are several ways of doing it. We could create a bidimensional array with the values of the buttons, and iterate it. In fact, I will do it that way. Your way works too, but we would have to write a lot. This is what I came up with:
static readonly string _player1_symbol = "X";
static readonly string _player2_symbol = "O";
static void CheckIfSomeoneHasWon()
{
string[,] userChoices = BuildUserChoices();
string winner = CheckWhoWon(userChoices);
if (winner != null)
{
// Somebody won! Display message and start over
}
}
private static string CheckWhoWon(string[,] values)
{
// Horizontal checks
for (int i = 0; i < 3; i++)
{
if (values[i, 0] == values[i, 1] && values[i, 1] == values[i, 2])
{
return (values[i, 0] == _player1_symbol) ? "player 1" : "player 2";
}
}
// Vertical checks
for (int i = 0; i < 3; i++)
{
if (values[0, i] == values[1, i] && values[1,i] == values[2,i])
{
return (values[i, 0] == _player1_symbol) ? "player 1" : "player 2";
}
}
// Diagonal checks
if (values[0, 0] == values[1, 1] && values[1, 1] == values[2, 2])
{
return (values[0, 0] == _player1_symbol) ? "player 1" : "player 2";
}
if (values[0, 2] == values[1, 1] && values[1, 1] == values[2, 0])
{
return (values[1, 1] == _player1_symbol) ? "player 1" : "player 2";
}
// No one has won yet
return null;
}
private static string[,] BuildUserChoices()
{
var values = new string[3, 3];
values[0, 0] = button1.Text;
values[0, 1] = button2.Text;
values[0, 2] = button3.Text;
// and so on...
// If a button has not been click, they must have a unique text, like a number
return values;
}
You need to check if a player wins after each turn. Right now you are checking it once, after the form loaded.
I understand that when Thread.Sleep is being executed, the buttons on my GUI are not able to be clicked on.
Is there any other ways to delay my codes from flowing yet still able to click on my buttons on the GUI?
For example right now after my codes execute Thread.Sleep(10000); and within this 10 seconds i'm not able to click on my button1 event, is there anyway that I can still click on my button1 event within these 10 seconds?
private void displaydata_event2(object sender, EventArgs e)
{
txt_data.AppendText(in_data + "\n");
string inStr;
inStr = in_data;
//MessageBox.Show(inStr.Length.ToString());
if (inStr.Length == 12)
{
int indexOfSpace = inStr.IndexOf(' ');
string Patient = inStr.Substring(indexOfSpace + 1);
int rx = 0;
int selected = 0;
txtData1.Text = Patient;
rx = Convert.ToInt16(Patient);
selected = Convert.ToInt16(txt_pnorec.Text);
if (rx != selected)
{
MessageBox.Show("Please check patient settings");
}
}
else if (inStr.Length == 24)
{
label2.Text = "Patient is not selected!";
label2.BackColor = Color.Red;
}
else if (inStr.Length == 10)
{
int indexOfSpace = inStr.IndexOf(':');
string Temp = inStr.Substring(indexOfSpace + 1);
txtData2.Text = Temp;
double tempflo;
tempflo = Convert.ToDouble(Temp);
if (tempflo > 20)
{
lbl_temp.Text = "Fever";
lbl_temp.BackColor = Color.Red;
}
}
else if (inStr.Length == 9)
{
int indexOfSpace = inStr.IndexOf(':');
string ECG = inStr.Substring(indexOfSpace + 1);
txtData3.Text = ECG;
}
else if (inStr.Length == 19 || inStr.Length == 20)
{
int indexOfSpace = inStr.IndexOf(':');
string Systolic = inStr.Substring(indexOfSpace + 1);
txtData4.Text = Systolic;
}
else if (inStr.Length == 21 || inStr.Length == 22)
{
int indexOfSpace = inStr.IndexOf(':');
string Diastolic = inStr.Substring(indexOfSpace + 1);
txtData5.Text = Diastolic;
}
else if (inStr.Length == 16)
{
int indexOfSpace = inStr.IndexOf(':');
string Pulse = inStr.Substring(indexOfSpace + 1);
txtData6.Text = Pulse;
}
else if (inStr.Length == 23 || inStr.Length == 17 || inStr.Length == 27 || inStr.Length == 30 || inStr.Length == 35 || inStr.Length == 29)
{
lbl_bp.Text = inStr;//to display status of BP (Normal,prehypotension etc)
string bp;
bp = inStr;
if (bp.Length == 23 || bp.Length == 27 || bp.Length == 31 || bp.Length == 35 || bp.Length == 30)
{
lbl_bp.BackColor = Color.Red;
}
else if (bp.Length == 17)
{
lbl_bp.BackColor = Color.LightGray;
}
}
else if (inStr.Length == 32 || inStr.Length == 25 || inStr.Length == 34 || inStr.Length == 33 || inStr.Length == 26 || inStr.Length == 31)
{
int indexOfSpace = inStr.IndexOf(':');
string Acc = inStr.Substring(indexOfSpace + 1);
txtData7.Text = Acc;
string test = inStr;
if (test.Length == 25 || test.Length == 34 || test.Length == 33 || test.Length == 26)
{
label21.Text = "Check on patient!";
label21.BackColor = Color.Red;
}
else if (test.Length == 32)
{
label21.Text = "";
label21.BackColor = Color.LightGray;
}
}
else
{
}
if (txtData1.Text != "" && txtData2.Text != "" && txtData3.Text != "" && txtData4.Text != "" && txtData5.Text != "" && txtData6.Text != "" && txtData7.Text != "")
{
try
{
connection2.Open();
OleDbCommand command2 = new OleDbCommand();
command2.Connection = connection2;
command2.CommandText = "insert into MedicalRecord (PatientNumber,FirstName,LastName,IC,Temperature,ECG,Systolic,Diastolic,Pulse) values('" + txt_pnorec.Text + "','" + txt_fnamerec.Text + "','" + txt_lnamerec.Text + "','" + txt_icrec.Text + "','" + txtData2.Text + "','" + txtData3.Text + "','" + txtData4.Text + "','" + txtData5.Text + "','" + txtData6.Text + "')";
command2.ExecuteNonQuery();
MessageBox.Show("Info Stored");
connection2.Close();
txtData1.Text = "";
txtData2.Text = "";
txtData3.Text = "";
txtData4.Text = "";
txtData5.Text = "";
txtData6.Text = "";
txtData7.Text = "";
Thread.Sleep(interval);
MessageBox.Show("Start");
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex);
}
txtData1.Text = "";
txtData2.Text = "";
txtData3.Text = "";
txtData4.Text = "";
txtData5.Text = "";
txtData6.Text = "";
txtData7.Text = "";
}
}
Thanks in advance.
There are multiple ways to achieve this. One example is to use a task with a delay:
Task.Delay(10000).ContinueWith(x =>
{
//Place the code you want delayed here.
});
Another example could be to use a BackgroundWorker which is made for this exact purpose.
you can use Async and Await
here is a good tutorial in combination with an GUI:
https://www.youtube.com/watch?v=MCW_eJA2FeY
you need to declare your function as async
public async void Foo()
{
...
}
than you can use:
await Task.Delay(10000);
it will release you GUI for the whole Delay and you can use your GUI while the Delay is waiting.
Task.Delay(10000).ContinueWith(x =>
{
//...
});
Have a look at Task.Delay and ContinueWith.
You can use Windows.Forms.Timer to execute something after delay... (with no UI thread freezing). Split your code on two parts. 1. Before delay 2. After delay
public partial class form1 : Form
{
// i used namespace to ensure that we use 'correct' Timer and we do not
// confuse it with System.Timers.Timer or System.Threading.Timer
System.Windows.Forms.Timer tmrDelay;
void SomeMethodWithDelay()
{
// code before delay here
tmrDelay.Enabled = true;
tmrDelay.Tick += Timer_Tick;
}
private void Timer_Tick(object sender, EventArgs e)
{
Thread.Sleep(5000);
// your code here
// disables timer to stop it
tmrDelay.Enabled = false;
}
}
Benefit from using Timer is that it is a native windows forms tool that was specially designed to help with this kind of problems.
However you can still use modern things like Tasks, for example : Task.Factory.StartNew(() => { Thread.Sleep(5000); // your method logic here });