CountDown check Time - c#

I've made an countdown and i want to add an time check for it now. If the minutes are < 01 and the seconds are != 60 so 00:59 the Time should be orange and if the seconds are then smaller then 10 the time should be red.
But it does not work.
They're always just getting orange if the time is 00:00:58, but why?
private int hours, minutes, seconds;
private bool paused;
private void button_Start_Click(object sender, EventArgs e)
{
button_Pause.Enabled = true;
button_Stop.Enabled = true;
if(paused != true)
{
hours = int.Parse(textBox_Hours.Text);
minutes = int.Parse(textBox_Minutes.Text);
seconds = int.Parse(textBox_Seconds.Text) + 1;
textBox_Hours.Enabled = false;
textBox_Minutes.Enabled = false;
textBox_Seconds.Enabled = false;
button_Start.Enabled = false;
timer_CountDown.Start();
}
}
private void timer_CountDown_Tick(object sender, EventArgs e)
{
if(hours == 0 && minutes < 1)
{
label_Hours.ForeColor = Color.Red;
label_Minutes.ForeColor = Color.Red;
label_Seconds.ForeColor = Color.Red;
label8.ForeColor = Color.Red;
label10.ForeColor = Color.Red;
}
if(hours == 0 && minutes == 0 && seconds == 0)
{
timer_CountDown.Stop();
textBox_Seconds.Enabled = true;
textBox_Minutes.Enabled = true;
textBox_Hours.Enabled = true;
button_Start.Enabled = true;
}
else
{
if (seconds < 1)
{
seconds = 59;
if (minutes < 1)
{
minutes = 59;
if (hours != 0)
{
hours -= 1;
}
}
else
{
minutes -= 1;
}
}
else
{
seconds -= 1;
}
if(hours > 9)
{
label_Hours.Text = hours.ToString();
}
else { label_Hours.Text = "0" + hours.ToString(); }
if(minutes > 9)
{
label_Minutes.Text = minutes.ToString();
}
else { label_Minutes.Text = "0" + minutes.ToString(); }
if(seconds > 9)
{
label_Seconds.Text = seconds.ToString();
}
else { label_Seconds.Text = "0" + seconds.ToString(); }
}
}
The Timer Intervall is 1000.

You're over complicating things. Why not just use the TimeSpan type and get rid of those hours, minutes, seconds?
private TimeSpan countDownTime = TimeSpan.Zero;
private void timer_CountDown_Tick(object sender, EventArgs e)
{
if(countDownTime == TimeSpan.Zero)
{
timer_CountDown.Stop();
textBox_Seconds.Enabled = true;
textBox_Minutes.Enabled = true;
textBox_Hours.Enabled = true;
button_Start.Enabled = true;
return;
}
countDownTime = countDownTime.Add(TimeSpan.FromSeconds(1).Negate());
label_Hours.Text = countDownTime.ToString("hh");
label_Minutes.Text = countDownTime.ToString("mm");
label_Seconds.Text = countDownTime.ToString("ss");
if(countDownTime.TotalSeconds < 10)
{
label_Hours.ForeColor = Color.Red;
label_Minutes.ForeColor = Color.Red;
label_Seconds.ForeColor = Color.Red;
label8.ForeColor = Color.Red;
label10.ForeColor = Color.Red;
}
else if (countDownTime.TotalMinutes < 1)
{
label_Hours.ForeColor = Color.Orange;
label_Minutes.ForeColor = Color.Orange;
label_Seconds.ForeColor = Color.Orange;
label8.ForeColor = Color.Orange;
label10.ForeColor = Color.Orange;
}
}
private void button_Start_Click(object sender, EventArgs e)
{
button_Pause.Enabled = true;
button_Stop.Enabled = true;
if(paused != true)
{
int hours = int.Parse(textBox_Hours.Text);
int minutes = int.Parse(textBox_Minutes.Text);
int seconds = int.Parse(textBox_Seconds.Text) + 1;
this.countDownTime = new TimeSpan(hours,minutes,seconds);
textBox_Hours.Enabled = false;
textBox_Minutes.Enabled = false;
textBox_Seconds.Enabled = false;
button_Start.Enabled = false;
timer_CountDown.Start();
}
}

Related

Countdown timer with numericupdown

