Issues with syntax c#, unable to use ojects/call get, set, - c#

I am new to C# and have been working on a project for a maze game in a haunted house context.After researching different approaches I have decided to go with using objects and a linked list. However, despite weeks of trying I am struggling with the code and have gotten to the point after hours of reading articles and watching online tutorials that I am now more confused that ever before. I want to go with this approach rather than an array as I feel like this is more efficient and more OOP.
I was thinking of going with a simple if/else structure but for this level of coding I feel it would be too messy.
Any help, constructive criticism or ideas would be highly appreciated as I don't want to give up after so many hours spent on it but I feel its getting to that point. This is my code so far.
Thanks in advance :)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace maze_3
{//open namespace
class Room
{//open class room
private string RoomName;
private Room N = null; // so that when i set the links they are automatically null unless i specify in main
private Room E = null;
private Room S = null;
private Room W = null;
public Room X { get; private set; } // the software implemented this
public void setName(string N) // so that i am able to set the name of the room
{
RoomName = N;
}
public void setN(Room X) // sets the north direction between the objects of the rooms
{
N = X;
}
public void setE(Room X)
{
E = X;
}
public void setW(Room X)
{
W = X;
}
public void setS(Room x)
{
S = X;
}
public Room getN() // want to get a direction from the user, in this case they would input a north direction
{
return N;
}
public Room getE()
{
return E;
}
public Room getS()
{
return S;
}
public Room getW()
{
return W;
}
static void Main(string[] args)// it is asking for a ; here but also says that I should declare it as extern, partial etc
class chamber// its telling me that a ; is expected ???
{//open class chamber
chamber gh = new chamber();// my objects that are the rooms in the haunted house.
chamber kit = new chamber();
chamber Pan = new chamber();
chamber Dun = new chamber();
chamber dr = new chamber();
chamber lib = new chamber();
chamber din = new chamber();
chamber sr = new chamber();
chamber weap = new chamber();
chamber tow = new chamber();
chamber gal = new chamber();
chamber tr = new chamber();
gh.RoomName("Great Hall"); //to set the object name as the Great Hall, all get and set links were available in class
gh.setW(dr); ///I want to set a west direction between my object gh to dr
gh.SetS(kit);// to set a south link between my two objects
dr.setName("Drawing Room");//states that all my setlinks are not valid in the current context- this is for all
dr.setS(lib); //it states the ; is not a valid token in class, struct or interface
kit.setName("Kitchen");// it states that my objects e.g kit is not valid in this current context-this is for all
kit.setS(pan);
pan.setName("Pantry");
pan.SetE(dun); /// this is a dead end in the game
lib.setName("Library ");
lib.setE(din);
din.setName("Dining Room");
din.setN(sr);
din.setE(gal);
din.setS(weap); //dead end in the game
sr.setName("Smoking Room");
sr.setE(tow);//dead end
gal.setName("Treasure Room");
gal.setS(tr)
/// </summary> so i wanted to have the actual game play to follow a linked list with a if else structure.
int finish = 0;
string choice;
Room current;
current=gh;
while (finish !=1) (finish ==0) //im confused as to which condition is best to use.
{Console.WriteLine("You are in room " + current.getRoomname() + "and you can move ");
    if( current.getN() != null)
        Console.WriteLine("North (N) ");
    if( current.getE() != null)
        Console.WriteLine("East (E) ");
Console.WriteLine("Please enter the direction you wish to go in ");
    string choice = Console.ReadLine();
    if (choice[0] == 'E') // or alternative means of getting in a choice from a string
        current = current.getE();// to be able to move to next 'current'room
// i was going to do this for all the options.
if(current == tr // ie last room
exit = 1;
Console.Writeline ("Well done you have found the treasure room");
}//close chamber
}//close class rooom
} //close namespace

You created a class object which doesn't have a main(). A project only has one main. So you either need to make the Room the main() in the application or removed main method from the Room Class. See my code below for changes.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace maze_3
{
class Program
{
static void Main(string[] args)
{
Room home = new Room("White House");
home.CreateRoom("W", "West Wing");
}
}
class Room
{//open class room
private string RoomName;
private Room N = null; // so that when i set the links they are automatically null unless i specify in main
private Room E = null;
private Room S = null;
private Room W = null;
private List<Chamber> chambers = new List<Chamber>();
public Room() { }
public Room(string name)
{
this.RoomName = name;
}
public void CreateRoom(string direction, string name)
{
Room newRoom = new Room();
newRoom.RoomName = name;
switch (direction)
{
case "N":
N = newRoom;
break;
case "E":
E = newRoom;
break;
case "S":
S = newRoom;
break;
case "W":
W = newRoom;
break;
}
}
}//close class rooom
public class Chamber// its telling me that a ; is expected ???
{//open class chamber
string name = "";
}//close chamber
}

Related

Rover And specimen C#

i am making a simple game of rover, in which i am having a simple problem which i can't figured out
This is my Main Function which is making One rover object in which rover can handle multiple device, there is one device which extract the specimen
Rover rov = new Rover();
string input;
//Device d = new Device();
//Specimen spec = new Specimen();
Console.WriteLine("Welcome to Planetary Rover");
Console.WriteLine("Enter y to start the game or n to exit");
string selection = Console.ReadLine();
if (selection == "y")
{
Console.WriteLine("Enter the rover Default Location X: ");
rov.X =
do
{
Console.WriteLine("Write the device nname to operate ");
input = Console.ReadLine();
rov.Handle(input);
//d.Operate();
} while (input != "end");
}
if (selection == "n")
{
Console.Clear();
}
else
{
Console.WriteLine("Wrong Input!");
}
THe drill is the device which extraxt the specimen whenever it is operated, it only extract if the specimen x and y is equals to rover x and y
I have done these thing but in my drill class there is operate functionwhich is doing the above thing, but problems occurs whenever drill is operating it is again making a new rover, so the rover x and y get null that time, so any can give me a potential fixes for that how can i use the existing rover in the drill function
public override void Operate(string ids)
{
Rover rov = new Rover();
if (specim.X == rov.X && specim.Y == rov.Y)
{
_wearfactor += 5;
Console.WriteLine("specimen extracted and wearfaction of drill is incresed by 5%");
Console.WriteLine(_wearfactor);
_spec. = 0;
}
if(specim.X != rov.X && specim.Y != rov.Y)
{
_wearfactor += 10;
Console.WriteLine("wear factor increased by 10%");
Console.WriteLine(_wearfactor);
}
if (_wearfactor == 100)
{
Console.WriteLine("Drill Destroyed");
Console.WriteLine("syart your program again");
Console.WriteLine("You can not drill specimen now");
this.Name = "";
}
}
You could change your Operate method's signature to:
public override void Operate(Rover rov, string ids)
then when you create Rover rov = new Rover(); you can pass it through for Operate to use.
Operate(rov, "ids");
Another option would be to make a public Rover object and directly reference it through Operate:
// assuming your main class is MainFunction
public class MainFunction()
{
public Rover rov { get; private set; }
public static void Main(string[] args)
{
// Establish the reusable rover
rov = new Rover();
// ...
}
}
Then in Operate, change all rov to MainFunction.rov

Solving Towers of Hanoi in C# using recursion

I'm facing the Towers of Hanoi problem, I read the concept and the recursive way of solving it from wikipedia, but I can not see what I'm missing in the implementation of the steps mentioned in wikipedia.
I have seen many examples here but I don't want my program to print the steps, I want the program solves the problem moving the "discs" between 3 collections, in my code I'm using 3 Stacks to simulate the pegs.
Here is my current code:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
var hs = new HanoiSolver(discs: 3);
hs.Solve();
Console.ReadKey();
}
}
class HanoiSolver
{
private int TotalDiscs { get; set; } = 0;
private Stack<int> FirstPeg { get; set; } = new Stack<int>();
private Stack<int> SecondPeg { get; set; } = new Stack<int>();
private Stack<int> ThirdPeg { get; set; } = new Stack<int>();
public HanoiSolver(int discs = 3)
{
TotalDiscs = discs;
//Create list of items (discs)
var discList = Enumerable.Range(1, TotalDiscs).Reverse();
//Add items (discs) to first peg
foreach (var d in discList)
{
FirstPeg.Push(d);
}
}
public void Solve()
{
if (ThirdPeg.Count != TotalDiscs)
{
PrintPegs();
//Move first item from firstpeg to secondpeg
if (FirstPeg.Any())
{
var fp_f = FirstPeg.Pop();
SecondPeg.Push(fp_f);
}
PrintPegs();
//Move second item from firstpeg to thirdpeg
if (FirstPeg.Any())
{
var fp_s = FirstPeg.Pop();
ThirdPeg.Push(fp_s);
}
PrintPegs();
//Move first item from secondpeg to thirdpeg
if (SecondPeg.Any())
{
var sp_f = SecondPeg.Pop();
ThirdPeg.Push(sp_f);
}
PrintPegs();
Solve();
}
}
private void PrintPegs()
{
var fp = FirstPeg.Select(x => x.ToString()).ToList();
if (fp.Count < TotalDiscs)
{
fp.AddRange(Enumerable.Repeat(string.Empty, (TotalDiscs - fp.Count)));
}
var sp = SecondPeg.Select(x => x.ToString()).ToList();
if (sp.Count < TotalDiscs)
{
sp.AddRange(Enumerable.Repeat(string.Empty, (TotalDiscs - sp.Count)));
}
var tp = ThirdPeg.Select(x => x.ToString()).ToList();
if (tp.Count < TotalDiscs)
{
tp.AddRange(Enumerable.Repeat(string.Empty, (TotalDiscs - tp.Count)));
}
Console.WriteLine($"{"[First Peg]",10}" + $"{"[Second Peg]",10}" + $"{"[Third Peg]",10}");
for (var i = 0; i < TotalDiscs; i++)
{
Console.WriteLine($"{fp[i],10}" +
$"{sp[i],10}" +
$"{tp[i],10}");
}
}
}
In order to make a recursive method you need one or more base cases where the recursion will end and then one or more recursive calls that break the problem down closer to one of the base cases. For Towers of Hanoi the idea is that moving n discs from Peg A to Peg C is just moving n-1 from Peg A to Peg B, then moving the nth from A to C and finally moving the n-1 discs from C to B. That will eventually get you down to moving no discs which is your base case. That can be done in a recursive method very simply like this.
private static void Move(
int discs,
Stack<int> fromPeg,
Stack<int> toPeg,
Stack<int> otherPeg)
{
if (discs == 0)
{
return;
}
Move(discs - 1, fromPeg, otherPeg, toPeg);
toPeg.Push(fromPeg.Pop());
Move(discs -1, otherPeg, toPeg, fromPeg);
}
When you are implementing TOH, this means you are new to DS and data types. So one must use the data type which is not present in DS like stack and queue. So the below approach is using array.
using System;
using static System.Console;
namespace TOH
{
class Program
{
// Problem statement
//Create an array tower(a) containing all element in ascending order
public static int[] towerSource = new int[] { 1, 3, 5,6,7,9,11,12,13,14,15,16,17};
//solution statement
//we have two more towers with same capacity, tower(b) as auxiliary and tower(c) as destination
public static int[] towerAuxiliary;
public static int[] towerDestination;
public static void CreateTowers()
{
towerAuxiliary = new int[towerSource.Length];
towerDestination = new int[towerSource.Length];
}
public static void Print(int[] tower)
{
for (int i = 0; i < tower.Length; i++)
Write(tower[i].ToString());
WriteLine("--------next run-------------");
}
//start operation
public static void TOH(int numberOfDisks, int[] source,int[] auxiliary,int[] destination)
{
//check if there is only one disk in source
if(numberOfDisks == 1)
{
//move to destination and come out
towerDestination[numberOfDisks-1] = towerSource[numberOfDisks-1];
Print(towerDestination);
return;
}
//move n-1 disks from source to auxiliary
TOH(numberOfDisks - 1, towerSource, towerAuxiliary, towerDestination);
towerDestination[numberOfDisks-1] = towerSource[numberOfDisks-1];
//move nth disc from source to dest
//this is being handeled by if condition
//move n-1 disks from auxiliary to dest
TOH(numberOfDisks - 1, towerAuxiliary, towerSource, towerDestination);
return;
}
static void Main(string[] args)
{
CreateTowers();
TOH(towerSource.Length, towerSource, towerAuxiliary, towerDestination);
}
}
}

