Memory game timer card reset - c#

I'm making a memory game and i need to set a timer to reset de images if they don't match but it doesn't work to turn the pictures back to hidden:
//set images
if (clickedLabel != null)
{
var Index = Convert.ToInt32(clickedLabel.Tag);
clickedLabel.Image = icons[Index];
//Check first clicked
if (firstClicked == null)
{
firstClicked = clickedLabel;
return;
}
secondClicked = clickedLabel;
timer1.Start();
}
Method timer1_Tick:
//Timer
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Stop();
firstClicked = null;
secondClicked = null;
}

This might work :
class YourClass
{
System.Timers.Timer aTimer;
void YourMethod()
{
//code
if (clickedLabel != null)
{
var Index = Convert.ToInt32(clickedLabel.Tag);
clickedLabel.Image = icons[Index];
//Check first clicked
if (firstClicked == null)
{
firstClicked = clickedLabel;
return;
}
secondClicked = clickedLabel;
SetTimer();
}
private static void SetTimer ()
{
//System.Timers.Timer aTimer; at the beginning of your class
aTimer = new System.Timers.Timer (2000); //the time you want in milliseconds
aTimer.Elapsed += OnTimedEvent;
aTimer.AutoReset = false;
aTimer.Enabled = true;
}
}
The AutoReset set to false will make the Elapsed event trigger only once. Then, you do what you want in that event.
private static void OnTimedEvent (Object source, ElapsedEventArgs e)
{
firstClicked = null;
secondClicked = null;
}
You might want to use Stop and Dispose methods on aTimer when you don't need it anymore.
You also should be more specific when posting questions, to be sure to have the help you need :)

Related

Frame animation in xamarin forms

I want to do frame animation and not sure should i use AnimationDrawable class for animation.
How do frame animation in Xamarin forms for Android. Is there any other approach? Simple example would be perfect.
I did trick just hiding and unhiding required elements. You could call from DoAnimation from any button click or smth else.
private void DoAnimation()
{
_timer = new System.Timers.Timer();
//Trigger event every second
_timer.Interval = 1000;
_timer.Elapsed += CheckStatus;
//count down 5 seconds
_countSeconds = 5000;
_timer.Enabled = true;
}
private void SpinAnimation()
{
switch (_letterShowState) {
case SomeStateStates.State1:
_pic1.IsVisible = false;
_pic2.IsVisible = true;
_pic3.IsVisible = false;
_letterShowState = SomeStateStates.State2;
break;
}
}
private void CheckStatus(object sender, System.Timers.ElapsedEventArgs e) {
_countSeconds--;
new System.Threading.Thread(new System.Threading.ThreadStart(() => {
Xamarin.Forms.Device.BeginInvokeOnMainThread(() => {
SpinAnimation();
});
})).Start();
if (_countSeconds == 0)
{
_timer.Stop();
}
}

Timer tick is not triggered