In a Winforms application, there are 3 different numericupdown such as min, sec, millisecond. How do I make a timer that counts down the value of entering numericupdowns? I have tried with if else blocks. I also saw a lot of time timespawn titles on the internet. Which is better for this countdown? if else blocks or timespawn
numericUpDownMiliSn.Value--;
if (numericUpDownMiliSn.Value == 0)
{
if (numericUpDownMiliSn.Value == 0 && numericUpDownSn.Value == 0 && numericUpDownDk.Value == 0)
{
timer2.Stop();
button2.Text = "Baslat";
durum = false;
}
else
{
if (numericUpDownSn.Value > 0)
{
numericUpDownSn.Value--;
numericUpDownMiliSn.Value = 60;
}
else
{
numericUpDownMiliSn.Value = 60;
}
if (numericUpDownSn.Value > 0)
{
numericUpDownSn.Value--;
numericUpDownSn.Value = 60;
}
}
}
From my comments in the original question above:
Timers in WinForms are NOT accurate, so you shouldn't be basing your
time off incrementing/decrementing those in a Tick() event. You should
definitely be using a TimeSpan (derived from subtracting the current
time from some future target time; based on the initial values in your
NumericUpDowns)...then simply update the NumericUpDowns with the
numbers in the TimeSpan.
Here's how that code might look:
private DateTime targetDT;
private void button1_Click(object sender, EventArgs e)
{
TimeSpan ts = new TimeSpan(0, 0, (int)numericUpDownMn.Value, (int)numericUpDownSn.Value, (int)numericUpDownMiliSn.Value);
if (ts.TotalMilliseconds > 0)
{
button1.Enabled = false;
numericUpDownMn.Enabled = false;
numericUpDownSn.Enabled = false;
numericUpDownMiliSn.Enabled = false;
targetDT = DateTime.Now.Add(ts);
timer1.Start();
}
}
private void timer1_Tick(object sender, EventArgs e)
{
TimeSpan ts = targetDT.Subtract(DateTime.Now);
if (ts.TotalMilliseconds > 0)
{
numericUpDownMn.Value = ts.Minutes;
numericUpDownSn.Value = ts.Seconds;
numericUpDownMiliSn.Value = ts.Milliseconds;
}
else
{
timer1.Stop();
numericUpDownMn.Value = 0;
numericUpDownSn.Value = 0;
numericUpDownMiliSn.Value = 0;
button1.Enabled = true;
numericUpDownMn.Enabled = true;
numericUpDownSn.Enabled = true;
numericUpDownMiliSn.Enabled = true;
}
}

clearing pictureboxes from a list array

im trying to clear the picturebox that are created from a list in my game once it has ended, i have cleared the list but the picturebox still display i have tried using the below code in a timer that is enable upon the game ending
foreach (Invader ship in invaders)
{
ship.isDisposed = true;
ship.ship.Dispose();
}
this doesnt do anyhting tho so does anyone have any ideas how i could do this?
public partial class Form1 : Form
{
private List<Invader> invaders = new List<Invader>();
private List<Laser> lasers = new List<Laser>();
int invaderNumber = 0;
int score = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
// moves the spacefighter up when clicked
if (e.KeyCode.Equals(Keys.W))
{
if (SpaceFighter.Top > 0)
{
SpaceFighter.Top = SpaceFighter.Top - 30;
}
}
// moves the spacefighter left when clicked
if (e.KeyCode.Equals(Keys.A))
{
if (SpaceFighter.Left > 0)
{
SpaceFighter.Left = SpaceFighter.Left - 10;
}
}
// moves the spacefighter right when clicked
if (e.KeyCode.Equals(Keys.D))
{
if (SpaceFighter.Right < this.Width)
{
SpaceFighter.Left = SpaceFighter.Left + 10;
}
}
// moves the spacefighter down when clicked
if (e.KeyCode.Equals(Keys.S))
{
if (SpaceFighter.Bottom < this.Height - 10)
{
SpaceFighter.Top = SpaceFighter.Top + 10;
}
}
// fires lasers when clicked
if (e.KeyCode.Equals(Keys.Space))
{
System.Media.SoundPlayer LaserSound = new System.Media.SoundPlayer(Properties.Resources.LaserSound);
LaserSound.Play();
this.lasers.Add(new Laser(this, SpaceFighter));
}
}
private void timer1_Tick(object sender, EventArgs e)
{
// introduces 10 enemies once the game starts
if (invaderNumber > 9 )
{
timer1.Enabled = false;
timer2.Enabled = true;
}
else
{
invaders.Add(new Invader(this));
invaderNumber++;
}
}
private void timer2_Tick(object sender, EventArgs e)
{
// detects if the enemy ship interacts with the spacefighter and ends the game if this happens
invaders.RemoveAll(ship => ship.isDisposed);
foreach(Invader ship in invaders)
{
ship.MoveInvader(this);
if (SpaceFighter.Bounds.IntersectsWith(ship.ship.Bounds))
{
// plays sound for exploding ship
System.Media.SoundPlayer SpaceshipSound = new System.Media.SoundPlayer(Properties.Resources.SpaceshipSound);
SpaceshipSound.Play();
timer2.Enabled = false;
timer3.Enabled = false;
timer4.Enabled = true;
invaders.Clear();
listBox1.Items.Add(lblScore.Text); // adds score to listbox
MessageBox.Show("You Lose!");
return;
}
}
// detects if an enemy ship his hit by a laser
lasers.RemoveAll(laser => laser.isDisposed);
foreach (Laser laser in lasers)
{
laser.MoveLaser(this);
foreach (Invader ship in invaders)
{
if (laser.laser.Bounds.IntersectsWith(ship.ship.Bounds))
{
laser.isDisposed = true;
laser.laser.Dispose();
ship.isDisposed = true;
ship.ship.Dispose(); // makes the ship dissappear once its shot
System.Media.SoundPlayer ShipSound = new System.Media.SoundPlayer(Properties.Resources.EnemySound); // sound for the enemy ship being destroyed
ShipSound.Play();
score = score + 2; //adds 2 points to players score if enemy is hit
lblScore.Text = score.ToString(); //updates the score label
invaderNumber = invaderNumber - 1;
}
}
}
foreach (Invader ship in invaders)
{
if (ship.ship.Top > 485)
{
ship.isDisposed = true;
ship.ship.Dispose();
invaderNumber = invaderNumber - 1;
}
}
}
private void btnStart_Click(object sender, EventArgs e)
{
timer1.Enabled = true; // activates timer 1
timer3.Enabled = true; // activates timer 3
btnStart.Visible = false; // hidesthe start button
lblScore.Text = "0"; // updates score label to 0 for start of game
lblName.Text = txtName.Text; // updates the name label to user nput
txtName.Visible = false; // hides the textbox
lblEnterName.Visible = false; // hides the enter name label
SpaceFighter.Visible = true; // makes the spacefighter visible
}
// code for the countdown clock
int m = 2;
int s = 60;
private void timer3_Tick(object sender, EventArgs e)
{
if(s > 0)
{
s = s - 1;
lblTimer.Text = "0" + m.ToString() + ":" + s.ToString();
}
if(s == 0)
{
s = 59;
m = m - 1;
lblTimer.Text = "0" + m.ToString() + ":" + s.ToString();
}
if(s < 10)
{
s = s - 1;
lblTimer.Text = "0" + m.ToString() + ":" + "0" + s.ToString();
}
if (m < 0)
{
listBox1.Items.Add(lblScore.Text + " " + lblName.Text); // adds score to list box
timer4.Enabled = true;
invaders.Clear();
}
if (m >= 0)
{
timer1.Enabled = true;
}
}
private void Form1_Load(object sender, EventArgs e)
{
SpaceFighter.Visible = false; // hides the space fighter until the player starts the game
listBox1.Visible = false; // keepsscore table hidden
lblScoreTable.Visible = false; // score table lables kept hidden
lblNameTable.Visible = false;
btnMenu.Visible = false;
}
private void Timer4_Tick(object sender, EventArgs e)
{
lblTimer.Text = "00:00"; // sets game timer to 00:00
timer3.Enabled = false; // disbales timer 3
listBox1.Visible = true; // makes score card visible
listBox1.Sorted = true;
lblNameTable.Visible = true; // displays score table labels
lblScoreTable.Visible = true;
btnMenu.Visible = true;
foreach (Invader ship in invaders)
{
ship.isDisposed = true;
ship.ship.Dispose();
}
}
private void BtnMenu_Click(object sender, EventArgs e)
{
// resets game to its original state in order to play another game
m = 2;
s = 60;
lblTimer.Text = "03:00";
timer1.Enabled = false;
timer2.Enabled = false;
timer3.Enabled = false;
timer4.Enabled = false;
listBox1.Visible = false;
lblNameTable.Visible = false;
lblScoreTable.Visible = false;
lblEnterName.Visible = true;
txtName.Visible = true;
SpaceFighter.Visible = false;
btnMenu.Visible = false;
btnStart.Visible = true;
score = 0;
lblScore.Text = "Score";
lblName.Text = "Name";
txtName.Clear();
invaderNumber = 0;
SpaceFighter.Top = 380;
SpaceFighter.Left = 400;
}
}
this would do:
foreach (var control in this.Controls)
{
var pb = control as PictureBox;
if (pb != null)
{
if (pb.Name != "SpaceFighter")
{
pb.Dispose();
this.Controls.Remove(pb);
}
}
}
for the listbox sorting:
using System.Collections;
ArrayList Sorting = new ArrayList();
foreach (var o in listBox1.Items)
{
Sorting.Add(o);
}
Sorting.Sort();
Sorting.Reverse();
listBox1.Items.Clear();
foreach (var o in Sorting)
{
listBox1.Items.Add(o);
}