Loop through list, match word call description from list

I am having a problem constructing a loop WHICH will COMPARE a VAR(userSelection) against the name ITEMS in my LIST(Listings). The goal is that if userSelection MATCHES name, getDescription will Console.WriteLine the GetDefinition and display the definition of the word in the list matched. Most of my code is working, and i've been working on this assignment for a week.
I'm very much a newb, please assume I know nothing. All help is appreciated. I think this would be a while loop, but i've played with all the loops now and am lost and confused. I'm a newb, please use small words and be as detailed as you can afford to be. It's greatly appreciated. Thank you.
My C# Program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;// Needed for Streaming...
using System.IO;// Needed for Streaming...
namespace a090___StreamReader_DictionarySearch
{
class Program
{
private const String FILE_NAME = "dictionary.txt";//establish text file instance
public void Play()
{
do
{
DisplayTitle();
List<Listing> items = LoadListings();//create a list of WordDef objects
Console.Write(string.Join(" | ", items.Select(x => x.GetName()))); //Console.Write("\b \b");// Backspace would also of worked
DisplayText("\n\nPlease enter a word from the selections about to see it's definition");// Nice use of PROMPT
String userSelection = Console.ReadLine().ToLower();//Capture input
//loop through all of the listings, and compare each one to userSelection
//Then once it equals print definition
bool found = false;
foreach (Listing item in items)
{
if (userSelection == item.GetName())
{
Console.WriteLine("You selected: " + userSelection +
"\nWhich Means: " + item.GetDefinition());
found = true;
break;
}
}
if (!found)
{ Console.WriteLine("I'm sorry, I don't have a match for that."); }
} while (PlayAgain());
Salutation();
}
//ToolBox -- my program specific tools
public List<Listing> LoadListings()//load entries display as list
{
StreamReader fileIn = new StreamReader(FILE_NAME);
List<Listing> entry = new List<Listing>();
//loop through every line of the file
while (!fileIn.EndOfStream)
{
String line = fileIn.ReadLine();
String[] pieces = line.Split(':');
if (pieces.Length < 1) continue;//error handling - set to length of text items
Listing myListing = new Listing(pieces[0], pieces[1]);
entry.Add(myListing);
}
fileIn.Close(); return entry;
}
//MaxBox -- my useful tools
public void DisplayText(String StringNameIs)
{ Console.WriteLine(StringNameIs); }//Where are we?
public Boolean PlayAgain()
{
Console.Write("\n\nDo you select again? (y)es or (n)o: ");
String command = Console.ReadLine().ToLower();
if (command == "y" || command == "yes") return true;
return false;
}
public void Salutation()
{ Console.Clear(); Console.WriteLine("Ti Do - oh - oh Ti Do -- So Do!"); } //The last line from the 'do-re-mi' song from the Sound of Music
public void DisplayTitle()
{ Console.Clear(); Console.WriteLine(">>>-- A Dictionary of Sounds --<<< \n"); } //Announce Our Program
static void Main(string[] args)
{
Program DictionaryLookup = new Program();
DictionaryLookup.Play();
Console.Read();
}
}
}
My Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace a090___StreamReader_DictionarySearch
{
class Listing
{
private String name;
private String definition;
public Listing(String name, String definition)
{ this.name = name;
this.definition = definition;}
public String GetName() {return name;}
public String GetDefinition() {return definition; }
}
}
My Text File
Doe: a deer, a female deer
Ray: a drop of golden sun
Me: a name I call myself
Far: a long, long way to run
Sew: a needle pulling thread
La: a note to follow Sew
Tea: a drink with jam and bread
This is untested, but should work, using your existing code.
Assuming each "name" (doe, ray, etc) only occurs once (which they do), then you can use Linq's "SingleOrDefault", which will return null if no match is found.
var selection = items.SingleOrDefault(x => x.GetName() == userSelection);
if (selection == null)
Console.WriteLine("I'm sorry, I don't have a match for that.");
else
Console.WriteLine("You selected: " + userSelection +
"\nWhich Means: " + selection.GetDefinition());
To ignore case during comparison, try modifying the above:
... items.SingleOrDefault(x => String.Compare(x.GetName(), userSelection, true));
There are a number of other things you could change here, but perhaps it won't matter for your assignment. For example, I'd eliminate the private variables in your Listing class and change the public "get" methods into properties:
public String Name { get; private set; }
public String Definition { get; private set; }
Substitute the code
while (true)
{
if (userSelection == name)
{Console.WriteLine("You selected: " + Listing.userSelection() +
"\nWhich Means: " + Listing.items.GetDefinition());}
}
else { Console.WriteLine("I'm sorry, I don't have a match for that."); }
with this
bool found = false;
foreach (Listing item in items)
{
if (userSelection == item.GetName().ToLower())
{
Console.WriteLine("You selected: " + userSelection +
"\nWhich Means: " + item.GetDefinition());
found = true;
break;
}
}
if (!found)
{ Console.WriteLine("I'm sorry, I don't have a match for that."); }
I have use the foreach statement; with this statement you can iterate all items of your collection.
Inside the foreach loop I check if the element Name is equal with the user input, if match I set a bool variable indicating element found.
After the loop if element not found print the message.
NB Obviously this code can be written more concisely with LINQ.

