I have put random numbers into arrays but now I want to prevent it from being shown double in the Listbox. I already got a beginning to start with:
private bool InArray(int getal, int[] getallen, int aantal)
{
}
I think the solution is something like when the number is already in it return true and else just keep going with the code, but I can't think of how I can do this.
This is my code:
namespace Trekking
{
public partial class Form1 : Form
{
private Trekking trekking;
public Form1()
{
InitializeComponent();
btnLaatZien.Enabled = false;
btnSerie.Enabled = false;
btnSorteer.Enabled = false;
btnStart.Enabled = true;
btnStop.Enabled = false;
btnTrek.Enabled = false;
}
private void btnStart_Click(object sender, EventArgs e)
{
int AantalGewenst = Convert.ToInt32(tbInvoerAantalGewenst.Text);
int Maxwaarde = Convert.ToInt32(tbInvoerMaxwaarde.Text);
trekking = new Trekking(Maxwaarde, AantalGewenst);
btnTrek.Enabled = true;
btnStop.Enabled = true;
btnStart.Enabled = false;
if (Maxwaarde > 90)
{
MessageBox.Show("Uw getal mag niet boven de 90 zijn!");
btnStart.Enabled = true;
btnTrek.Enabled = false;
btnStop.Enabled = false;
}
else if (Maxwaarde < 0)
{
MessageBox.Show("Dit aantal is niet mogelijk!");
btnStart.Enabled = true;
btnTrek.Enabled = false;
btnStop.Enabled = false;
}
else if (AantalGewenst > 45)
{
MessageBox.Show("Uw getal mag niet boven de 45 zijn!");
btnStart.Enabled = true;
btnTrek.Enabled = false;
btnStop.Enabled = false;
}
if (AantalGewenst < 1)
{
MessageBox.Show("Dit aantal is niet mogelijk!");
btnStart.Enabled = true;
btnTrek.Enabled = false;
btnStop.Enabled = false;
}
else if (Maxwaarde / AantalGewenst < 2)
{
MessageBox.Show("Uw maxwaarde moet minstens het dubbele van Aantal Gewenst zijn!");
btnStart.Enabled = true;
btnTrek.Enabled = false;
btnStop.Enabled = false;
}
else
{
if (AantalGewenst <= 45)
btnStart.Enabled = false;
btnTrek.Enabled = true;
btnStop.Enabled = true;
}
}
public void getSingleNumber(int hoeveel)
{
int Getal = trekking.GeefGetal(hoeveel);
lbResultaat.Items.Add(Getal);
}
public void getTrekkingData()
{
for (int p = 0; p < trekking.AantalGewenst; p++)
{
int alleGetallen = trekking.GeefGetal(p);
lbResultaat.Items.Add(alleGetallen);
}
}
int count = 0;
private void btnTrek_Click(object sender, EventArgs e)
{
int gewenst = trekking.AantalGewenst;
label3.Text = Convert.ToString(count);
btnStop.Enabled = true;
btnSerie.Enabled = false;
trekking.TrekGetal();
getSingleNumber(count);
count++;
if (count == trekking.AantalGewenst)
{
MessageBox.Show("Alle gewenste trekkingen zijn uitgevoerd");
btnTrek.Enabled = false;
btnStop.Enabled = true;
btnSerie.Enabled = false;
}
}
private void btnStop_Click(object sender, EventArgs e)
{
lbResultaat.Items.Clear();
btnLaatZien.Enabled = false;
btnSerie.Enabled = false;
btnSorteer.Enabled = false;
btnStart.Enabled = true;
btnStop.Enabled = false;
btnTrek.Enabled = false;
tbInvoerAantalGewenst.Enabled = true;
tbInvoerMaxwaarde.Enabled = true;
count = 0;
}
private void tbInvoerMaxwaarde_KeyPress(object sender, KeyPressEventArgs e)
{
char ch = e.KeyChar;
e.Handled = !(Char.IsDigit(ch) || (ch == '-') || (ch < ' '));
}
private void k(object sender, KeyPressEventArgs e)
{
char ch = e.KeyChar;
e.Handled = !(Char.IsDigit(ch) || (ch == '-') || (ch < ' '));
}
private bool InArray(int getal, int[] getallen, int aantal)
{
}
}
}
The class:
namespace Trekking
{
class Trekking
{
//attributes
private Random random;
private int[] getallen;
//properties
public int Maxwaarde { get; private set; } //maximum waarde van te trekken getal
public int AantalGetrokken { get; private set; } //aantal getrokken getallen
public int AantalGewenst { get; private set; } //aantal te trekken getallen
public bool IsTenEinde { get; private set; } //true als alle getallen gerokken
//constructor en methoden
public Trekking(int Maxwaarde, int AantalGewenst)
{
this.Maxwaarde = Maxwaarde;
this.AantalGewenst = AantalGewenst;
AantalGetrokken = 0;
IsTenEinde = false;
random = new Random();
getallen = new int[AantalGewenst];
}
//methods
public void TrekGetal()
{
int erbijArray;
for (int i = 0; i < AantalGewenst; i++)
{
erbijArray = random.Next(1, Maxwaarde);
getallen[i] = erbijArray;
AantalGetrokken++;
}
}
public int GeefGetal(int number)
{
return getallen[number];
}
//sorteert getrokken getallen in array "getallen"
public void Sort()
{
Array.Sort(getallen);
}
}
}
I simplified your problem (leaving out min, max, max number etc).
Basically, you can keep a list of things you already encountered:
public class Lottery
{
public HashSet<int> _previousNumbers = new HashSet<int>();
private Random random = new Random();
public int GetNextNumber()
{
int next;
do
{
next = random.Next();
}
while (_previousNumbers.Contains(next));
_previousNumbers.Add(next);
return next;
}
}
A set does not contain duplicates and is efficient in its Contains implementation.
Related
I'm taking over a project on Xamarin.
It work on android and I want it to work on iOS.
Initially, it have been done for that so I expected it work with maybe only settings ?
Anyway it work on Android but not on iOS.
I have this code :
public App()
{
Debug.WriteLine(Current.Properties); //return default value
try
{
ViewModelLocator.MainViewModel.RestoreState(Current.Properties);
BindingContext = ViewModelLocator.MainViewModel;
MainTabPage = new SGC400Tab();
MainPage = MainTabPage;
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
public static class ViewModelLocator
{
private static GlobalViewModel _myViewModel = new GlobalViewModel();
public static GlobalViewModel MainViewModel
{
get
{
return _myViewModel;
}
}
}
public class GlobalViewModel : INotifyPropertyChanged
{
public void RestoreState(IDictionary<string, object> dictionary)
{
Thing1.SelectedUnitySystem_Presure = GetDictionaryEntry(dictionary, "SavedUnitySystem_Pression", "Bars");
Thing1.SelectedUnitySystem_Flow = GetDictionaryEntry(dictionary, "SavedUnitySystem_Debit", "m3/h");
Thing1.SelectedUnitySystem_Temperature = GetDictionaryEntry(dictionary, "SavedUnitySystem_Temperature", "°C");
Thing1.SelectedLanguageKey = GetDictionaryEntry(dictionary, "SavedLanguage", "en");
}
}
Which return an error :
System.NullReferenceException on line :
private static GlobalViewModel _myViewModel = new GlobalViewModel();
I'm a bit puzzled by the fact it work on android... but not on iOS...
I have to tell I'm pretty new on Xamarin, may you give me some pointer ?
Thank you in advance !
PS : Class GlobalViewModel here :
public class GlobalViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
//#####################################
//Enneigeur
public Enneigeur _Enneigeur1 = new Enneigeur();
public Enneigeur Enneigeur1
{
get { return _Enneigeur1; }
set
{
_Enneigeur1 = value;
}
}
//Com
public ComSGC400 _comSGC400 = new ComSGC400();
public ComSGC400 ComSGC400
{
get { return _comSGC400; }
set { _comSGC400 = value; }
}
public const int TIMOUT_COM_MS = 500;
public const int DELAI_ENTRE_TRAME_MS = 1000;
//#####################################
//Bluetooth
public ObservableCollection<string> ListOfDevices { get; set; } = new ObservableCollection<string>();
public string inputBuffer;
public string SelectedBthDevice { get;set; } = "";
private bool _isConnected { get; set; } = false;
public bool IsConnected {
get { return _isConnected; }
set
{
_isConnected = value;
if (_isConnected == true)
{
((App)Application.Current).AddPages();
} else
{
((App)Application.Current).RemovePages();
}
}
}
private bool _isSelectedBthDevice { get { if (string.IsNullOrEmpty(SelectedBthDevice)) return false; return true; }}
public bool IsConnectEnabled { get { if (_isSelectedBthDevice == false) return false; return !IsConnected; }}
public bool IsDisconnectEnabled { get { if (_isSelectedBthDevice == false) return false; return IsConnected; } }
public Color ConnectBackgroundcolor { get { if (IsConnectEnabled) return Color.Green; return Color.FromRgb(48, 48, 48); } }
public Color DisconnectBackgroundColor { get { if (IsDisconnectEnabled) return Color.Red; return Color.FromRgb(48, 48, 48); } }
public bool IsConnectionInit { get { if (EtatGrafcet_loop < 2 || IsConnected == false ) return false; return true; } }
public bool IsModeManuOK { get { if (EtatGrafcet_loop >= 2 && IsConnected == true && _Enneigeur1.Manu == true) return true; return false; } }
public bool IsBoutonRotaOK { get { if (EtatGrafcet_loop >= 2 && IsConnected == true && ( _Enneigeur1._VersionSGC400 > 10213 || _Enneigeur1.Manu == true)) return true; return false; } }
public bool IsPickerEnabled { get { return !IsConnected; }}
public bool IsBalayageDispo { get { if (EtatGrafcet_loop < 2 || IsConnected == false || _Enneigeur1.OptionBalayageDispo == false) return false; return true; } }
public LocalizedResources Resources { get; private set;}
public Color Mode_Manu_Button_Text_Color
{
get
{
if (EtatGrafcet_loop < 2)
return Color.Gray;
else
return Color.White;
}
}
public Color Mode_Manu_Button_Color {
get {
if (EtatGrafcet_loop < 2)
return Color.FromRgb(48, 48, 48);
else
{
if (_Enneigeur1.ModeMarche == 1) return Color.Green; return Color.Black;
}
}
}
public Color Mode_Stop_Button_Text_Color
{
get
{
if (EtatGrafcet_loop < 2)
return Color.Gray;
else
return Color.White;
}
}
public Color Mode_Stop_Button_Color {
get
{
if (EtatGrafcet_loop < 2)
return Color.FromRgb(48, 48, 48);
else
{
if (_Enneigeur1.ModeMarche == 2) return Color.Green; return Color.Black;
}
}
}
public Color Mode_Forcage_Button_Text_Color
{
get
{
if (EtatGrafcet_loop < 2)
return Color.Gray;
else
return Color.White;
}
}
public Color Mode_Forcage_Button_Color
{
get
{
if (EtatGrafcet_loop < 2)
return Color.FromRgb(48, 48, 48);
else
{
if (_Enneigeur1.ModeMarche == 0) return Color.Green; return Color.Black;
}
}
}
private CancellationTokenSource _ct { get; set; }
private int EtatGrafcet_loop { get; set; }
private DateTime timer_send = DateTime.Now;
private bool envoiContinu = false;
private string envoiWrite = "";
private async Task Loop()
{
string bufferEnvoi = "";
bool res;
int erreur_cryptage = 0;
EtatGrafcet_loop = 0;
int reponseLen = 0;
_Enneigeur1.ResetValues();
_ct = new CancellationTokenSource();
ComSGC400.AddrSGC400 = Convert.ToUInt16(SelectedBthDevice.Substring(5));
while (_ct.IsCancellationRequested == false)
{
switch (EtatGrafcet_loop)
{
case 0://Envoi trame clé crypté
if (DateTime.Now > timer_send.AddMilliseconds(DELAI_ENTRE_TRAME_MS)) //Temps entre trames
{
//Test d'echange de clé de cryptage
inputBuffer = "";
reponseLen = ComSGC400.Create_Trame_getKey(ref bufferEnvoi);
if (bufferEnvoi.Length > 0)
{
Xamarin.Forms.MessagingCenter.Send<App, string>((App)Xamarin.Forms.Application.Current, "WriteDatas", bufferEnvoi);
timer_send = DateTime.Now;
EtatGrafcet_loop = 1;
}
}
break;
case 1: //attente reception clé crypté
if (DateTime.Now > timer_send.AddMilliseconds(TIMOUT_COM_MS)){ EtatGrafcet_loop = 0; break; } //timeout
if (inputBuffer != null)
{
ComSGC400.Trame_RechercheDebutTrame(ref inputBuffer);
if (inputBuffer.Length >= reponseLen)
{
inputBuffer = inputBuffer.Substring(0, reponseLen);
res = ComSGC400.Update_ProtectionKey( inputBuffer);
if (res == true)
{
//cle cryptage OK
bufferEnvoi = "";
EtatGrafcet_loop = 2;
erreur_cryptage = 0;
}
else
{
//cle cryptage non ok
bufferEnvoi = "";
EtatGrafcet_loop = 0;
}
inputBuffer = "";
}
}
break;
case 2: //envoi trame readMain
if (envoiWrite != "")
EtatGrafcet_loop = 10; //envoi write
else
{
if (DateTime.Now > timer_send.AddMilliseconds(DELAI_ENTRE_TRAME_MS)) //Temps entre trames
{
reponseLen = ComSGC400.Create_Trame_ReadMain(ref bufferEnvoi);
if (bufferEnvoi.Length > 0)
{
inputBuffer = "";
Xamarin.Forms.MessagingCenter.Send<App, string>((App)Xamarin.Forms.Application.Current, "WriteDatas", bufferEnvoi);
timer_send = DateTime.Now;
EtatGrafcet_loop = 3;
}
}
}
break;
case 3: //attente reponse trame readMain
if (DateTime.Now > timer_send.AddMilliseconds(TIMOUT_COM_MS)) {
EtatGrafcet_loop = 20; break;
} //timeout
if (inputBuffer != null)
{
ComSGC400.Trame_RechercheDebutTrame(ref inputBuffer);
if (inputBuffer.Length >= reponseLen)
{
inputBuffer = inputBuffer.Substring(0, reponseLen);
res = ComSGC400.Update_Enneigeur( inputBuffer, ref _Enneigeur1);
if (res == true)
{
//Message OK
bufferEnvoi = "";
EtatGrafcet_loop = 4;//Passage readCom
erreur_cryptage = 0;
_Enneigeur1.LastRead = DateTime.Now;
}
else
{
//Message NON OK
EtatGrafcet_loop = 20;
}
inputBuffer = "";
}
}
break;
case 4: //envoi trame readCom
if (envoiWrite != "")
EtatGrafcet_loop = 10; //envoi write
else
{
if (DateTime.Now > timer_send.AddMilliseconds(50)) //Temps entre trames
{
reponseLen = ComSGC400.Create_Trame_ReadCom(ref bufferEnvoi);
if (bufferEnvoi.Length > 0)
{
inputBuffer = "";
Xamarin.Forms.MessagingCenter.Send<App, string>((App)Xamarin.Forms.Application.Current, "WriteDatas", bufferEnvoi);
timer_send = DateTime.Now;
EtatGrafcet_loop = 5;
}
}
}
break;
case 5: //attente reponse trame readCom
if (DateTime.Now > timer_send.AddMilliseconds(TIMOUT_COM_MS)) {
EtatGrafcet_loop = 21; break;
} //timeout
if (inputBuffer != null)
{
ComSGC400.Trame_RechercheDebutTrame(ref inputBuffer);
if (inputBuffer.Length >= reponseLen)
{
inputBuffer = inputBuffer.Substring(0, reponseLen);
res = ComSGC400.Update_Enneigeur( inputBuffer, ref _Enneigeur1);
if (res == true)
{
//Message OK
bufferEnvoi = "";
EtatGrafcet_loop = 2; //Retour read main
erreur_cryptage = 0;
_Enneigeur1.LastRead = DateTime.Now;
if (_Enneigeur1.Reset)
Send_value_bluetooth("reset", false);
}
else
{
//Message NON OK
EtatGrafcet_loop = 21;
}
inputBuffer = "";
}
}
break;
case 10: //envoi trame Write
inputBuffer = "";
Xamarin.Forms.MessagingCenter.Send<App, string>((App)Xamarin.Forms.Application.Current, "WriteDatas", envoiWrite);
timer_send = DateTime.Now;
EtatGrafcet_loop =11;
break;
case 11: //attente reponse trame Write
if (DateTime.Now > timer_send.AddMilliseconds(TIMOUT_COM_MS)) { EtatGrafcet_loop = 20; break; } //timeout
if (inputBuffer != null)
{
ComSGC400.Trame_RechercheDebutTrame(ref inputBuffer);
if (inputBuffer.Length >= 16)
{
bufferEnvoi = "";
if (envoiContinu)
{
EtatGrafcet_loop = 10; //envoi continu
}
else
{
envoiWrite = "";
EtatGrafcet_loop = 2; //Retour read main
}
erreur_cryptage = 0;
_Enneigeur1.LastWrite = DateTime.Now;
inputBuffer = "";
}
}
break;
case 20://Erreur de reception trame readMain
bufferEnvoi = "";
erreur_cryptage = erreur_cryptage + 1;
envoiWrite = "";
if (erreur_cryptage > 3)
{
_Enneigeur1.ResetValues();
erreur_cryptage = 0;
EtatGrafcet_loop = 0;
}
else
{
EtatGrafcet_loop = 2;
}
break;
case 21://Erreur de reception trame readCom
bufferEnvoi = "";
erreur_cryptage = erreur_cryptage + 1;
envoiWrite = "";
if (erreur_cryptage > 3)
{
_Enneigeur1.ResetValues();
erreur_cryptage = 0;
EtatGrafcet_loop = 0;
}
else
{
EtatGrafcet_loop = 4;
}
break;
default:
EtatGrafcet_loop = 0;
break;
}
await Task.Delay(10);
}
EtatGrafcet_loop = 0;
}
public void Send_value_bluetooth(string nom_param, bool value)
{
if (value == true) Send_value_bluetooth( nom_param, 1); else Send_value_bluetooth(nom_param, 0);
}
public void Send_value_bluetooth(string nom_param, double value)
{
//la modif de Enneigeur1 entraine l'envoi d'une trame WRITE en bluetooth (si la liaison est OK)
string bufferEnvoi = "";
if (EtatGrafcet_loop >= 2)
{
switch(nom_param.ToLower())
{
Cases...
}
}
}
public void ExitApp()
{
// Disconnect from bth device
DependencyService.Get<IBtInterface>().Disconnect();
MessagingCenter.Unsubscribe<App, string>(this, "ReadDatas");
IsConnected = false;
if (_ct != null)
{
System.Diagnostics.Debug.WriteLine("Send a cancel to task!");
_ct.Cancel();
}
}
public GlobalViewModel()
{
Resources = new LocalizedResources(typeof(AppResources), Enneigeur1._SelectedLanguageKey
);
MessagingCenter.Subscribe<App>(this, "Sleep", (obj) =>
{
// When the app "sleep", I close the connection with bluetooth
if (IsConnected)
DependencyService.Get<IBtInterface>().Disconnect();
});
MessagingCenter.Subscribe<App>(this, "Resume", (obj) =>
{
// When the app "resume" I try to restart the connection with bluetooth
if (IsConnected)
DependencyService.Get<IBtInterface>().Connect(SelectedBthDevice);
});
this.InitCommand = new Command(() =>
{
// Try to connect to a bth device
DependencyService.Get<IBtInterface>().Init();
});
this.ConnectCommand = new Command(() =>
{
EtatGrafcet_loop = 0;
// Try to connect to a bth device
IsConnected = DependencyService.Get<IBtInterface>().Connect(SelectedBthDevice);
//second essai
if (IsConnected == false) IsConnected = DependencyService.Get<IBtInterface>().Connect(SelectedBthDevice);
if (IsConnected == true)
{
// initialisation des echange de données
MessagingCenter.Subscribe<App, string>(this, "ReadDatas", (sender, arg) =>
{
//inputBuffer = inputBuffer + arg;
inputBuffer = inputBuffer + arg;
});
Task.Run(async () => Loop());
}else
{
//erreur aux 2 tentatives de connection
//Task.Run(async () => ((App)Application.Current).OpenTextBoxDialog());
((App)Application.Current).OpenTextBoxDialog();
}
});
this.DisconnectCommand = new Command(() =>
{
EtatGrafcet_loop = 0;
ExitApp();
});
this.RefreshListDeviceCommand = new Command(() =>
{
try
{
ListOfDevices = DependencyService.Get<IBtInterface>().PairedDevices();
}
catch (Exception ex)
{
Application.Current.MainPage.DisplayAlert("Attention", ex.Message, "Ok");
}
});
// At startup, I load all paired devices
try
{
ListOfDevices = DependencyService.Get<IBtInterface>().PairedDevices();
}
catch (Exception ex)
{
Application.Current.MainPage.DisplayAlert("Attention", ex.Message, "Ok");
}
}
private object Await(App current)
{
throw new NotImplementedException();
}
public ICommand InitCommand { get; protected set; }
public ICommand ConnectCommand { get; protected set; }
public ICommand DisconnectCommand { get; protected set; }
public ICommand RefreshListDeviceCommand { get; protected set; }
public void SaveState(IDictionary<string, object> dictionary)
{
dictionary["SavedLanguage"] = Enneigeur1._SelectedLanguageKey;
dictionary["SavedUnitySystem_Pression"] = Enneigeur1.SelectedUnitySystem_Presure;
dictionary["SavedUnitySystem_Debit"] = Enneigeur1.SelectedUnitySystem_Flow;
dictionary["SavedUnitySystem_Temperature"] = Enneigeur1.SelectedUnitySystem_Temperature;
}
public void RestoreState(IDictionary<string, object> dictionary)
{
Enneigeur1.SelectedUnitySystem_Presure = GetDictionaryEntry(dictionary, "SavedUnitySystem_Pression", "Bars");
Enneigeur1.SelectedUnitySystem_Flow = GetDictionaryEntry(dictionary, "SavedUnitySystem_Debit", "m3/h");
Enneigeur1.SelectedUnitySystem_Temperature = GetDictionaryEntry(dictionary, "SavedUnitySystem_Temperature", "°C");
Enneigeur1.SelectedLanguageKey = GetDictionaryEntry(dictionary, "SavedLanguage", "en");
}
public T GetDictionaryEntry<T>(IDictionary<string, object> dictionary,
string key, T defaultValue)
{
if (dictionary.ContainsKey(key))
return (T)dictionary[key];
return defaultValue;
}
}
Any idea why my visual studio doesn't send to windowsform from pi but it does send when i'm using my school's visual studio ( same version ). Do I have to download any specific thing or whatsoever to make it work? Please help.
Here's my code in case too. Would be cool if some1 can go through it and help me with it ( school's project ) Much appreciated !
string strConnectionString =
ConfigurationManager.ConnectionStrings["DataCommsDBConnection"].ConnectionString;
DataComms dataComms;
public delegate void myprocessDataDelegate(string strData);
private void saveWaterSensorDataToDB(string strTime, string strWaterValue, string strStatus)
{
SqlConnection myConnect = new SqlConnection(strConnectionString);
string strCommandText = "INSERT MySensor (TimeOccurred, SensorValue, SensorStatus) +" +
"VALUES (#time, #value, #status)";
SqlCommand updateCmd = new SqlCommand(strCommandText, myConnect);
updateCmd.Parameters.AddWithValue("#time", strTime);
updateCmd.Parameters.AddWithValue("#value", strWaterValue);
updateCmd.Parameters.AddWithValue("#status", strStatus);
myConnect.Open();
int result = updateCmd.ExecuteNonQuery();
myConnect.Close();
}
private string extractStringValue(string strData, string ID)
{
string result = strData.Substring(strData.IndexOf(ID) + ID.Length);
return result;
}
private float extractFloatValue(string strData, string ID)
{
return (float.Parse(extractStringValue(strData, ID)));
}
private void handleWaterSensorData(string strData, string strTime, string ID)
{
string strWaterValue = extractStringValue(strData, ID);
txtWaterValue.Text = strWaterValue;
txtWaterLevel.Text = strWaterValue;
float fWaterValue = extractFloatValue(strData, ID);
string status = "";
if (fWaterValue <= 500)
status = "Dry";
else
status = "Wet";
txtRoomStatus.Text = status;
}
private void handleButtonData(string strData, string strTime, string ID)
{
string strbuttonValue = extractStringValue(strData, ID);
txtButtonValue.Text = strbuttonValue;
txtDoorBell.Text = strbuttonValue;
}
private void extractSensorData(string strData, string strTime)
{
if (strData.IndexOf("WaterLevel=") != -1)
handleWaterSensorData(strData, strTime, "WaterLevel=");
else if (strData.IndexOf("BUTTON=") != -1)
handleButtonData(strData, strTime, "BUTTON=");
}
public void handleSensorData(string strData)
{
string dt = DateTime.Now.ToString();
extractSensorData(strData, dt);
string strMessage = dt + ":" + strData;
lbDataComms.Items.Insert(0, strMessage);
}
public void processDataReceive(string strData)
{
myprocessDataDelegate d = new myprocessDataDelegate(handleSensorData);
lbDataComms.Invoke(d, new object[] { strData });
}
public void commsDataReceive(string dataReceived)
{
processDataReceive(dataReceived);
}
public void commsSendError(string errMsg)
{
MessageBox.Show(errMsg);
processDataReceive(errMsg);
}
private void InitComms()
{
dataComms = new DataComms();
dataComms.dataReceiveEvent += new DataComms.DataReceivedDelegate(commsDataReceive);
dataComms.dataSendErrorEvent += new DataComms.DataSendErrorDelegate(commsSendError);
}
public frmDataComms()
{
InitializeComponent();
}
private void frmDataComms_Load(object sender, EventArgs e)
{
InitComms();
}
private void btnClear_Click(object sender, EventArgs e)
{
lbDataComms.Items.Clear();
}
private void btnSendLight_Click(object sender, EventArgs e)
{
dataComms.sendData("SENDWATER");
}
private void btnSendButton_Click(object sender, EventArgs e)
{
dataComms.sendData("SENDBUTTON");
}
private void btnCmd_Click(object sender, EventArgs e)
{
dataComms.sendData(txtCmd.Text);
}
private void btnSendAll_Click(object sender, EventArgs e)
{
dataComms.sendData("SENDALL");
}
private void btnSendTemp_Click(object sender, EventArgs e)
{
dataComms.sendData("SENDTEMP");
}
}
Form ***
namespace DataCommsRpi
{
public sealed class StartupTask : IBackgroundTask
{
const int MODE_SENDWATER = 1;
const int MODE_SENDBUTTON = 2;
const int MODE_SENDALL = 3;
const int MODE_SENDTEMP = 4;
static int curMode;
Pin waterPin = Pin.AnalogPin2;
IButtonSensor button = DeviceFactory.Build.ButtonSensor(Pin.DigitalPin4);
Pin tempPin = Pin.AnalogPin0;
DataComms dataComms;
string strDataReceived = "";
private bool buttonPressed = false;
private bool prevButtonStatus = false;
int moistureAdcValue = 800;
double tempDegree = 20;
private bool moistureWet = false;
private bool moistureDry = false;
private bool tempHot = false;
private bool tempCold = false;
private void Sleep(int NoOfMs)
{
Task.Delay(NoOfMs).Wait();
}
private async void startWaterMonitoring()
{
int iPrevAdcValue = 800, iReadAdcValue, iDiff;
await Task.Delay(100);
while (true)
{
Sleep(500);
iReadAdcValue = DeviceFactory.Build.GrovePi().AnalogRead(waterPin);
if (iPrevAdcValue > iReadAdcValue)
iDiff = iPrevAdcValue - iReadAdcValue;
else
iDiff = iReadAdcValue - iPrevAdcValue;
iPrevAdcValue = iReadAdcValue;
if (iDiff < 100)
moistureAdcValue = iReadAdcValue;
}
}
private async void startTempMonitoring()
{
await Task.Delay(100);
int adcValue; double tempCalculated = 0, R;
while (true)
{
Sleep(1000);
adcValue = DeviceFactory.Build.GrovePi().AnalogRead(tempPin);
int B = 4250, R0 = 100000;
R = 100000 * (1023.0 - adcValue) / adcValue;
tempCalculated = 1 / (Math.Log(R / R0) / B + 1 / 298.15) - 273.15;
if (!Double.IsNaN(tempCalculated))
tempDegree = tempCalculated;
}
}
private async void startButtonMonitoring()
{
await Task.Delay(100);
while(true)
{
Sleep(100);
string buttonState = button.CurrentState.ToString();
if (buttonState.Equals("On"))
{
Sleep(100);
buttonState = button.CurrentState.ToString();
if(buttonState.Equals("On"))
{
buttonPressed = true;
}
}
}
}
private void commsDataReceive(string dataReceived)
{
strDataReceived = dataReceived;
Debug.WriteLine("Data Received : " + strDataReceived);
}
private void sendDataToWindows(string strDataOut)
{
try
{
dataComms.sendData(strDataOut);
Debug.WriteLine("Sending Msg : " + strDataOut);
}
catch(Exception)
{
Debug.WriteLine("ERROR. Did you forget to initComms()?");
}
}
private void initComms()
{
dataComms = new DataComms();
dataComms.dataReceiveEvent += new DataComms.DataReceivedDelegate(commsDataReceive);
}
private void handleModeSendWater()
{
if (moistureAdcValue <= 500)
moistureWet = true;
else
moistureWet = false;
if (moistureAdcValue <= 500 && moistureDry != moistureWet)
sendDataToWindows("WaterLevel=" + moistureAdcValue + " wet");
if (moistureAdcValue > 500 && moistureDry != moistureWet)
sendDataToWindows("WaterLevel=" + moistureAdcValue + " dry");
moistureDry = moistureWet;
if (strDataReceived.Equals("SENDBUTTON"))
{
curMode = MODE_SENDBUTTON;
Debug.WriteLine("===Entering MODE_SENDBUTTON===");
}
else if (strDataReceived.Equals("SENDALL"))
{
curMode = MODE_SENDALL;
Debug.WriteLine("===Entering MODE_SENDALL");
}
else if (strDataReceived.Equals("SENDTEMP"))
{
curMode = MODE_SENDTEMP;
Debug.WriteLine("===Entering MODE_SENDTEMP");
}
strDataReceived = "";
}
private void handleModeSendTemperature()
{
if (tempDegree <= 31)
tempCold = true;
else
tempCold = false;
if (tempDegree <= 31 && tempCold != tempHot)
{
Sleep(3000);
sendDataToWindows("Temperature = " + tempDegree.ToString("N2") + " : cold");
}
else if (tempDegree >= 32 && tempCold != tempHot)
{
Sleep(3000);
sendDataToWindows("Temperature = " + tempDegree.ToString("N2") + " : hot");
}
if (strDataReceived.Equals("SENDBUTTON"))
{
curMode = MODE_SENDBUTTON;
Debug.WriteLine("===Entering MODE_SENDBUTTON===");
}
else if (strDataReceived.Equals("SENDALL"))
{
curMode = MODE_SENDALL;
Debug.WriteLine("===Entering MODE_SENDALL");
}
else if (strDataReceived.Equals("SENDWATER"))
{
curMode = MODE_SENDWATER;
Debug.WriteLine("===Entering MODE_SENDWATER===");
}
}
private void handleModeSendButton()
{
if(buttonPressed != prevButtonStatus)
{
sendDataToWindows("BUTTON=" + buttonPressed);
}
prevButtonStatus = buttonPressed;
buttonPressed = false;
if(strDataReceived.Equals("SENDWATER"))
{
curMode = MODE_SENDWATER;
Debug.WriteLine("===Entering MODE_SENDWATER===");
}
else if(strDataReceived.Equals("SENDALL"))
{
curMode = MODE_SENDALL;
Debug.WriteLine("===Entering MODE_SENDALL");
}
else if (strDataReceived.Equals("SENDTEMP"))
{
curMode = MODE_SENDTEMP;
Debug.WriteLine("===Entering MODE_SENDTEMP");
}
}
private void handleModeSendAll()
{
Sleep(5000);
sendDataToWindows("Water Level=" + moistureAdcValue);
sendDataToWindows("Temperature = " + tempDegree.ToString("N2"));
if (strDataReceived.Equals("SENDWATER"))
{
curMode = MODE_SENDWATER;
Debug.WriteLine("===Entering MODE_SENDWATER");
}
else if (strDataReceived.Equals("SENDBUTTON"))
{
curMode = MODE_SENDBUTTON;
Debug.WriteLine("===Entering MODE_SENDBUTTON");
}
else if (strDataReceived.Equals("SENDTEMP"))
{
curMode = MODE_SENDTEMP;
Debug.WriteLine("===Entering MODE_SENDTEMP");
}
}
public void Run(IBackgroundTaskInstance taskInstance)
{
//
// TODO: Insert code to perform background work
//
// If you start any asynchronous methods here, prevent the task
// from closing prematurely by using BackgroundTaskDeferral as
// described in http://aka.ms/backgroundtaskdeferral
//
initComms();
startButtonMonitoring();
startWaterMonitoring();
startTempMonitoring();
curMode = MODE_SENDWATER;
Debug.WriteLine("===Entering MODE_SENDWATER===");
while (true)
{
Sleep(300);
if (curMode == MODE_SENDWATER)
handleModeSendWater();
else if (curMode == MODE_SENDBUTTON)
handleModeSendButton();
else if (curMode == MODE_SENDALL)
handleModeSendAll();
else if (curMode == MODE_SENDTEMP)
handleModeSendTemperature();
else
Debug.WriteLine("ERROR: Invalid Mode. Please check your logic");
}
}
}
}
I have a code that executes every X seconds. And it updates lists that are linked to listboxes in my form.
I would like the listboxes to refresh when the lists are updated.
For now i update them by having a button "refresh" because the button has the access to the listboxes.
private void button3_Click(object sender, EventArgs e)
{
listBox1.DataSource = null;
listBox2.DataSource = null;
listBox3.DataSource = null;
listBox4.DataSource = null;
listBox1.DataSource = subject;
listBox2.DataSource = from;
listBox3.DataSource = date;
listBox4.DataSource = timeLeft;
}
Is there a way to do it without having this button ? Automatically ?
The whole code:
//class email
public class email
{
public string title { get; set; }
public DateTime date { get; set; }
public string sender { get; set; }
public bool treated { get; set; }
public bool toDelete { get; set; }
public email() { }
public email(string eTitle, DateTime eDate, string eSender, bool eTreated, bool eToDelete)
{
title = eTitle;
date = eDate;
sender = eSender;
treated = eTreated;
toDelete = eToDelete;
}
}
//Initialisation de la fenetre principale
public Form1()
{
InitializeComponent();
comboBox1.Text = "30";
label1.Text = "Process stopped";
listBox1.DataSource = subject;
listBox2.DataSource = from;
listBox3.DataSource = date;
listBox4.DataSource = timeLeft;
initiate();
System.Timers.Timer timer = new System.Timers.Timer(10000);
timer.Elapsed += OnTimedEvent;
timer.Enabled = true;
}
//Prise des informations outlook
private static void initiate()
{
if (Process.GetProcessesByName("OUTLOOK").Count() > 0)
{
try
{
app = Marshal.GetActiveObject("Outlook.Application") as Outlook.Application;
ns = app.GetNamespace("MAPI");
inbox = ns.Folders["Support N2 MAS"].Folders["Inbox"];
items = inbox.Items;
}
catch (COMException ex)
{
MessageBox.Show(ex.Message);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
else
{
MessageBox.Show("Please, start outlook..");
}
}
//Run
private void Run_Click(object sender, EventArgs e)
{
isRunning = true;
label1.Text = "Process running";
}
//Stop
private void Stop_Click(object sender, EventArgs e)
{
isRunning = false;
label1.Text = "Process stopped";
}
//Icone barre des taches
private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
{
this.Show();
RemedyMailAlert.Visible = false;
isVisible = true;
}
//Traitement toutes les X secondes
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
if (isRunning)
{
if (Process.GetProcessesByName("OUTLOOK").Count() > 0)
{
try
{
DateTime dateToCheck = DateTime.Now.AddDays(-5);
currentList.Clear();
foreach (Object obj in items)
{
if (obj is Outlook.MailItem)
{
Outlook.MailItem mail = (Outlook.MailItem)obj;
if(mail.CreationTime > dateToCheck && !mail.Subject.ToString().Contains("INC000") && mail.CreationTime < DateTime.Now.AddMinutes(-reminder) && mail.UnRead)
{
email email = new email();
email.title = mail.Subject.ToString();
email.date = mail.CreationTime;
email.sender = mail.SenderName;
email.treated = false;
email.toDelete = false;
currentList.Add(email);
}
}
}
Compare();
Clean();
Display();
}
catch (COMException ex)
{
MessageBox.Show(ex.Message);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
else
{
MessageBox.Show("Please, start outlook..");
}
}
else
{
//doesn't run so we don't do anything..
}
}
//Compare
public static void Compare()
{
for (int i = 0; i < currentList.Count; i++)
{
int a = 0;
for (int j = 0; j < listEmail.Count; j++)
{
if (listEmail[j].date == currentList[i].date && listEmail[j].title == currentList[i].title && listEmail[j].sender == currentList[i].sender)
{
a++;
}
}
if (a == 0)
{
listEmail.Add(currentList[i]);
}
}
}
//Clean
public static void Clean()
{
List<int> toDelete = new List<int>();
for (int i = 0; i < listEmail.Count; i++)
{
int a = 0;
for (int j = 0; j < currentList.Count; j++)
{
if (currentList[j].date != listEmail[i].date || listEmail[i].title != currentList[j].title)
{
a++;
}
}
if (a == currentList.Count)
{
toDelete.Add(i);
}
}
for (int i = 0; i < toDelete.Count; i++)
{
listEmail.RemoveAt(toDelete[i]);
}
}
//Display
public static void Display()
{
fillListBoxes();
//otherthings to come
}
//Traitement pour remplir les listbox
public static void fillListBoxes()
{
subject.Clear();
from.Clear();
date.Clear();
timeLeft.Clear();
for (int i = 0; i < listEmail.Count; i++)
{
subject.Add(listEmail[i].title);
from.Add(listEmail[i].sender);
date.Add(listEmail[i].date.ToShortTimeString());
int time = (int)(DateTime.Now - listEmail[i].date).TotalMinutes;
timeLeft.Add((60 - time).ToString());
listEmail[i].treated = true;
}
}
//reglage du temps du reminder
private void button1_Click(object sender, EventArgs e)
{
reminder = int.Parse(comboBox1.SelectedItem.ToString());
}
private void button3_Click(object sender, EventArgs e)
{
Display();
listBox1.DataSource = null;
listBox2.DataSource = null;
listBox3.DataSource = null;
listBox4.DataSource = null;
listBox1.DataSource = subject;
listBox2.DataSource = from;
listBox3.DataSource = date;
listBox4.DataSource = timeLeft;
}
private void button2_Click(object sender, EventArgs e)
{
this.Hide();
RemedyMailAlert.Visible = true;
isVisible = false;
}
}
At the starting of GameState.Running, i want to stop input key in 3 seconds, after that, every time when my character take damage, i want to lose control in 1 second, could anyone show me how to do that?
public override void Update(GameTime gameTime, KeyboardState Current, KeyboardState Old)
{
float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
if (TimeGetReady < 0)
{
LockKey = false;
}
else
{
LockKey = true;
TimeGetReady -= elapsed;
}
if (LockKey == false)
{
CurrentKeys = Current;
OldKeys = Old;
}
if (CurrentKeys.IsKeyDown(Keys.P))
{
if (!OldKeys.IsKeyDown(Keys.P))
if (IsPause == true)
IsPause = false;
else
IsPause = true;
}
if (IsPause == true)
{
return;
}
Update(elapsed);
if (CurrentKeys.IsKeyDown(Keys.Left))
{
KeyLeft = true;
if (HPF < 3)
HPF += 2;
PushHorizontal += 5;
Face = -1;
}
else
if (Old.IsKeyDown(Keys.Left))
{
KeyLeft = false;
}
if (CurrentKeys.IsKeyDown(Keys.Right))
{
KeyRight = true;
PushHorizontal += 5;
if (HPF < 3)
HPF += 2;
Face = 1;
}
else
if (Old.IsKeyDown(Keys.Right))
{
KeyRight = false;
}
if (KeyLeft == true || KeyRight == true)
{
KeyMove = true;
}
else
{
KeyMove = false;
}
if (KeyLeft == true && KeyRight == true)
{
KeyLeft = false;
KeyRight = false;
KeyMove = false;
}
if (CurrentKeys.IsKeyDown(Keys.X))
{
if (LockKeyX == false)
{
KeyJump = true;
LockKeyX = true;
PushVertical += 500;
}
if (VPF < 8)
VPF += 3;
}
else
if (Old.IsKeyDown(Keys.X))
{
KeyJump = false;
}
if (CurrentKeys.IsKeyUp(Keys.X))
{
if (Down == true)
{
LockKeyX = false;
}
}
if (CurrentKeys.IsKeyDown(Keys.Z))
{
if (LockKeyZ == false)
{
KeyDash = true;
KeyJump = false;
LockKeyZ = true;
PushHorizontal += 100;
}
if (KeyDash == true)
{
HPF = 1;
PushVertical += Gravity;
VPF = Gravity;
}
}
else
if (Old.IsKeyDown(Keys.Z))
{
KeyDash = false;
}
if (CurrentKeys.IsKeyUp(Keys.Z))
{
if (KeyMove == false && Down == true)
LockKeyZ = false;
}
if (CurrentKeys.IsKeyDown(Keys.C))
{
ChargeTime += elapsed;
if (LockKeyC == false)
{
LockKeyC = true;
TimeShot += 10f;
StayShot.ResetFrame();
}
}
else
if (Old.IsKeyDown(Keys.C))
{
if (ChargeTime > 0)
{
TimeShot += 0.4f;
ChargeTime = 0;
}
LockKeyC = false;
}
Update(elapsed);
UpdateInteraction();
if (TimeGetReady <= 0)
{
UpdateStatus(gameTime);
}
UpdateFrameStatus(elapsed);
LastStatus = RockmanStatus;
}
You need some InputManager that you update only when you need. Here is example of basic verstion of InputManager.
public override void Update(){
if(updateKeyboard) {InputManager.Update()}
}
new InputManager Class
public static class InputManager
{
public static void Update()
{
_previousKeyboardState = _currentKeyboardState;
_currentKeyboardState = Keyboard.GetState();
}
public static bool IsKeyDown(Keys key)
{
return _currentKeyboardState.IsKeyDown(key);
}
public static bool IsKeyUp(Keys key)
{
return _currentKeyboardState.IsKeyUp(key);
}
public static bool OnKeyDown(Keys key)
{
return _currentKeyboardState.IsKeyDown(key) && _previousKeyboardState.IsKeyUp(key);
}
public static bool OnKeyUp(Keys key)
{
return _currentKeyboardState.IsKeyUp(key) && _previousKeyboardState.IsKeyDown(key);
}
private static KeyboardState _currentKeyboardState;
private static KeyboardState _previousKeyboardState;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm trying to make a Simon Says game for Windoes Phone 8, and I've hit a wall and can't figure out what's wrong... I'd greatly appreciate some help.
The problems are with the "continueGame" and "initializeColorSequence" paramenters.
Cheers.
{
namespace SimonSez
{
public sealed partial class MainPage : PhoneApplicationPage
{
#region Variables
//Variables
const int colours_amount = 4;
const int colour1 = 1;
const int colour2 = 2;
const int colour3 = 3;
const int colour4= 4;
const int max_seq_count = 100; // TODO: Make 100 for release version
const String startgame_click = "Click to begin!";
const String win = "YOU WIN!";
int currentLengthOfSequence = 0;
Random randomNumber;
int[] correctColorSequence;
int[] playerColorSequence;
int correctColorSequenceIndex = 0;
int playerColorSequenceIndex = 0;
Boolean isPlayerTurn = true;
Boolean isSequenceCorrect = false;
Boolean isGameStarted = false;
Boolean isDoingAnimation = false;
long timeStart, timeEnd, timeDifference;
#endregion
// Constructor
public MainPage()
{
this.InitializeComponent();
randomNumber = new Random();
correctColorSequence = new int[max_seq_count];
playerColorSequence = new int[max_seq_count];
initializeColorSequence();
textBlockRoundNumber.Opacity = 0;
// Sample code to localize the ApplicationBar
//BuildLocalizedApplicationBar();
}
private void startGame()
{
currentLengthOfSequence = 0;
//textBlockCenter.Text = "Round " + roundNumber;
textBlockRoundNumber.Text = currentLengthOfSequence.ToString();
textBlockRoundNumber.Foreground = new SolidColorBrush(Colors.White);
textBlockRoundNumber.Opacity = 100;
textBlockStartGame.Opacity = 0;
isGameStarted = true;
playerColorSequenceIndex = 0;
initializeColorSequence();
isPlayerTurn = false;
continueGame();
}
private void continueGame()
{
isSequenceCorrect = true;
for (int i = 0; i < playerColorSequenceIndex; i++)
{
if (correctColorSequence[i] == playerColorSequence[i])
{
// do nothing
}
else
{
isSequenceCorrect = false;
break;
}
}
}
private void initializeColorSequence()
{
for (int i = 0; i < max_seq_count; i++)
{
correctColorSequence[i] = randomNumber.Next(1, colours_amount);
playerColorSequence[i] = 0;
}
}
#region Grip Tapping
private void Rect1_Tap(object sender, GestureEventArgs e)
{
if (isPlayerTurn)
{
//storyboardRectangle0Player.Begin();
//audioPiano12.Volume = 0.5;
//audioPiano12.Play();
if (isGameStarted)
{
playerColorSequence[playerColorSequenceIndex++] = colour1;
isPlayerTurn = false;
continueGame();
}
}
}
private void Rect2_Tap(object sender, GestureEventArgs e)
{
if (isPlayerTurn)
{
//storyboardRectangle1Player.Begin();
//audioPiano12.Volume = 0.5;
//audioPiano12.Play();
if (isGameStarted)
{
playerColorSequence[playerColorSequenceIndex++] = colour2;
isPlayerTurn = false;
continueGame();
}
}
}
private void Rect3_Tap(object sender, GestureEventArgs e)
{
if (isPlayerTurn)
{
//storyboardRectangle2Player.Begin();
//audioPiano12.Volume = 0.5;
//audioPiano12.Play();
if (isGameStarted)
{
playerColorSequence[playerColorSequenceIndex++] = colour3;
isPlayerTurn = false;
continueGame();
}
}
}
private void Rect4_Tap(object sender, GestureEventArgs e)
{
if (isPlayerTurn)
{
//storyboardRectangle3Player.Begin();
//audioPiano12.Volume = 0.5;
//audioPiano12.Play();
if (isGameStarted)
{
playerColorSequence[playerColorSequenceIndex++] = colour4;
isPlayerTurn = false;
continueGame();
}
}
}
private void StartGame_Tap(object sender, GestureEventArgs e)
{
if (textBlockStartGame.Text.Equals(startgame_click))
{
if (textBlockStartGame.Opacity != 0)
{
startGame();
}
}
else if (textBlockStartGame.Text.Equals(win))
{
endGame(startgame_click);
}
else
{
// Do nothing
}
}
#endregion
private void continueGame()
{
isSequenceCorrect = true;
for (int i = 0; i < playerColorSequenceIndex; i++)
{
if (correctColorSequence[i] == playerColorSequence[i])
{
// do nothing
}
else
{
isSequenceCorrect = false;
break;
}
}
if (isSequenceCorrect)
{
if (playerColorSequenceIndex >= currentLengthOfSequence)
{
currentLengthOfSequence++;
if (currentLengthOfSequence < max_seq_count)
{
//audioShinyDing.Volume = 0.5;
//audioShinyDing.Play();
textBlockRoundNumber.Text = currentLengthOfSequence.ToString();
}
else // roundNumber == MAX_SEQUENCE_COUNT
{
// audioApplause.Volume = 0.5;
//audioApplause.Play();
endGame(win);
}
}
else // playerColorSequenceIndex < roundNumber
{
//playerColorSequenceIndex++;
isPlayerTurn = true;
}
}
else // isSquenceCorrect == false
{
endGame(startGame);
}
}
private void endGame(String endGameMessage)
{
isGameStarted = false;
textBlockStartGame.Text = endGameMessage;
textBlockStartGame.Opacity = 100;
textBlockRoundNumber.Foreground = new SolidColorBrush(Colors.Gray);
textBlockRoundNumber.Opacity = 40;
isPlayerTurn = true;
}
#region Helper Functions
private void initializeColorSequence()
{
for (int i = 0; i < max_seq_count; i++)
{
correctColorSequence[i] = randomNumber.Next(1, colours_amount);
playerColorSequence[i] = 0;
}
}
private void waitMilliseconds(int waitTime) // Not used
{
timeStart = DateTime.Now.Ticks;
long totalWaitTimeInTicks = waitTime * 10000;
do
{
timeEnd = DateTime.Now.Ticks;
timeDifference = timeEnd - timeStart;
}
while (timeDifference < totalWaitTimeInTicks);
}
#endregion
}
}
}
You seem to have two functions called "continueGame" and also two "initializeColorSequence", hence why it says a member is already defined.
You appear to have defined both of those methods twice in the code you've provided.