Why when changing one of the trackBars values it's reseting the other values of the watch to 0?

The code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using DannyGeneral;
namespace StopwatchTimer
{
public partial class Form1 : Form
{
private static readonly Stopwatch watch = new Stopwatch();
private long diff = 0, previousTicks = 0, ticksDisplayed = 0;
private OptionsFile optionsfile = new OptionsFile(Path.GetDirectoryName(Application.LocalUserAppDataPath) + "\\Settings.txt");
private string result;
public Form1()
{
InitializeComponent();
richTextBox1.TabStop = false;
richTextBox1.ReadOnly = true;
richTextBox1.BackColor = Color.White;
richTextBox1.Cursor = Cursors.Arrow;
richTextBox1.Enter += RichTextBox1_Enter;
trackBarHours.Value = Convert.ToInt32(optionsfile.GetKey("trackbarhours"));
trackBarMinutes.Value = Convert.ToInt32(optionsfile.GetKey("trackbarminutes"));
trackBarSeconds.Value = Convert.ToInt32(optionsfile.GetKey("trackbarseconds"));
richTextBox1.Text = optionsfile.GetKey("result");
string radiobutton1 = optionsfile.GetKey("radiobutton1");
bool b;
bool.TryParse(radiobutton1.Trim(), out b);
radioButton1.Checked = b;
if (ticksDisplayed > 0 && b == false)
radioButton2.Checked = true;
if(trackBarHours.Value == 0 && trackBarMinutes.Value == 0 && trackBarSeconds.Value == 0)
{
btnPause.Enabled = false;
btnReset.Enabled = false;
}
else
{
btnPause.Enabled = false;
btnReset.Enabled = true;
}
//UpdateTime();
}
private void RichTextBox1_Enter(object sender, EventArgs e)
{
btnStart.Focus();
}
private void UpdateTime()
{
if (ticksDisplayed > 0)
btnReset.Enabled = true;
richTextBox1.Text = GetTimeString(watch.Elapsed);
optionsfile.SetKey("result", result.ToString());
}
private string GetTimeString(TimeSpan elapsed)
{
result = string.Empty;
//calculate difference in ticks
diff = elapsed.Ticks - previousTicks;
if (radioButton1.Checked == true)
{ //counting up
ticksDisplayed += diff;
}
else
{ //counting down
ticksDisplayed -= diff;
}
if (ticksDisplayed < 0)
{
ticksDisplayed = 0;
}
//Make ticksDisplayed to regular time to display in richtextbox
TimeSpan ctimeSpan = new TimeSpan(ticksDisplayed);
result = string.Format("{0:00}:{1:00}:{2:00}.{3:000}",
ctimeSpan.Hours,
ctimeSpan.Minutes,
ctimeSpan.Seconds,
ctimeSpan.Milliseconds);
previousTicks = elapsed.Ticks;
return result;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btnStart_Click(object sender, EventArgs e)
{
if (btnStart.Text == "START")
{
watch.Reset();
//Here
TimeSpan ctimeSpan = new TimeSpan(0, trackBarHours.Value, trackBarMinutes.Value, trackBarSeconds.Value, 0);
diff = 0;
previousTicks = 0;
ticksDisplayed = ctimeSpan.Ticks;
watch.Start();
btnStart.Text = "STOP";
btnPause.Enabled = true;
btnReset.Enabled = true;
timer1.Enabled = true;
}
else
{
watch.Stop();
btnStart.Text = "START";
btnPause.Text = "PAUSE";
btnPause.Enabled = false;
if (trackBarHours.Value == 0 && trackBarMinutes.Value == 0 && trackBarSeconds.Value == 0 && ticksDisplayed == 0)
{
btnReset.Enabled = false;
}
else
{
btnReset.Enabled = true;
}
if (ticksDisplayed > 0)
btnReset.Enabled = true;
timer1.Enabled = false;
}
}
private void btnReset_Click(object sender, EventArgs e)
{
watch.Reset();
if (btnStart.Text == "STOP")
watch.Start();
diff = 0;
previousTicks = 0;
ticksDisplayed = 0;
trackBarHours.Value = 0;
trackBarMinutes.Value = 0;
trackBarSeconds.Value = 0;
if (trackBarHours.Value == 0 && trackBarMinutes.Value == 0 && trackBarSeconds.Value == 0)
{
btnReset.Enabled = false;
}
else
{
btnReset.Enabled = true;
}
UpdateTime();
}
private void trackBarHours_Scroll(object sender, EventArgs e)
{
//get ticksDisplayed as TimeSpan
TimeSpan ctimeSpan = new TimeSpan(ticksDisplayed);
//change only the hour
TimeSpan htimeSpan = new TimeSpan(ctimeSpan.Days, trackBarHours.Value, ctimeSpan.Minutes, ctimeSpan.Seconds, ctimeSpan.Milliseconds);
//set it to ticksDisplayed and update.
ticksDisplayed = htimeSpan.Ticks;
if (trackBarSeconds.Value == 0 && trackBarHours.Value == 0 && trackBarMinutes.Value == 0)
btnStart.Enabled = false;
if (trackBarHours.Value > 0)
{
btnStart.Enabled = true;
btnReset.Enabled = true;
}
optionsfile.SetKey("trackbarhours", trackBarHours.Value.ToString());
UpdateTime();
}
private void trackBarMinutes_Scroll(object sender, EventArgs e)
{
TimeSpan ctimeSpan = new TimeSpan(ticksDisplayed);
TimeSpan mtimeSpan = new TimeSpan(ctimeSpan.Days, ctimeSpan.Hours, trackBarMinutes.Value, ctimeSpan.Seconds, ctimeSpan.Milliseconds);
ticksDisplayed = mtimeSpan.Ticks;
if (trackBarSeconds.Value == 0 && trackBarHours.Value == 0 && trackBarMinutes.Value == 0)
btnStart.Enabled = false;
if (trackBarMinutes.Value > 0)
{
btnStart.Enabled = true;
btnReset.Enabled = true;
}
optionsfile.SetKey("trackbarminutes", trackBarMinutes.Value.ToString());
UpdateTime();
}
private void trackBarSeconds_Scroll(object sender, EventArgs e)
{
TimeSpan ctimeSpan = new TimeSpan(ticksDisplayed);
TimeSpan stimeSpan = new TimeSpan(ctimeSpan.Days, ctimeSpan.Hours, ctimeSpan.Minutes, trackBarSeconds.Value, ctimeSpan.Milliseconds);
ticksDisplayed = stimeSpan.Ticks;
if (trackBarSeconds.Value == 0 && trackBarHours.Value == 0 && trackBarMinutes.Value == 0)
btnStart.Enabled = false;
if (trackBarSeconds.Value > 0)
{
btnStart.Enabled = true;
btnReset.Enabled = true;
}
optionsfile.SetKey("trackbarseconds", trackBarSeconds.Value.ToString());
UpdateTime();
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
optionsfile.SetKey("radiobutton1", radioButton1.Checked.ToString());
}
private void btnPause_Click(object sender, EventArgs e)
{
if (btnStart.Text == "STOP")
{
if (btnPause.Text == "PAUSE")
{
btnPause.Text = "CONTINUE";
watch.Stop();
timer1.Enabled = false;
}
else
{
btnPause.Text = "PAUSE";
watch.Start();
timer1.Enabled = true;
}
}
}
private void timer1_Tick(object sender, EventArgs e)
{
UpdateTime();
}
}
}
Now for example when running the application and it's loading the values from a saved text file the values of the trackBars fro example: Hours = 1 Minutes = 10 Seconds = 50
If now I will change one of the trackBars values the other values in the richTextBox will change to 00 the other two trackBars will keep in the same values but the values in the riachTextBox will be change to 00 for both trackBars.
For example I'm running the application first time in the richTextBox the time is: 01:10:50.000 the trackBars values are the same 1 10 50 now I'm changing the value of 01 the hours trackBar to 05 the other two trackBars will stay on values 10 and 50 but in the richTextBox the 10 and 50 will be reset to 00:00.
Can't figure out why.
This is the class t=for saving/loading the settings:
/*----------------------------------------------------------------
* Module Name : OptionsFile
* Description : Saves and retrievs application options
* Author : Danny
* Date : 10/02/2010
* Revision : 1.00
* --------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Configuration;
/*
* Introduction :
*
* This module helps in saving application options
*
*
* Typical file could look like this:
* user_color=Red
* time_left=30
*
*
*
*
*
* */
namespace DannyGeneral
{
class OptionsFile
{
/*----------------------------------------
* P R I V A T E V A R I A B L E S
* ---------------------------------------*/
/*---------------------------------
* P U B L I C M E T H O D S
* -------------------------------*/
string path_exe;
string temp_settings_file;
string temp_settings_dir;
string Options_File;
StreamWriter sw;
StreamReader sr;
/*----------------------------------------------------------
* Function : OptionsFile
* Description : Constructor
* Parameters : file_name is the name of the file to use
* Return : none
* --------------------------------------------------------*/
///<summary>
///<para>Enter a path with a filename</para>
///</summary>
public OptionsFile(string settingsFileAndPath)
{
if (!File.Exists(settingsFileAndPath))
{
if (!Directory.Exists(Path.GetDirectoryName(settingsFileAndPath)))
{
Directory.CreateDirectory(Path.GetDirectoryName(settingsFileAndPath));
}
File.Create(settingsFileAndPath).Close();
}
path_exe = Path.GetDirectoryName(Application.LocalUserAppDataPath);
Options_File = settingsFileAndPath;
}
/*----------------------------------------------------------
* Function : GetKey
* Description : gets the value of the key.
* Parameters : key
* Return : value of the key if key exist, null if not exist
* --------------------------------------------------------*/
public string GetKey(string key)
{
// string value_of_each_key;
string key_of_each_line;
string line;
int index;
string key_value;
key_value = null;
sr = new StreamReader(Options_File);
while (null != (line = sr.ReadLine()))
{
index = line.IndexOf("=");
// value_of_each_key = line.Substring(index+1);
if (index >= 1)
{
key_of_each_line = line.Substring(0, index);
if (key_of_each_line == key)
{
key_value = line.Substring(key.Length + 1);
}
}
else
{
}
}
sr.Close();
return key_value;
}
/*----------------------------------------------------------
* Function : SetKey
* Description : sets a value to the specified key
* Parameters : key and a value
* Return : none
* --------------------------------------------------------*/
public void SetKey(string key , string value)
{
bool key_was_found_inside_the_loop;
string value_of_each_key;
string key_of_each_line ;
string line;
int index;
key_was_found_inside_the_loop = false;
temp_settings_file = "\\temp_settings_file.txt";
temp_settings_dir = path_exe + #"\temp_settings";
if (!Directory.Exists(temp_settings_dir))
{
Directory.CreateDirectory(temp_settings_dir);
}
sw = new StreamWriter(temp_settings_dir+temp_settings_file);
sr = new StreamReader(Options_File);
while (null != (line = sr.ReadLine()))
{
index = line.IndexOf("=");
key_of_each_line = line.Substring(0, index);
value_of_each_key = line.Substring( index + 1);
// key_value = line.Substring(0,value.Length);
if (key_of_each_line == key)
{
sw.WriteLine(key + "=" + value);
key_was_found_inside_the_loop = true;
}
else
{
sw.WriteLine(key_of_each_line+"="+value_of_each_key);
}
}
if (!key_was_found_inside_the_loop)
{
sw.WriteLine(key + "=" + value);
}
sr.Close();
sw.Close();
File.Delete(Options_File);
File.Move(temp_settings_dir + temp_settings_file, Options_File);
return;
}
public List<float> GetListFloatKey(string keys)
{
List<float> result = new List<float>();
string s = GetKey(keys);
if (s != null)
{
string[] items = s.Split(new char[] { ',' });
float f;
foreach (string item in items)
{
if (float.TryParse(item, out f))
result.Add(f);
}
return result;
}
else
{
return result;
}
}
public void SetListFloatKey(string key, List<float> Values)
{
StringBuilder sb = new StringBuilder();
foreach (float value in Values)
{
sb.AppendFormat(",{0}", value);
}
if (Values.Count == 0)
{
SetKey(key, "");
}
else
{
SetKey(key, sb.ToString().Substring(1));
}
}
public List<int> GetListIntKey(string keys)
{
/*List<int> t = new List<int>();
t = (GetListFloatKey(keys).ConvertAll(x => (int)x));
return t;*/
List<int> result = new List<int>();
string s = GetKey(keys);
if (s != null)
{
string[] items = s.Split(new char[] { ',' });
int f;
foreach (string item in items)
{
if (int.TryParse(item, out f))
result.Add(f);
}
return result;
}
else
{
return result;
}
;
}
public void SetListIntKey(string key, List<int> Values)
{
StringBuilder sb = new StringBuilder();
foreach (int value in Values)
{
sb.AppendFormat(",{0}", value);
}
if (Values.Count == 0)
{
SetKey(key, "");
}
else
{
SetKey(key, sb.ToString().Substring(1));
}
}
/*---------------------------------
* P R I V A T E M E T H O D S
* -------------------------------*/
}
}
What you did is set the "time" in richtextbox as text while you didn't update the ticksDisplayed variable:
richTextBox1.Text = optionsfile.GetKey("result");
When the clock runs it reads the ticksDisplayed variable it adds or subtracts the diff and presents the result. Your ticksDisplayed is zero at this point! Then you change the hour trackbar to 5 and the ticksDisplayed becomes 05:00:00, in ticks of cource. You need to update ticksDisplayed also:
richTextBox1.Text = optionsfile.GetKey("result");
//You need to update ticksDisplayed also!
TimeSpan ctimeSpan = new TimeSpan(0, trackBarHours.Value, trackBarMinutes.Value, trackBarSeconds.Value, 0);
ticksDisplayed = ctimeSpan.Ticks;
....
....
If you had pressed the start button it whould have worked fine(cause it sets the ticksDisplayed value) but you probably started the timer and the clock without setting the correct ticksDisplayed value.
To change the trackbars to follow the time just add this code in GetTimeString():
private string GetTimeString(TimeSpan elapsed)
{
result = string.Empty;
//calculate difference in ticks
diff = elapsed.Ticks - previousTicks;
if (radioButton1.Checked == true)
{ //counting up
ticksDisplayed += diff;
}
else
{ //counting down
ticksDisplayed -= diff;
}
if (ticksDisplayed < 0)
{
ticksDisplayed = 0;
}
//Make ticksDisplayed to regular time to display in richtextbox
TimeSpan ctimeSpan = new TimeSpan(ticksDisplayed);
//HERE
if( trackBarHours.Value != ctimeSpan.Hours ){ trackBarHours.Value = ctimeSpan.Hours; }
if( trackBarMinutes.Value != ctimeSpan.Minutes){ trackBarMinutes.Value = ctimeSpan.Minutes; }
if( trackBarSeconds.Value != ctimeSpan.Seconds){ trackBarSeconds.Value = ctimeSpan.Seconds; }
result = string.Format("{0:00}:{1:00}:{2:00}.{3:000}",
ctimeSpan.Hours,
ctimeSpan.Minutes,
ctimeSpan.Seconds,
ctimeSpan.Milliseconds);
previousTicks = elapsed.Ticks;
return result;
}

How can I add a designer control the form for setting a target time?

When the timer is getting to this time to stop.
The box is a small richTextBox and above it I added a small label "Set time target".
Either the timer is counting up or down when getting to the target time stop everything.
I'm not sure if using richTextbox or textBox and how to make that the user can change the time input and then to take effect either when the watch/timer are running or if not running so it will stop when getting to the target time.
The format inside the richTextBox/textBox should be 00:00:00 hours/minutes/second
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using DannyGeneral;
namespace StopwatchTimer
{
public partial class Form1 : Form
{
private static readonly Stopwatch watch = new Stopwatch();
private long diff = 0, previousTicks = 0, ticksDisplayed = 0;
private OptionsFile optionsfile = new OptionsFile(Path.GetDirectoryName(Application.LocalUserAppDataPath) + "\\Settings.txt");
private string result;
private bool runOnStart = false;
private bool countingDown = false;
public Form1()
{
InitializeComponent();
richTextBox1.TabStop = false;
richTextBox1.ReadOnly = true;
richTextBox1.BackColor = Color.White;
richTextBox1.Cursor = Cursors.Arrow;
richTextBox1.Enter += RichTextBox1_Enter;
trackBarHours.Value = Convert.ToInt32(optionsfile.GetKey("trackbarhours"));
trackBarMinutes.Value = Convert.ToInt32(optionsfile.GetKey("trackbarminutes"));
trackBarSeconds.Value = Convert.ToInt32(optionsfile.GetKey("trackbarseconds"));
richTextBox1.Text = optionsfile.GetKey("result");
TimeSpan ctimeSpan = new TimeSpan(0, trackBarHours.Value, trackBarMinutes.Value, trackBarSeconds.Value, 0);
ticksDisplayed = ctimeSpan.Ticks;
radioButton1.Checked = GetBool("radiobutton1");
if (ticksDisplayed > 0 && radioButton1.Checked == false)
radioButton2.Checked = true;
if (ticksDisplayed == 0)
radioButton1.Checked = true;
if(trackBarHours.Value == 0 && trackBarMinutes.Value == 0 && trackBarSeconds.Value == 0)
{
btnPause.Enabled = false;
btnReset.Enabled = false;
}
else
{
btnPause.Enabled = false;
btnReset.Enabled = true;
}
runOnStart = GetBool("runonstart");
if(runOnStart == true)
{
autoRunOnStart.Checked = true;
StartOnRun();
}
else
{
autoRunOnStart.Checked = false;
}
}
private void RichTextBox1_Enter(object sender, EventArgs e)
{
btnStart.Focus();
}
private void UpdateTime()
{
if (ticksDisplayed > 0)
btnReset.Enabled = true;
richTextBox1.Text = GetTimeString(watch.Elapsed);
optionsfile.SetKey("result", result.ToString());
}
private string GetTimeString(TimeSpan elapsed)
{
result = string.Empty;
//calculate difference in ticks
diff = elapsed.Ticks - previousTicks;
if (radioButton1.Checked == true)
{ //counting up
ticksDisplayed += diff;
}
else
{
if (countingDown)
{
ticksDisplayed += diff;
}
else
{
//counting down
ticksDisplayed -= diff;
}
}
if (ticksDisplayed < 0)
{
ticksDisplayed = 0;
watch.Stop();
btnStart.Text = "START";
btnPause.Text = "PAUSE";
btnPause.Enabled = false;
if (trackBarHours.Value == 0 && trackBarMinutes.Value == 0 && trackBarSeconds.Value == 0 && ticksDisplayed == 0)
{
btnReset.Enabled = false;
}
timer1.Enabled = false;
}
//Make ticksDisplayed to regular time to display in richtextbox
TimeSpan ctimeSpan = new TimeSpan(ticksDisplayed);
if (trackBarHours.Value != ctimeSpan.Hours) { trackBarHours.Value = ctimeSpan.Hours; }
if (trackBarMinutes.Value != ctimeSpan.Minutes) { trackBarMinutes.Value = ctimeSpan.Minutes; }
if (trackBarSeconds.Value != ctimeSpan.Seconds) { trackBarSeconds.Value = ctimeSpan.Seconds; }
result = string.Format("{0:00}:{1:00}:{2:00}.{3:000}",
ctimeSpan.Hours,
ctimeSpan.Minutes,
ctimeSpan.Seconds,
ctimeSpan.Milliseconds);
previousTicks = elapsed.Ticks;
return result;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btnStart_Click(object sender, EventArgs e)
{
if (btnStart.Text == "START")
{
watch.Reset();
TimeSpan ctimeSpan = new TimeSpan(0, trackBarHours.Value, trackBarMinutes.Value, trackBarSeconds.Value, 0);
diff = 0;
previousTicks = 0;
ticksDisplayed = ctimeSpan.Ticks;
watch.Start();
btnStart.Text = "STOP";
btnPause.Enabled = true;
btnReset.Enabled = true;
timer1.Enabled = true;
}
else
{
watch.Stop();
btnStart.Text = "START";
btnPause.Text = "PAUSE";
btnPause.Enabled = false;
if (trackBarHours.Value == 0 && trackBarMinutes.Value == 0 && trackBarSeconds.Value == 0 && ticksDisplayed == 0)
{
btnReset.Enabled = false;
}
else
{
btnReset.Enabled = true;
}
if (ticksDisplayed > 0)
btnReset.Enabled = true;
timer1.Enabled = false;
}
}
private void btnReset_Click(object sender, EventArgs e)
{
watch.Reset();
diff = 0;
previousTicks = 0;
ticksDisplayed = 0;
trackBarHours.Value = 0;
trackBarMinutes.Value = 0;
trackBarSeconds.Value = 0;
if (btnPause.Text == "PAUSE" && btnStart.Text == "STOP")
watch.Start();
if (trackBarHours.Value == 0 && trackBarMinutes.Value == 0 && trackBarSeconds.Value == 0)
{
btnReset.Enabled = false;
}
else
{
btnReset.Enabled = true;
}
if (radioButton2.Checked && ticksDisplayed == 0)
{
countingDown = true;
radioButton2.Checked = false;
radioButton1.Checked = true;
}
UpdateTime();
}
private void trackBarHours_Scroll(object sender, EventArgs e)
{
//get ticksDisplayed as TimeSpan
TimeSpan ctimeSpan = new TimeSpan(ticksDisplayed);
//change only the hour
TimeSpan htimeSpan = new TimeSpan(ctimeSpan.Days, trackBarHours.Value, ctimeSpan.Minutes, ctimeSpan.Seconds, ctimeSpan.Milliseconds);
//set it to ticksDisplayed and update.
ticksDisplayed = htimeSpan.Ticks;
TrackbarsScrollStates();
optionsfile.SetKey("trackbarhours", trackBarHours.Value.ToString());
UpdateTime();
}
private void trackBarMinutes_Scroll(object sender, EventArgs e)
{
TimeSpan ctimeSpan = new TimeSpan(ticksDisplayed);
TimeSpan mtimeSpan = new TimeSpan(ctimeSpan.Days, ctimeSpan.Hours, trackBarMinutes.Value, ctimeSpan.Seconds, ctimeSpan.Milliseconds);
ticksDisplayed = mtimeSpan.Ticks;
TrackbarsScrollStates();
optionsfile.SetKey("trackbarminutes", trackBarMinutes.Value.ToString());
UpdateTime();
}
private void trackBarSeconds_Scroll(object sender, EventArgs e)
{
TimeSpan ctimeSpan = new TimeSpan(ticksDisplayed);
TimeSpan stimeSpan = new TimeSpan(ctimeSpan.Days, ctimeSpan.Hours, ctimeSpan.Minutes, trackBarSeconds.Value, ctimeSpan.Milliseconds);
ticksDisplayed = stimeSpan.Ticks;
TrackbarsScrollStates();
optionsfile.SetKey("trackbarseconds", trackBarSeconds.Value.ToString());
UpdateTime();
}
private void TrackbarsScrollStates()
{
if (trackBarSeconds.Value == 0 && trackBarHours.Value == 0 && trackBarMinutes.Value == 0)
btnReset.Enabled = false;
if (trackBarSeconds.Value > 0 || trackBarHours.Value > 0 || trackBarMinutes.Value > 0)
btnReset.Enabled = true;
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
optionsfile.SetKey("radiobutton1", radioButton1.Checked.ToString());
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
optionsfile.SetKey("trackbarhours", trackBarHours.Value.ToString());
optionsfile.SetKey("trackbarminutes", trackBarMinutes.Value.ToString());
optionsfile.SetKey("trackbarseconds", trackBarSeconds.Value.ToString());
}
private void btnPause_Click(object sender, EventArgs e)
{
if (btnStart.Text == "STOP")
{
if (btnPause.Text == "PAUSE")
{
btnPause.Text = "CONTINUE";
watch.Stop();
timer1.Enabled = false;
}
else
{
btnPause.Text = "PAUSE";
watch.Start();
timer1.Enabled = true;
}
}
}
private void timer1_Tick(object sender, EventArgs e)
{
UpdateTime();
}
private void autoRunOnStart_CheckedChanged(object sender, EventArgs e)
{
if (autoRunOnStart.Checked)
{
runOnStart = true;
}
else
{
runOnStart = false;
}
optionsfile.SetKey("runonstart", runOnStart.ToString());
}
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
countingDown = false;
}
private void StartOnRun()
{
watch.Reset();
TimeSpan ctimeSpan = new TimeSpan(0, trackBarHours.Value, trackBarMinutes.Value, trackBarSeconds.Value, 0);
diff = 0;
previousTicks = 0;
ticksDisplayed = ctimeSpan.Ticks;
watch.Start();
btnStart.Text = "STOP";
btnPause.Enabled = true;
btnReset.Enabled = true;
timer1.Enabled = true;
}
private bool GetBool(string keyname)
{
string radiobutton1 = optionsfile.GetKey(keyname);
bool b;
bool.TryParse(radiobutton1.Trim(), out b);
return b;
}
}
}
You dont need a richtextbox. Use a DateTimePicker. Go to the properties and set:
Format : Custom
ShowUpDown : True
CustomFormat : HH:mm:ss
When ever you want to get the hour, minutes and seconds:
int hour = dateTimePicker1.Value.Hour;
int minutes = dateTimePicker1.Value.Minute;
int seconds = dateTimePicker1.Value.Second;

C# Windows Form snake

I have this simple snake game, my problem is that the tails wont add when it reaches three tails.
namespace Snake
{
public partial class Form1 : Form
{
bool left = false, right = false;
bool top = false, down = false;
PictureBox pic = new PictureBox();
List<PictureBox> tails = new List<PictureBox>();
int score = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
if (((e.KeyChar.ToString() == "a") || (e.KeyChar.ToString() == "A"))&&(right == false))
{
right = false;
top = false;
down = false;
left = true;
}
else if (((e.KeyChar.ToString() == "d") || (e.KeyChar.ToString() == "D"))&& (left == false))
{
top = false;
down = false;
left = false;
right = true;
}
else if (((e.KeyChar.ToString() == "w") || (e.KeyChar.ToString() == "W"))&& (down == false))
{
down = false;
left = false;
right = false;
top = true;
}
else if (((e.KeyChar.ToString() == "s") || (e.KeyChar.ToString() == "S"))&& (top == false))
{
top = false;
left = false;
right = false;
down = true;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
//ticks every 1 sec
if (pic.Location == head.Location)
{
score++;
spawnFood();
tails.Add(addTails());
}
sortLocation();
if (right == true)
{
int r = head.Location.X + head.Height;
head.Location = new Point(r, head.Location.Y);
}
else if(left == true)
{
int l = head.Location.X - head.Height;
head.Location = new Point(l, head.Location.Y);
}
else if (top == true)
{
int t = head.Location.Y - head.Height;
head.Location = new Point(head.Location.X, t);
}
else if (down == true)
{
int d = head.Location.Y + head.Height;
head.Location = new Point(head.Location.X,d);
}
txtScore.Text = score.ToString();
}
private void sortLocation()
{
if (tails.Count == 0)
{
}
else
{
for (int i = 1; i < tails.Count; i++)
{
tails[i].Location = tails[i-1].Location;
}
tails[0].Location = head.Location;
}
}
private PictureBox addTails()
{
PictureBox tail = new PictureBox();
tail.Name = "tail" + score.ToString();
tail.BackColor = Color.Black;
tail.Width = 10;
tail.Height = 10;
this.Controls.Add(tail);
return tail;
}
private void spawnFood()
{
Random rnd = new Random();
int rndLocationX = rnd.Next(10, 50);
int rndLocationY = rnd.Next(10, 50);
pic.BackColor = Color.Red;
pic.Height = 10;
pic.Width = 10;
this.Controls.Add(pic);
if (rndLocationX >= 500)
{
rndLocationX -= 10;
}
if (rndLocationY >= 500)
{
rndLocationY -= 10;
}
pic.Location = new Point(rndLocationX*10,rndLocationY*10);
}
private void Form1_Load(object sender, EventArgs e)
{
timer1.Start();
spawnFood();
}
}
}
for (int i = 1; i < tails.Count; i++)
{
tails[i].Location = tails[i+1].Location;
}
tails[0].Location = head.Location;
Are your tails there just stacked so to speak? That's another thought I might be thinking. I changed the tails[i-1] to tails [i+1]. Check if that does the trick.

Categories