LeaderBoard in C# UNITY3D?

I Needed To Develop LeaderBoard For Storing Details(means Scores) of Players in Games.Just Displaying players Scores on LeaderBoard in UNITY3D.so plz help me i dont have any idea. in below code Social Platforms NameSpace is there but i dont know how start and how to implement LeaderBoard in unity3d.
using UnityEngine;
using System.Collections.Generic;
using UnityEngine.SocialPlatforms;
public class LBoard : MonoBehaviour
{
ILeaderboard leaderBoard;
// Use this for initialization
void Start ()
{
leaderBoard = Social.CreateLeaderboard();
}
// Update is called once per frame
void Update ()
{
}
}
You need to create an IComparable class and add details like name and score , compare by score.
public class PlayerScore : IComparable<PlayerScore>
public string name;
public int score;
public int CompareTo(PlayerScore other)
{
return this.score.CompareTo(other.score);
}
You also need a list
public static List<PlayerScore> scoreIndex = new List<PlayerScore>(5);
You need some way of getting input from user to add name.
When adding score, create object of iComparer class and set name, score etc.
PlayerScore a = new PlayerScore();//create instance
a.name = PlayerStats.playerName;//set name
a.score = PlayerStats.score;//and score
scoreIndex.Add(a);
Then add new object to List and sort list, List.Sort();. if you want reversed then add reverse().
scoreIndex.Sort ();
scoreIndex.Reverse ();
Save list to player prefs e.g.
PlayerPrefs.SetString("name0" , scoreIndex[0].name);
PlayerPrefs.SetInt("score0" , scoreIndex[0].score);
PlayerPrefs.SetString("name1" , scoreIndex[1].name);
PlayerPrefs.SetInt("score1" , scoreIndex[1].score);
To display names and scores, create 3dText objects for names/scores and place a script like
public class PlayerNameHS : MonoBehaviour
public int pos;
void Start ()
{
renderer.material.color = Color.black;
TextMesh t = (TextMesh)gameObject.GetComponent(typeof(TextMesh));
t.text = PlayerPrefs.GetString("name" + pos);
}
void Update ()
{
}
}
Set Pos for each object.Do the same for scores with score script.
At the start of the game add player prefs into list or you will get an error when trying to retrieve names/scores. needs to be same amount as list size.
PlayerScore a = new PlayerScore();
a.name = PlayerPrefs.GetString("name0");
a.score = PlayerPrefs.GetInt("score0");
yourScript.scoreIndex.Add(a);
PlayerScore b = new PlayerScore();
b.name = PlayerPrefs.GetString("name1");
b.score = PlayerPrefs.GetInt("score1");
yourScript.scoreIndex.Add(b);
Don't know if I'm explaining this well, but you basically need to add playerprefs to list, add comparable scores to list, sort the list, save the list, display the saved list. I'm new to this so take it easy with criticism ;)
If you mean leaderboard like a local high scores table, you would need two functions: AddScore and a function that gets the high scores. (note this example is in C#)
function AddScore(string name, int score){
int newScore;
string newName;
int oldScore;
string oldName;
newScore = score;
newName = name;
for(int i=0;i<10;i++){
if(PlayerPrefs.HasKey(i+"HScore")){
if(PlayerPrefs.GetInt(i+"HScore")<newScore){
// new score is higher than the stored score
oldScore = PlayerPrefs.GetInt(i+"HScore");
oldName = PlayerPrefs.GetString(i+"HScoreName");
PlayerPrefs.SetInt(i+"HScore",newScore);
PlayerPrefs.SetString(i+"HScoreName",newName);
newScore = oldScore;
newName = oldName;
}
}else{
PlayerPrefs.SetInt(i+"HScore",newScore);
PlayerPrefs.SetString(i+"HScoreName",newName);
newScore = 0;
newName = "";
}
}
}
And then to get the highscores:
void GetHighScores()
{
for(int i = 0; i < 10; i++)
{
Debug.Log(PlayerPrefs.GetString(i + "HScoreName") + " has a score of: " + PlayerPrefs.GetInt(i + "HScore"));
}
}
If you want to create a networked/online leaderboard, you need to use something like GameFly (take a look at that example).

Please critique my class

I've taken a few school classes along time ago on and to be honest i never really understood the concept of classes. I recently "got back on the horse" and have been trying to find some real world application for creating a class.
you may have seen that I'm trying to parse a lot of family tree data that is in an very old and antiquated format called gedcom
I created a Gedcom Reader class to read in the file , process it and make it available as two lists that contain the data that i found necessary to use
More importantly to me is i created a class to do it so I would very much like to get the experts here to tell me what i did right and what i could have done better ( I wont say wrong because the thing works and that's good enough for me)
Class:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace GedcomReader
{
class Gedcom
{
private string GedcomText = "";
public struct INDI
{
public string ID;
public string Name;
public string Sex;
public string BDay;
public bool Dead;
}
public struct FAM
{
public string FamID;
public string Type;
public string IndiID;
}
public List<INDI> Individuals = new List<INDI>();
public List<FAM> Families = new List<FAM>();
public Gedcom(string fileName)
{
using (StreamReader SR = new StreamReader(fileName))
{
GedcomText = SR.ReadToEnd();
}
ReadGedcom();
}
private void ReadGedcom()
{
string[] Nodes = GedcomText.Replace("0 #", "\u0646").Split('\u0646');
foreach (string Node in Nodes)
{
string[] SubNode = Node.Replace("\r\n", "\r").Split('\r');
if (SubNode[0].Contains("INDI"))
{
Individuals.Add(ExtractINDI(SubNode));
}
else if (SubNode[0].Contains("FAM"))
{
Families.Add(ExtractFAM(SubNode));
}
}
}
private FAM ExtractFAM(string[] Node)
{
string sFID = Node[0].Replace("# FAM", "");
string sID = "";
string sType = "";
foreach (string Line in Node)
{
// If node is HUSB
if (Line.Contains("1 HUSB "))
{
sType = "PAR";
sID = Line.Replace("1 HUSB ", "").Replace("#", "").Trim();
}
//If node for Wife
else if (Line.Contains("1 WIFE "))
{
sType = "PAR";
sID = Line.Replace("1 WIFE ", "").Replace("#", "").Trim();
}
//if node for multi children
else if (Line.Contains("1 CHIL "))
{
sType = "CHIL";
sID = Line.Replace("1 CHIL ", "").Replace("#", "");
}
}
FAM Fam = new FAM();
Fam.FamID = sFID;
Fam.Type = sType;
Fam.IndiID = sID;
return Fam;
}
private INDI ExtractINDI(string[] Node)
{
//If a individual is found
INDI I = new INDI();
if (Node[0].Contains("INDI"))
{
//Create new Structure
//Add the ID number and remove extra formating
I.ID = Node[0].Replace("#", "").Replace(" INDI", "").Trim();
//Find the name remove extra formating for last name
I.Name = Node[FindIndexinArray(Node, "NAME")].Replace("1 NAME", "").Replace("/", "").Trim();
//Find Sex and remove extra formating
I.Sex = Node[FindIndexinArray(Node, "SEX")].Replace("1 SEX ", "").Trim();
//Deterine if there is a brithday -1 means no
if (FindIndexinArray(Node, "1 BIRT ") != -1)
{
// add birthday to Struct
I.BDay = Node[FindIndexinArray(Node, "1 BIRT ") + 1].Replace("2 DATE ", "").Trim();
}
// deterimin if there is a death tag will return -1 if not found
if (FindIndexinArray(Node, "1 DEAT ") != -1)
{
//convert Y or N to true or false ( defaults to False so no need to change unless Y is found.
if (Node[FindIndexinArray(Node, "1 DEAT ")].Replace("1 DEAT ", "").Trim() == "Y")
{
//set death
I.Dead = true;
}
}
}
return I;
}
private int FindIndexinArray(string[] Arr, string search)
{
int Val = -1;
for (int i = 0; i < Arr.Length; i++)
{
if (Arr[i].Contains(search))
{
Val = i;
}
}
return Val;
}
}
}
Implementation:
using System;
using System.Windows.Forms;
using GedcomReader;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string path = #"C:\mostrecent.ged";
string outpath = #"C:\gedcom.txt";
Gedcom GD = new Gedcom(path);
GraphvizWriter GVW = new GraphvizWriter("Family Tree");
foreach(Gedcom.INDI I in GD.Individuals)
{
string color = "pink";
if (I.Sex == "M")
{
color = "blue";
}
GVW.ListNode(I.ID, I.Name, "filled", color, "circle");
if (I.ID == "ind23800")
{MessageBox.Show("stop");}
//"ind23800" [ label="Sarah Mandley",shape="circle",style="filled",color="pink" ];
}
foreach (Gedcom.FAM F in GD.Families)
{
if (F.Type == "par")
{
GVW.ConnNode(F.FamID, F.IndiID);
}
else if (F.Type =="chil")
{
GVW.ConnNode(F.IndiID, F.FamID);
}
}
string x = GVW.SB.ToString();
GVW.SaveFile(outpath);
MessageBox.Show("done");
}
}
I am particularly interested in if anything could be done about the structures i don't know if how i use them in the implementation is the greatest but again it works
Thanks alot
Quick thoughts:
Nested types should not be visible.
ValueTypes (structs) should be immutable.
Fields (class variables) should not be public. Expose them via properties instead.
Check passed arguments for invalid values, like null.
It might be more readable. It's hard to read and understand.
You may study SOLID principles (http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod)
Robert C. Martin gave good presentation on Oredev 2008 about clean code (http://www.oredev.org/topmenu/video/agile/robertcmartincleancodeiiifunctions.4.5a2d30d411ee6ffd2888000779.html)
Some recomended books to read about code readability:
Kent Beck "Implemetation patterns"
Robert C Martin "Clean Code" Robert C
Martin "Agile Principles, Patterns
and Practices in C#"
I suggest you check this place out: http://refactormycode.com/.
For some quick things, your naming is the biggest thing I would start to change.
No need to use ALL-CAPS or abbreviated terms.
Also, FxCop will help with a lot of suggested changes. For example, FindIndexinArray would be named FindIndexInArray.
EDIT:
I don't know if this is a bug in your code or by-design, but in FindIndexinArray, you don't break from your loop once you find a match. Do you want the first (break) or last (no break) match in the array?

Categories