I check a condition on my form_load event whether the form window should be closed or not. If so, a timer with an interval of 3000 will be started and after the tick, the form should be closed. When I check my debugger, even though the condition returns true, the debugger jumps over my timer.Start() method and my timer is never ticked.
I have defined the timer in my class as System.Windows.Forms.Timer timer; and this is how I am initiating it:
timer = new System.Windows.Forms.Timer();
this.timer.Enabled = true;
this.timer.Interval = 3000;
this.timer.Tick += new System.EventHandler(this.timer_Tick_1);
The tick event:
private void timer_Tick_1(object sender, EventArgs e)
{
this.Close();
}
And the condition is as simple as:
if (closeWindow)
timer.Start();
And trust me, the closeWindow returns true.
P.s. Strangely enough, this timer used to work. I know I have it messed up somewhere perhaps. But I do not know where.
Update: the form_load event
private void FormMain_Load(object sender, EventArgs e)
{
metroLabelBuild.Text = args["name"] + " " + args["action"];
if (CheckArguments(args, 18))
{
try
{
campaignRecipientsFileLocation = args["recipientsfile"].Trim();
campaignName = args["name"].Trim();
campaignDescription = args["description"].Trim();
campaignAction = args["action"].Trim();
campaignOutputFormat = args["outputformat"].Trim();
campaignType = args["type"].Trim().ToLower();
campaignDelimiter = args["delimeter"].Trim();
campaignOutputPath = args["outputpath"].Trim();
campaignFileName = args["filename"].Trim();
campaignId = Convert.ToInt64(args["id"].Trim());
campaignFixedCost = Convert.ToInt32(args["fixedcost"]);
campaignVariableCost = Convert.ToInt32(args["variablecost"]);
campaignControlGroup = Convert.ToInt32(args["controlgroup"]);
campaignFtpId = Convert.ToInt64(args["ftpid"].Trim());
campaignHasSpyList = (args["hasspylist"].ToLower().Equals("true") || args["hasspylist"].Equals("1")) ? true : false;
closeWindow = (args["closewindow"].ToLower().Equals("true") || args["closewindow"].Equals("1")) ? true : false;
campaignShouldUploadToFTP = (args["shoulduploadtoftp"].ToLower().Equals("true") || args["shoulduploadtoftp"].Equals("1")) ? true : false;
}
catch
{
listBoxMessages.Items.Add("Error preparing the arguments.");
continueProcess = false;
this.Close();
}
finally
{
logger = new Logger(loggerEnabled, cs);
fh = new FileHelper(logger);
rh = new RecipientHelper(logger);
dbh = new DatabaseHelper(logger, cs);
if (continueProcess)
{
InsertCampaignRun("Running");
RunCampaign();
if (closeWindow)
timer.Start();
}
}
}
else
{
if (closeWindow)
timer.Start();
}
}

How to determine that a thread is finished using c#?

I am working with threads in C#. Below is the code which I am using
// worker thread
Thread m_WorkerThread;
// events used to stop worker thread
ManualResetEvent m_EventStopThread;
ManualResetEvent m_EventThreadStopped;
private void btnSend_Click(object sender, EventArgs e)
{
if (btnSend.Text == "Cancel")
{
StopThread();
btnSend.Text = "Send";
return;
}
else
{
// initialize events
m_EventStopThread = new ManualResetEvent(false);
m_EventThreadStopped = new ManualResetEvent(false);
btnSend.Text = "Cancel";
// reset events
m_EventStopThread.Reset();
m_EventThreadStopped.Reset();
// create worker thread instance
m_WorkerThread = new Thread(new ThreadStart(this.ThreadFunction));
m_WorkerThread.Name = "Thread Sample"; // looks nice in Output window
m_WorkerThread.Start();
}
}
private void StopThread()
{
if (m_WorkerThread != null && m_WorkerThread.IsAlive) // thread is active
{
// set event "Stop"
m_EventStopThread.Set();
// wait when thread will stop or finish
try
{
Thread.Sleep(1000);
m_WorkerThread.Abort();
m_WorkerThread.Suspend();
}
catch { }
}
ThreadFinished(); // set initial state of buttons
return;
}
private void ThreadFunction()
{
// Doing My Work
}
private void ThreadFinished()
{
btnSend.Text = "Send";
}
The code above is working fine, but I have some problems.
When the threads end, btnSend.Text = "Send" is not setting.
When I press cancel, the the threads are not ending properly.
When I press cancel and close my application, the application keeps running in the background.
How can I fix these problems?
This is an example of how to use a BackgroundWorker with cancellation:
public partial class Form1 : Form
{
bool _isWorking = false;
public Form1()
{
InitializeComponent();
backgroundWorker1.DoWork += backgroundWorker1_DoWork;
backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;
backgroundWorker1.WorkerSupportsCancellation = true;
}
private void button1_Click(object sender, EventArgs e)
{
if (_isWorking)
{
// Cancel the worker
backgroundWorker1.CancelAsync();
button1.Enabled = false;
return;
}
_isWorking = true;
button1.Text = "Cancel";
backgroundWorker1.RunWorkerAsync();
}
void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
for (var i = 0; i < 10; i++)
{
if (backgroundWorker1.CancellationPending) { return; }
Thread.Sleep(1000);
}
e.Result = "SomeResult";
}
void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
_isWorking = false;
button1.Enabled = true;
button1.Text = "Run";
if (e.Cancelled) return;
// Some type checking
string theResult = e.Result as string;
if (theResult == null) return; // Or throw an error or whatever u want
MessageBox.Show(theResult);
}
}

