I'm making a small game for myself and my family using a MenuStrip as the action commands in the combat. However, I can't quite figure out how to set up the Click function for the magic. Because the menustrip starts off mostly blank, I can't both create the list of spells and targets, and set up the click methods for those spells. I'm at a bit of an impasse...
This is what it looks like
string[] Spells = { };
string[] Elements = { };
string[] Targets = { };
double[] Power = { };
double[] ManaCost = { };
StreamReader strReader = null;
try
{
FileStream flsStream = new FileStream(Application.StartupPath + "\\Spells.txt", FileMode.Open, FileAccess.Read);
strReader = new StreamReader(flsStream);
while (strReader.Peek() != -1)
{
string line = strReader.ReadLine();
string[] lines = line.Split(':');
Array.Resize(ref Spells, Spells.Length + 1);
Array.Resize(ref Elements, Elements.Length + 1);
Array.Resize(ref Targets, Targets.Length + 1);
Array.Resize(ref Power, Power.Length + 1);
Array.Resize(ref ManaCost, ManaCost.Length + 1);
Spells[Spells.Length - 1] = lines[0];
Elements[Elements.Length - 1] = lines[1];
Targets[Targets.Length - 1] = lines[2];
Power[Power.Length - 1] = Convert.ToDouble(lines[3]);
ManaCost[ManaCost.Length - 1] = Convert.ToDouble(lines[4]);
}
for (int x = 0; x < Spells.Length; x++)
{
mnuMagic.DropDownItems.Add(Spells[x]);
mnuMagic.DropDownItems[x].Name = string.Format("tsmi{0}", Spells[x]);
mnuMagic.DropDownItems[x].Text += string.Format(", {0} MP", ManaCost[x]);
if (Targets[x] == "Single")
{
try
{
if (Foe1.Status != "Dead")
{
if (Foe1.Health > Foe1.MaxHealth / 2)
(mnuMagic.DropDownItems[x] as ToolStripMenuItem).DropDownItems.Add(strFoe1, imgEnemyStatus.Images[0]);
else if (Foe1.Health > Foe1.Health / 4)
(mnuMagic.DropDownItems[x] as ToolStripMenuItem).DropDownItems.Add(strFoe1, imgEnemyStatus.Images[1]);
else
(mnuMagic.DropDownItems[x] as ToolStripMenuItem).DropDownItems.Add(strFoe1, imgEnemyStatus.Images[2]);
}
if (Foe2.Status != "Dead")
{
if (Foe2.Health > Foe2.MaxHealth / 2)
(mnuMagic.DropDownItems[x] as ToolStripMenuItem).DropDownItems.Add(strFoe2, imgEnemyStatus.Images[0]);
else if (Foe2.Health > Foe2.Health / 4)
(mnuMagic.DropDownItems[x] as ToolStripMenuItem).DropDownItems.Add(strFoe2, imgEnemyStatus.Images[1]);
else
(mnuMagic.DropDownItems[x] as ToolStripMenuItem).DropDownItems.Add(strFoe2, imgEnemyStatus.Images[2]);
}
if (Foe3.Status != "Dead")
{
if (Foe3.Health > Foe3.MaxHealth / 2)
(mnuMagic.DropDownItems[x] as ToolStripMenuItem).DropDownItems.Add(strFoe3, imgEnemyStatus.Images[0]);
else if (Foe3.Health > Foe3.Health / 4)
(mnuMagic.DropDownItems[x] as ToolStripMenuItem).DropDownItems.Add(strFoe3, imgEnemyStatus.Images[1]);
else
(mnuMagic.DropDownItems[x] as ToolStripMenuItem).DropDownItems.Add(strFoe3, imgEnemyStatus.Images[2]);
}
if (Foe4.Status != "Dead")
{
if (Foe4.Health > Foe4.MaxHealth / 2)
(mnuMagic.DropDownItems[x] as ToolStripMenuItem).DropDownItems.Add(strFoe4, imgEnemyStatus.Images[0]);
else if (Foe4.Health > Foe4.Health / 4)
(mnuMagic.DropDownItems[x] as ToolStripMenuItem).DropDownItems.Add(strFoe4, imgEnemyStatus.Images[1]);
else
(mnuMagic.DropDownItems[x] as ToolStripMenuItem).DropDownItems.Add(strFoe4, imgEnemyStatus.Images[2]);
}
if (Foe5.Status != "Dead")
{
if (Foe5.Health > Foe5.MaxHealth / 2)
(mnuMagic.DropDownItems[x] as ToolStripMenuItem).DropDownItems.Add(strFoe5, imgEnemyStatus.Images[0]);
else if (Foe5.Health > Foe5.Health / 4)
(mnuMagic.DropDownItems[x] as ToolStripMenuItem).DropDownItems.Add(strFoe5, imgEnemyStatus.Images[1]);
else
(mnuMagic.DropDownItems[x] as ToolStripMenuItem).DropDownItems.Add(strFoe5, imgEnemyStatus.Images[2]);
}
}
catch { }
}
else if (Targets[x] == "Ally")
{
try
{
(mnuMagic.DropDownItems[x] as ToolStripMenuItem).DropDownItems.Add(Fighter1.Name,imgEnemyStatus.Images[0]);
if (Fighter2.Name != null)
(mnuMagic.DropDownItems[x] as ToolStripMenuItem).DropDownItems.Add(Fighter2.Name);
if (Fighter3.Name != null)
(mnuMagic.DropDownItems[x] as ToolStripMenuItem).DropDownItems.Add(Fighter3.Name);
}
catch { }
}
else if (Targets[x] == "All")
{
(mnuMagic.DropDownItems[x] as ToolStripMenuItem).DropDownItems.Add("All Enemies");
}
else if (Targets[x] == "Team")
(mnuMagic.DropDownItems[x] as ToolStripMenuItem).DropDownItems.Add("All Allies");
if (Elements[x] == "Fire")
mnuMagic.DropDownItems[x].ForeColor = Color.Red;
else if (Elements[x] == "Water")
mnuMagic.DropDownItems[x].ForeColor = Color.Blue;
else if (Elements[x] == "Earth")
mnuMagic.DropDownItems[x].ForeColor = Color.FromArgb(255, 128, 0);
else if (Elements[x] == "Wind")
mnuMagic.DropDownItems[x].ForeColor = Color.LimeGreen;
if (ManaCost[x] > Fighter1.Mana) { mnuMagic.DropDownItems[x].Enabled = false; }
}
}
catch { }
}
I think you should start dividing your code into subclasses. It will be very helpfull, even for little games. Here is a little bit of code I fiddled together. It does not handle everything you have, but you can easily extend that functionality. If you need additional informations, please tell me.
public partial class Form1 : Form
{
private double CurrentMana { get; set; } = 50;
private List<BasicSpell> m_lstSpells = new List<BasicSpell>();
private List<BasicTarget> m_lstTargets = new List<BasicTarget>();
public Form1()
{
InitializeComponent();
Init();
try
{
ToolStripMenuItem tsmiMagic = new ToolStripMenuItem("Magic");
foreach (BasicSpell spell in m_lstSpells)
{
ToolStripMenuItem tsmiSpell = spell.ToToolStripMenuItem();
if (spell.CanHitAllEnemies)
{
ToolStripItem tsiAll = tsmiSpell.DropDownItems.Add("All");
tsiAll.Click += (sender, arguments) => m_lstTargets.ForEach((target) => TryCastSpell(spell, target));
}
else { } // This spell can not hit all enemies
for (int i = 0; i < m_lstTargets.Count; i++)
{
BasicTarget target = m_lstTargets[i];
ToolStripItem tsiTarget = tsmiSpell.DropDownItems.Add($"Target {i}: {target.Name}");
tsiTarget.Image = target.StatusImage;
tsiTarget.Click += (sender, arguments) => TryCastSpell(spell, target);
}
tsmiMagic.DropDownItems.Add(tsmiSpell);
}
m_tsCombatOptions.Items.Add(tsmiMagic);
}
catch (Exception ex)
{
MessageBox.Show($"{ex}");
}
}
private void TryCastSpell(BasicSpell spell, BasicTarget target)
{
if (!spell.Cast(target))
{
MessageBox.Show($"You can not cast this spell with your current mana!");
}
}
private void Init()
{
m_lstSpells.Add(new Fireball());
m_lstSpells.Add(new Fireball());
m_lstSpells.Add(new Fireball());
m_lstSpells.Add(new Fireball());
m_lstTargets.Add(new Monster("Reißzahn", 500));
m_lstTargets.Add(new Monster("Reißzahn", 500));
m_lstTargets.Add(new Monster("Reißzahn", 500));
m_lstTargets.Add(new Monster("Reißzahn", 500));
m_lstTargets.Add(new Monster("Reißzahn", 500));
}
}
// TODO: POWER?
[Flags]
public enum Element
{
Fire = 0x0,
Earth = 0x1,
Water = 0x2,
Wind = 0x4
}
public abstract class BasicSpell
{
public string Name { get; set; }
public Element DamageType { get; set; }
public double ManaCost { get; set; }
public bool CanHitAllEnemies { get; set; } = false;
public abstract bool Cast(BasicTarget target);
public ToolStripMenuItem ToToolStripMenuItem()
{
ToolStripMenuItem tsmiSpell = new ToolStripMenuItem();
tsmiSpell.Text = $"{this.Name}, {ManaCost} MP";
return tsmiSpell;
}
}
public class Fireball : BasicSpell
{
public override bool Cast(BasicTarget target)
{
// TODO: Check if castable (maybe add caster as parameter)
target.HP -= 500;
return true;
}
}
public abstract class BasicTarget
{
public enum CombatStatus
{
Alive = 0,
Dead = 1
}
public enum TargetRelation
{
Enemy = 0,
Ally = 1
}
public string Name { get; set; }
public double HP { get; set; }
public CombatStatus Status { get; set; }
public TargetRelation Relation { get; set; }
public Image StatusImage => null;
}
public class Monster : BasicTarget
{
public Monster(string strName, int nHP)
{
this.Name = strName;
this.HP = nHP;
this.Status = CombatStatus.Alive;
this.Relation = TargetRelation.Enemy;
}
}
Related
Form1
public Form1()
{
InitializeComponent();
new GameSetting();
new GameSetting2();
GameTimer.Interval = 60;
GameTimer.Tick += UpdateScreen;
GameTimer.Start();
startGame();
}
private void UpdateScreen(object sender, EventArgs e)
{
if (GameSetting.Gameover == true || GameSetting2.Gameover2 == true)
{
if (KeyInput.KeyInputs(Keys.Enter))
{
startGame();
}
}
else
{
if (KeyInput.KeyInputs(Keys.Right) && GameSetting.Movment != SnakeMovment.Left)
{
GameSetting.Movment = SnakeMovment.Right;
}
else if (KeyInput.KeyInputs(Keys.Left) && GameSetting.Movment != SnakeMovment.Right)
{
GameSetting.Movment = SnakeMovment.Left;
}
else if (KeyInput.KeyInputs(Keys.Up) && GameSetting.Movment != SnakeMovment.Down)
{
GameSetting.Movment = SnakeMovment.Up;
}
else if (KeyInput.KeyInputs(Keys.Down) && GameSetting.Movment != SnakeMovment.Up)
{
GameSetting.Movment = SnakeMovment.Down;
}
PlayerMovment();
}
private void PlayerMovment()
{
for (int i = SnakeBoddy.Count - 1; i >= 0; i--)
{
if (i == 0)
{
switch (GameSetting.Movment)
{
case SnakeMovment.Right:
SnakeBoddy[i].X++;
break;
case SnakeMovment.Left:
SnakeBoddy[i].X--;
break;
case SnakeMovment.Up:
SnakeBoddy[i].Y--;
break;
case SnakeMovment.Down:
SnakeBoddy[i].Y++;
break;
}
GameSetting
class GameSetting
{
public static int Width { get; set; }
public static int Height { get; set; }
public static int SnakeSpeed { get; set; }
public static int GameScore { get; set; }
public static int GamePoint { get; set; }
public static bool Gameover { get; set; }
public static SnakeMovment Movment { get; set; }
public GameSetting()
{
Height = 16;
Width = 16;
Gameover = false;
SnakeSpeed = 60;
Movment = SnakeMovment.Down;
GamePoint = 1;
GameScore = 0;
}
}
How would I make it so that the snake speed is = to SnakeSpeed. I can do something like GameTimer.Interval = 360/GameSetting.SnakeSpeed;but that wouldn't work if I have more than 1 snake + I feel like changing the interval is not the right way, and instead of setting the speed of snake to the interval how would i set it to the snake individually?
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;
}
}
I have simple binary search tree
public class BNode
{
public int item;
public BNode right;
public BNode left;
public BNode(int item)
{
this.item = item;
}
}
public class BTree
{
private BNode _root;
private int _count;
private IComparer<int> _comparer = Comparer<int>.Default;
public BTree()
{
_root = null;
_count = 0;
}
public bool Add(int Item)
{
if (_root == null)
{
_root = new BNode(Item);
_count++;
return true;
}
else
{
return Add_Sub(_root, Item);
}
}
private bool Add_Sub(BNode Node, int Item)
{
if (_comparer.Compare(Node.item, Item) < 0)
{
if (Node.right == null)
{
Node.right = new BNode(Item);
_count++;
return true;
}
else
{
return Add_Sub(Node.right, Item);
}
}
else if (_comparer.Compare(Node.item, Item) > 0)
{
if (Node.left == null)
{
Node.left = new BNode(Item);
_count++;
return true;
}
else
{
return Add_Sub(Node.left, Item);
}
}
else
{
return false;
}
}
public void Print()
{
Print(_root, 4);
}
public void Print(BNode p, int padding)
{
if (p != null)
{
if (p.right != null)
{
Print(p.right, padding + 4);
}
if (padding > 0)
{
Console.Write(" ".PadLeft(padding));
}
if (p.right != null)
{
Console.Write("/\n");
Console.Write(" ".PadLeft(padding));
}
Console.Write(p.item.ToString() + "\n ");
if (p.left != null)
{
Console.Write(" ".PadLeft(padding) + "\\\n");
Print(p.left, padding + 4);
}
}
}
}
where I can insert values like
BTree btr = new BTree();
btr.Add(6);
btr.Add(2);
btr.Add(3);
btr.Add(11);
btr.Add(30);
btr.Add(9);
btr.Add(13);
btr.Add(18);
I want to display my tree within my console application. I have a btr.Print(); which displays my tree from left to right (6 is the root) - but I'm not happy with it.
Question: Is there a better way to display this tree within a console application? Even a improvement of this Print() would help me.
I've ended up with the following method that allows you to print arbitrary subtree:
public static class BTreePrinter
{
class NodeInfo
{
public BNode Node;
public string Text;
public int StartPos;
public int Size { get { return Text.Length; } }
public int EndPos { get { return StartPos + Size; } set { StartPos = value - Size; } }
public NodeInfo Parent, Left, Right;
}
public static void Print(this BNode root, string textFormat = "0", int spacing = 1, int topMargin = 2, int leftMargin = 2)
{
if (root == null) return;
int rootTop = Console.CursorTop + topMargin;
var last = new List<NodeInfo>();
var next = root;
for (int level = 0; next != null; level++)
{
var item = new NodeInfo { Node = next, Text = next.item.ToString(textFormat) };
if (level < last.Count)
{
item.StartPos = last[level].EndPos + spacing;
last[level] = item;
}
else
{
item.StartPos = leftMargin;
last.Add(item);
}
if (level > 0)
{
item.Parent = last[level - 1];
if (next == item.Parent.Node.left)
{
item.Parent.Left = item;
item.EndPos = Math.Max(item.EndPos, item.Parent.StartPos - 1);
}
else
{
item.Parent.Right = item;
item.StartPos = Math.Max(item.StartPos, item.Parent.EndPos + 1);
}
}
next = next.left ?? next.right;
for (; next == null; item = item.Parent)
{
int top = rootTop + 2 * level;
Print(item.Text, top, item.StartPos);
if (item.Left != null)
{
Print("/", top + 1, item.Left.EndPos);
Print("_", top, item.Left.EndPos + 1, item.StartPos);
}
if (item.Right != null)
{
Print("_", top, item.EndPos, item.Right.StartPos - 1);
Print("\\", top + 1, item.Right.StartPos - 1);
}
if (--level < 0) break;
if (item == item.Parent.Left)
{
item.Parent.StartPos = item.EndPos + 1;
next = item.Parent.Node.right;
}
else
{
if (item.Parent.Left == null)
item.Parent.EndPos = item.StartPos - 1;
else
item.Parent.StartPos += (item.StartPos - 1 - item.Parent.EndPos) / 2;
}
}
}
Console.SetCursorPosition(0, rootTop + 2 * last.Count - 1);
}
private static void Print(string s, int top, int left, int right = -1)
{
Console.SetCursorPosition(left, top);
if (right < 0) right = left + s.Length;
while (Console.CursorLeft < right) Console.Write(s);
}
}
As you can see, I've added some parameters that affect the formatting. By default it produces the most compact representation.
In order to play with it, I've modified the BTree class as follows:
public class BTree
{
// ...
public BNode Root { get { return _root; } }
public void Print()
{
Root.Print();
}
}
Using your sample data, here are some results:
btr.Root.Print();
btr.Root.Print(textFormat: "(0)", spacing: 2);
UPDATE: IMO the default format above is compact and readable, but just for fun, adjusted the algorithm to produce more "graphical" output (textFormat and spacing parameters removed):
public static class BTreePrinter
{
class NodeInfo
{
public BNode Node;
public string Text;
public int StartPos;
public int Size { get { return Text.Length; } }
public int EndPos { get { return StartPos + Size; } set { StartPos = value - Size; } }
public NodeInfo Parent, Left, Right;
}
public static void Print(this BNode root, int topMargin = 2, int leftMargin = 2)
{
if (root == null) return;
int rootTop = Console.CursorTop + topMargin;
var last = new List<NodeInfo>();
var next = root;
for (int level = 0; next != null; level++)
{
var item = new NodeInfo { Node = next, Text = next.item.ToString(" 0 ") };
if (level < last.Count)
{
item.StartPos = last[level].EndPos + 1;
last[level] = item;
}
else
{
item.StartPos = leftMargin;
last.Add(item);
}
if (level > 0)
{
item.Parent = last[level - 1];
if (next == item.Parent.Node.left)
{
item.Parent.Left = item;
item.EndPos = Math.Max(item.EndPos, item.Parent.StartPos);
}
else
{
item.Parent.Right = item;
item.StartPos = Math.Max(item.StartPos, item.Parent.EndPos);
}
}
next = next.left ?? next.right;
for (; next == null; item = item.Parent)
{
Print(item, rootTop + 2 * level);
if (--level < 0) break;
if (item == item.Parent.Left)
{
item.Parent.StartPos = item.EndPos;
next = item.Parent.Node.right;
}
else
{
if (item.Parent.Left == null)
item.Parent.EndPos = item.StartPos;
else
item.Parent.StartPos += (item.StartPos - item.Parent.EndPos) / 2;
}
}
}
Console.SetCursorPosition(0, rootTop + 2 * last.Count - 1);
}
private static void Print(NodeInfo item, int top)
{
SwapColors();
Print(item.Text, top, item.StartPos);
SwapColors();
if (item.Left != null)
PrintLink(top + 1, "┌", "┘", item.Left.StartPos + item.Left.Size / 2, item.StartPos);
if (item.Right != null)
PrintLink(top + 1, "└", "┐", item.EndPos - 1, item.Right.StartPos + item.Right.Size / 2);
}
private static void PrintLink(int top, string start, string end, int startPos, int endPos)
{
Print(start, top, startPos);
Print("─", top, startPos + 1, endPos);
Print(end, top, endPos);
}
private static void Print(string s, int top, int left, int right = -1)
{
Console.SetCursorPosition(left, top);
if (right < 0) right = left + s.Length;
while (Console.CursorLeft < right) Console.Write(s);
}
private static void SwapColors()
{
var color = Console.ForegroundColor;
Console.ForegroundColor = Console.BackgroundColor;
Console.BackgroundColor = color;
}
}
and the result is:
This is my take at it:
I've added PrintPretty to BNode, and I've removed the second Print function you had in BTree.
(Edit: I made the tree more lisible by changing the original chars to draw the branches of the tree)
static void Main(string[] args)
{
BTree btr = new BTree();
btr.Add(6);
btr.Add(2);
btr.Add(3);
btr.Add(11);
btr.Add(30);
btr.Add(9);
btr.Add(13);
btr.Add(18);
btr.Print();
}
public class BNode
{
public int item;
public BNode right;
public BNode left;
public BNode(int item)
{
this.item = item;
}
public void PrintPretty(string indent, bool last)
{
Console.Write(indent);
if (last)
{
Console.Write("└─");
indent += " ";
}
else
{
Console.Write("├─");
indent += "| ";
}
Console.WriteLine(item);
var children = new List<BNode>();
if (this.left != null)
children.Add(this.left);
if (this.right != null)
children.Add(this.right);
for (int i = 0; i < children.Count; i++)
children[i].PrintPretty(indent, i == children.Count - 1);
}
}
public class BTree
{
private BNode _root;
private int _count;
private IComparer<int> _comparer = Comparer<int>.Default;
public BTree()
{
_root = null;
_count = 0;
}
public bool Add(int Item)
{
if (_root == null)
{
_root = new BNode(Item);
_count++;
return true;
}
else
{
return Add_Sub(_root, Item);
}
}
private bool Add_Sub(BNode Node, int Item)
{
if (_comparer.Compare(Node.item, Item) < 0)
{
if (Node.right == null)
{
Node.right = new BNode(Item);
_count++;
return true;
}
else
{
return Add_Sub(Node.right, Item);
}
}
else if (_comparer.Compare(Node.item, Item) > 0)
{
if (Node.left == null)
{
Node.left = new BNode(Item);
_count++;
return true;
}
else
{
return Add_Sub(Node.left, Item);
}
}
else
{
return false;
}
}
public void Print()
{
_root.PrintPretty("", true);
}
}
This is the result (more compact, as I mentioned):
Edit: the following code has been modified in order to show the info about left-right:
static void Main(string[] args)
{
BTree btr = new BTree();
btr.Add(6);
btr.Add(2);
btr.Add(3);
btr.Add(11);
btr.Add(30);
btr.Add(9);
btr.Add(13);
btr.Add(18);
btr.Print();
}
public enum NodePosition
{
left,
right,
center
}
public class BNode
{
public int item;
public BNode right;
public BNode left;
public BNode(int item)
{
this.item = item;
}
private void PrintValue(string value, NodePosition nodePostion)
{
switch (nodePostion)
{
case NodePosition.left:
PrintLeftValue(value);
break;
case NodePosition.right:
PrintRightValue(value);
break;
case NodePosition.center:
Console.WriteLine(value);
break;
default:
throw new NotImplementedException();
}
}
private void PrintLeftValue(string value)
{
Console.ForegroundColor = ConsoleColor.Magenta;
Console.Write("L:");
Console.ForegroundColor = (value == "-") ? ConsoleColor.Red : ConsoleColor.Gray;
Console.WriteLine(value);
Console.ForegroundColor = ConsoleColor.Gray;
}
private void PrintRightValue(string value)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.Write("R:");
Console.ForegroundColor = (value == "-") ? ConsoleColor.Red : ConsoleColor.Gray;
Console.WriteLine(value);
Console.ForegroundColor = ConsoleColor.Gray;
}
public void PrintPretty(string indent, NodePosition nodePosition, bool last, bool empty)
{
Console.Write(indent);
if (last)
{
Console.Write("└─");
indent += " ";
}
else
{
Console.Write("├─");
indent += "| ";
}
var stringValue = empty ? "-" : item.ToString();
PrintValue(stringValue, nodePosition);
if(!empty && (this.left != null || this.right != null))
{
if (this.left != null)
this.left.PrintPretty(indent, NodePosition.left, false, false);
else
PrintPretty(indent, NodePosition.left, false, true);
if (this.right != null)
this.right.PrintPretty(indent, NodePosition.right, true, false);
else
PrintPretty(indent, NodePosition.right, true, true);
}
}
}
public class BTree
{
private BNode _root;
private int _count;
private IComparer<int> _comparer = Comparer<int>.Default;
public BTree()
{
_root = null;
_count = 0;
}
public bool Add(int Item)
{
if (_root == null)
{
_root = new BNode(Item);
_count++;
return true;
}
else
{
return Add_Sub(_root, Item);
}
}
private bool Add_Sub(BNode Node, int Item)
{
if (_comparer.Compare(Node.item, Item) < 0)
{
if (Node.right == null)
{
Node.right = new BNode(Item);
_count++;
return true;
}
else
{
return Add_Sub(Node.right, Item);
}
}
else if (_comparer.Compare(Node.item, Item) > 0)
{
if (Node.left == null)
{
Node.left = new BNode(Item);
_count++;
return true;
}
else
{
return Add_Sub(Node.left, Item);
}
}
else
{
return false;
}
}
public void Print()
{
_root.PrintPretty("", NodePosition.center, true, false);
}
}
The result:
If your tree is in the form of a QuickGraph IBidirectionalGraph, you could print it recursively like this:
static void PrintVertex<TVertex>(IBidirectionalGraph<TVertex, IEdge<TVertex>> graph, TVertex vertex, Func<TVertex, string> labelSelector, bool[] isLastVertexIntendations = null)
{
var prefix = string.Concat(Enumerable.Concat(
/*up to last*/isLastVertexIntendations.NeverNull().Reverse().Skip(1).Reverse().Select(isLast => isLast ? " " : "│ "),
/*last*/isLastVertexIntendations.NeverNull().Reverse().Take(1).Select(isLast => isLast ? "└─" : "├─")
));
Console.Write(prefix);
Console.WriteLine(labelSelector(vertex));
var edges = graph.OutEdges(vertex);
foreach (var edge in edges)
{
PrintVertex(graph, edge.Target, labelSelector, isLastVertexIntendations: isLastVertexIntendations.NeverNull().Concat(new[] { edge == edges.Last() }).ToArray());
}
}
Currently I am learning how to build my own linked list in C#. I have created a function called AddTrees that adds a tree to the end of the list. User create their trees through textboxes input:tree_name, tree_height, tree_price and tree_instock. I am requesting help with my InsertTree which is not inserting a tree between current and current.next_tree? But instead of instead of inserting it between, it adds it to the top of the list.
namespace Tree_farm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public class TheTrees
{
private string tree_type = " ";
private int tree_height = 0;
public double tree_price = 0;
private int tree_instock = 0;
public TheTrees next_tree;
public TheTrees(string newtree, int newheight, int newinstock, double newprice)
{
tree_type = newtree;
tree_height = newheight;
tree_price = newprice;
tree_instock = newinstock;
next_tree = null;
}
public override string ToString()
{
return tree_type + " " + tree_height + " " + tree_price + " " + tree_instock;
}
}
public class ListForTrees
{
public TheTrees first_tree;
public TheTrees last_tree;
public int count = 0;
public ListForTrees(TheTrees new_tree)
{
first_tree = new_tree;
last_tree = new_tree;
count = 1;
}
public ListForTrees()
{
}
public void InsertTree(TheTrees new_tree)
{
TheTrees current = first_tree;
if (count == 0)
{
first_tree = new_tree;
last_tree = new_tree;
count = 1;
}
else if (count != 0)
{
if (new_tree.tree_price <= first_tree.tree_price)
{
new_tree.next_tree = first_tree;
first_tree = new_tree;
}
else if (new_tree.tree_price >= last_tree.tree_price)
{
last_tree.next_tree = new_tree;
last_tree = new_tree;
}
else
{
while (new_tree.tree_price > current.next_tree.tree_price)
{
current.next_tree = current;
}
new_tree.next_tree = current.next_tree;
current.next_tree = new_tree;
}
count++;
}
}
public void AddTree(TheTrees new_tree)
{
TheTrees current = first_tree;
if (count == 0)
{
first_tree = new_tree;
last_tree = new_tree;
count = 1;
}
else if (count != 0)
{
if (new_tree.tree_price <= first_tree.tree_price)
{
new_tree.next_tree = first_tree;
first_tree = new_tree;
}
else if (new_tree.tree_price >= last_tree.tree_price)
{
last_tree.next_tree = new_tree;
last_tree = new_tree;
}
else
{
while (new_tree.tree_price > current.next_tree.tree_price)
{
current = current.next_tree;
}
new_tree.next_tree = current.next_tree;
current.next_tree = new_tree;
}
count++;
}
}
public void ClearTrees()
{
first_tree = null;
count = 0;
}
}
ListForTrees mainlist = new ListForTrees();
private void Form1_Load(object sender, EventArgs e)
{
}
private void BtnInsertTree_Click(object sender, EventArgs e)
{
//Insert Code
try
{
int height = Convert.ToInt32(TxtTreeHeight.Text);
int stock = Convert.ToInt32(TxtTreeStock.Text);
double price = Convert.ToDouble(TxtTreePrice.Text);
TheTrees treeinsert = new TheTrees(TxtTreeName.Text, height, stock, price);
mainlist.InsertTree(treeinsert);
}
catch
{
MessageBox.Show("Please check intput fields");
}
}
private void BtnAddTree_Click(object sender, EventArgs e)
{
try
{
int height = Convert.ToInt32(TxtTreeHeight.Text);
int stock = Convert.ToInt32(TxtTreeStock.Text);
double price = Convert.ToDouble(TxtTreePrice.Text);
TheTrees treeadd = new TheTrees(TxtTreeName.Text, height, stock, price);
mainlist.AddTree(treeadd);
}
catch
{
MessageBox.Show("Please check intput fields");
}
}
}
}
First, I think your expected result is wrong. It appears you want the linked list sorted in order of price (lowest to highest). If so, Cypress should actually go at the end of your list, not in the middle (80.00 > 50.00 > 2.00).
Secondly, I believe the issue rests in your while loop.
while (new_tree.tree_price > current.next_tree.tree_price)
{
current.next_tree = current;
}
I believe what you're trying to do is walk down your linked list. What you're actually doing is mucking up your linked list by changing current.next_tree to point to itself. Changing it to the following is a positive first step towards correcting your algorithm:
while (new_tree.tree_price > current.next_tree.tree_price)
{
current = current.next_tree;
}
EDIT: It should be noted that I do not get the same error that you get in your original post. When I insert items in the same order that you claim to, I get the list in correct sorted order. This is due to the fact that Cypress goes to the end, as expected. How did you get the result that you claim in the question?
To start off I am new to C# and I am in need of some help. I a class that contains a list. I can set the items in the list from the application but not from the class(where it needs to be done). I am also needing to move an event to class as well. This works in the app as well. Any help with this is greatly appreciated. Below is the code from my class:
namespace CarRace
{
class Cars
{
public string Name { get; set; }
public int StartPOS { get; set; }
public int Speed { get; set; }
public int CurPOS { get; set; }
public double Location { get; set; }
public Cars(string Name, int StartPOS, int Speed, int CurPOS, long Location)
{
this.Name = Name;
this.StartPOS = StartPOS;
this.Speed = Speed;
this.CurPOS = 0;
this.Location = 0;
}
public static int CompareCurrentLocation(Cars c1, Cars c2)
{
return c2.Location.CompareTo(c1.Location);
}
}
}
I am needing to add this to the class:
if (File.Exists("NewRace.xml"))
{
XDocument doc = XDocument.Load("NewRace.xml");
var nCars = doc.Descendants("Car").Select(x => new Cars("", 0, 0, 0, 0)
{
Name = x.Attribute("Name").Value,
StartPOS = int.Parse(x.Attribute("StartPOS").Value),
Speed = int.Parse(x.Attribute("Speed").Value),
CurPOS = 0
});
}
And this:
int p = 1;
int prevPOS = 1;
DateTime? PrevTime;
double dist = 0;
double PrevLoc = 0;
if (i == 0)
{
return;
}
foreach (var car in RaceList)
{
dist = (((car.Speed * 1609.344) * 1) / 1609.344) / 3600;
car.Location = car.Location + dist;
}
Comparison<Cars> compLoc = Cars.CompareCurrentLocation;
RaceList.Sort(compLoc);
PrevTime = DateTime.Now;
foreach (var car in RaceList)
{
if (car.Location != PrevLoc)
{
car.CurPOS = p;
}
else
{
car.CurPOS = prevPOS;
}
prevPOS = car.CurPOS;
PrevLoc = car.Location;
p++;
}
Thanks
Thanks for all of your replies. I tried the car.speed/3600 but only get
back 0 for that so I did the long way. I did get everything working
the way I needed it to.
That's because you are doing an integer division (car.Speed is of type int) so the fractional part of the result is discarded. Since the car's speed is less than 3600 this would hence always result in zero. You can avoid this by casting car.Speed to a double first - this should produce the result you want:
dist = (double)car.Speed / 3600;
Thanks for all of your replies. I tried the car.speed/3600 but only get back 0 for that so I did the long way. I did get everything working the way I needed it to. I am a rookie at this and any tips are greatly appreciated. Below is the code I have updated to.
namespace CarRace
{
class Cars
{
public string Name { get; set; }
public int StartPOS { get; set; }
public int CurPOS { get; set; }
public int Speed { get; set; }
public double Location { get; set; }
public string Make { get; set; }
private static List<Cars> CarList;
private static string ProgPart;
public Cars(string Name, int StartPOS, int CurPOS, int Speed, double Location, string Make)
{
this.Name = Name;
this.StartPOS = StartPOS;
this.CurPOS = CurPOS;
this.Speed = Speed;
this.Location = Location;
this.Make = Make;
}
public static List<Cars> FillList()
{
return CarList;
}
public static void Main()
{
try
{
bool Prog = false;
//Get Part to display
while (!Prog)
{
Console.WriteLine("Select the part you would like to test.(1 or 2)");
ProgPart = Console.ReadLine();
if (ProgPart == "1" || ProgPart == "2")
{
Prog = true;
}
}
Console.WriteLine("----------------------------------------");
//Read XML File and set the CarList
if (File.Exists("NewRace.xml"))
{
XDocument doc = XDocument.Load("NewRace.xml");
var nCars = doc.Descendants("Car").Select(x => new Cars("", 0, 0, 0, 0, "")
{
Name = x.Attribute("Name").Value,
StartPOS = int.Parse(x.Element("StartPOS").Value),
CurPOS = 0,
Speed = int.Parse(x.Element("Speed").Value),
Location = double.Parse(x.Element("Location").Value),
Make = x.Attribute("Make").Value
});
CarList = new List<Cars>();
foreach (var car1 in nCars)
{
if (ProgPart == "1")
{
CarList.Add(new Cars(car1.Name, car1.StartPOS, car1.CurPOS, car1.Speed, car1.Location, car1.Make));
}
else
{
CarList.Add(new Cars(car1.Name, car1.StartPOS, car1.CurPOS, 0, car1.Location, car1.Make));
}
}
}
else
{
Console.WriteLine("File Not Found!");
Console.ReadKey();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
public static int CompareCurrentLocation(Cars c1, Cars c2)
{
return c2.Location.CompareTo(c1.Location);
}
public static Boolean UpdateLeaderBoard(long i)
{
try
{
int p = 1;
int prevPOS = 1;
DateTime? PrevTime;
double dist = 0;
double prevLocation = 0;
if (i == 0)
{
return false;
}
foreach (var car in CarList)
{
if (ProgPart == "2")
{
switch (car.Make)
{
case "300ZX":
//Slow continuous gain of speed by percentage after 60 with top speed of 320.
if (i <= 15)
{
car.Speed = car.Speed + (60 / 10);
}
else if (car.Speed < 320)
{
double percent = (double)(car.Speed * .1);
if ((Convert.ToInt32(car.Speed + percent)) > 320)
{
car.Speed = 320;
}
else
{
car.Speed = Convert.ToInt32(car.Speed + (percent));
}
}
break;
case "Camero":
//0-60 4 seconds 60-220 20 seconds Top 220
if (i <= 4)
{
car.Speed = car.Speed + (60 / 4);
}
else if (i <= 20)
{
car.Speed = car.Speed + 10;
}
break;
case "Mustang":
//0-top(210) 25 seconds
if (car.Speed <= 200)
{
car.Speed = car.Speed + (200 / 20);
}
break;
case "VW Bug":
//Constant Speed
car.Speed = 165;
break;
default:
Console.WriteLine("Make not found");
break;
}
}
//Set Cars Current Location
dist = (((car.Speed * 1609.344) * 1) / 1609.344) / 3600;
car.Location = car.Location + dist;
}
//Sort list by location
Comparison<Cars> compLoc = Cars.CompareCurrentLocation;
CarList.Sort(compLoc);
PrevTime = DateTime.Now;
//Set the Current Position
foreach (var car in CarList)
{
if (car.Location != prevLocation)
{
car.CurPOS = p;
}
else
{
car.CurPOS = prevPOS;
}
prevPOS = car.CurPOS;
prevLocation = car.Location;
p++;
}
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return false;
}
}
}
}