timer doesn't stop c#

I am using timer in form to send a command to a controller after every 3 seconds when user presses button. The timer should stop after user again presses same button. But in my case timer doesn't stop. I am using timer in the following way.
private void autoModeTempBtn_Click(object sender, EventArgs e)
{
System.Timers.Timer tempTimer = new System.Timers.Timer(3000);
tempTimer.SynchronizingObject = this;
tempTimer.AutoReset = true;
if (autoModeTempBtn.Text == "Get Temperature Auto Mode")
{
autoModeTempBtn.Text = "hello";
tempTimer.Elapsed += new System.Timers.ElapsedEventHandler(OnTemperatureEvent);
tempTimer.Enabled = true;
}
else /*user presses button second time */
{
tempTimer.Stop();
tempTimer.AutoReset = false;
tempTimer.Enabled = false;
autoModeTempBtn.Text = "Get Temperature Auto Mode";
}
}
private void OnTemperatureEvent(object source, System.Timers.ElapsedEventArgs e)
{
//do something
}
Where I am making mistake?
You are creating your timer new every time you click the button. Create the timer once and just Start/Stop it everytime you click. Also you should use the System.Windows.Forms.Timer instead of the System.Timers.Timer.
var _timer = new Timer() { Interval = 3000 };
private void autoModeTempBtn_Click(object sender, EventArgs e)
{
if (!validateSerialNumber())
return;
if (!_timer.Enabled)
{
_timer.Start();
autoModeTempBtn.Text = "hello";
}
else
{
_timer.Stop();
autoModeTempBtn.Text = "Get Temperature Auto Mode";
}
}
And add this code to your constructor:
_timer.Tick += OnTemperatureEvent;

Displaying two labels for one second through a timer

I'm making a little game in C#
When the score is 100, I want two labels to display for one second, then they need to be invisible again.
At the moment I have in Form1:
void startTimer(){
if (snakeScoreLabel.Text == "100"){
timerWIN.Start();
}
}
private void timerWIN_Tick(object sender, EventArgs e)
{
int timerTick = 1;
if (timerTick == 1)
{
lblWin1.Visible=true;
lblWin2.Visible=true;
}
else if (timerTick == 10)
{
lblWin1.Visible = false;
lblWin2.Visible = false;
timerWIN.Stop();
}
timerTick++;
}
The timer's interval is 1000ms.
Problem = labels aren't showing at all
Timers are pretty new to me, so I'm stuck here :/
Try this :
void startTimer()
{
if (snakeScoreLabel.Text == "100")
{
System.Timers.Timer timer = new System.Timers.Timer(1000) { Enabled = true };
timer.Elapsed += (sender, args) =>
{
lblWin1.Visible=true;
timer.Dispose();
};
}
}
Try multithreaded System.Threading.Timer :
public int TimerTick = 0;
private System.Threading.Timer _timer;
public void StartTimer()
{
label1.Visible = true;
label2.Visible = true;
_timer = new System.Threading.Timer(x =>
{
if (TimerTick == 10)
{
Invoke((Action) (() =>
{
label1.Visible = false;
label2.Visible = false;
}));
_timer.Dispose();
TimerTick = 0;
}
else
{
TimerTick++;
}
}, null, 0, 1000);
}

Categories