init commit

This commit is contained in:
2026-08-04 06:56:44 -06:00
commit 4862002cd7
50 changed files with 2194 additions and 0 deletions
+76
View File
@@ -0,0 +1,76 @@
using System;
namespace Contacts
{
/// <summary>
/// Represents an address for a contact. Contains methods to determine if two addresses are equal.
/// </summary>
public class Address : IEquatable<Address>
{
private readonly string _abbr;
private readonly string _city;
private readonly string _street;
private readonly string _zip;
public AddressType Type { get; }
/// <summary>
/// Accepts input string in format "123 Example St,City,ST,12345".
/// </summary>
/// <param name="address">Full address</param>
/// <param name="type">If null, defaults to "Other"</param>
public Address(string address, AddressType? type)
{
string[] parsedAddress = address.Split(",");
if (parsedAddress.Length != 4)
throw new ArgumentException("Address must be in the format of \"123 Example St,City,ST,12345\"");
_street = parsedAddress[0];
_city = parsedAddress[1];
_abbr = parsedAddress[2];
_zip = parsedAddress[3];
this.Type = type ?? AddressType.Other;
}
/// <summary>
/// Accepts input strings for each part of an address to create a new Address object.
/// </summary>
/// <param name="street"></param>
/// <param name="city"></param>
/// <param name="abbr"></param>
/// <param name="zip"></param>
/// <param name="type">If null, defaults to "Other"</param>
public Address(string street, string city, string abbr, string zip, AddressType? type)
{
this._street = street;
this._city = city;
this._abbr = abbr;
this._zip = zip;
this.Type = type ?? AddressType.Other;
}
/// <summary>
/// Determines if two addresses are equal, to avoid potential duplication.
/// </summary>
/// <param name="otherAddr">Address to compare to. If null, returns false.</param>
/// <returns>Whether or not the two addresses are the same.</returns>
public bool Equals(Address? otherAddr)
{
if (otherAddr == null)
return false;
return this.ToString().Equals(otherAddr.ToString());
}
/// <summary>
/// Formats address object to "123 Example St, City, ST 12345".
/// </summary>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public override string ToString()
{
return _street + ", " + _city + ", " + _abbr + " " + _zip;
}
}
}
+11
View File
@@ -0,0 +1,11 @@
namespace Contacts
{
public enum AddressType
{
Home,
Business,
Work,
Other
}
}
+67
View File
@@ -0,0 +1,67 @@
using System;
namespace Contacts
{
/// <summary>
/// Represents the birthday of a contact.
/// </summary>
/// <author>Josh A</author>
public class Birthday : IEquatable<Birthday>
{
private readonly int day;
private readonly int month;
private readonly int year;
public int Age { get; }
/// <summary>
/// Creates a new Birthday object.
/// </summary>
/// <param name="month"></param>
/// <param name="day"></param>
public Birthday(int month, int day)
{
this.month = month;
this.day = day;
year = -1;
Age = -1;
}
/// <summary>
/// Creates a new Birthday and determines the age.
/// </summary>
/// <param name="month"></param>
/// <param name="day"></param>
/// <param name="year"></param>
public Birthday(int month, int day, int year)
{
this.month = month;
this.day = day;
this.year = year;
Age = 2023 - year;
}
/// <summary>
/// Determines if two birthdays are equal, to avoid potential duplication.
/// </summary>
/// <param name="birthdayToCompare">Birthday to compare to. If null, returns false.</param>
/// <returns>Whether or not the two birthdays are the same.</returns>
public bool Equals(Birthday? birthdayToCompare)
{
if (birthdayToCompare == null)
return false;
return this.ToString().Equals(birthdayToCompare.ToString());
}
/// <summary>
/// Formats a birthday to "MM-DD" or "MM-DD-YYYY", if a birthyear was provided.
/// </summary>
/// <returns>Formatted birthdate.</returns>
public override string ToString()
{
if (year == -1)
return month + "-" + day;
return month + "-" + day + "-" + year;
}
}
}
+385
View File
@@ -0,0 +1,385 @@
using System;
using System.Collections.Generic;
namespace Contacts
{
/// <summary>
/// Represents a contact inside of the contacts manager console application. Provides methods to update key information as well as methods to add and remove communication information.
/// </summary>
public class Contact : IEquatable<Contact>
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Birthday? Bday { get; set; }
public List<Address> Addresses { get; }
public List<Phone> Numbers { get; }
public List<string> Emails { get; }
public ContactCategory Type { get; set; }
public string PictureUrl { get; set; }
private List<string> attributes { get; }
/// <summary>
/// Loads a saved contact and creates a new Contact object based upon the saved information.
/// </summary>
/// <param name="savedContact"></param>
public Contact(string savedContact)
{
string[] contactArr = savedContact.Split("|");
FirstName = contactArr[0];
LastName = contactArr[1];
Addresses = new List<Address>();
Numbers = new List<Phone>();
Emails = new List<string>();
if (contactArr[2].Length > 0)
{
string[] addr = contactArr[2].Split(",");
foreach (string a in addr)
{
if (!a.Equals(""))
Addresses.Add(new Address(a, null)); // TODO: Need to find addr type.
}
}
if (contactArr[3].Length > 0)
{
string[] phones = contactArr[3].Split(",");
foreach (string p in phones)
{
if (!p.Equals(""))
Numbers.Add(new Phone(p, null)); // TODO: Need to find phone type.
}
}
if (contactArr[4].Length > 0)
{
string[] emails = contactArr[4].Split(",");
foreach (string e in emails)
{
if (!e.Equals(""))
Emails.Add(e);
}
}
if (!contactArr[5].Equals(""))
{
ContactCategory cat = (ContactCategory)Enum.Parse(typeof(ContactCategory), contactArr[5]);
Type = cat;
}
else
{
Type = ContactCategory.Other;
}
if (!contactArr[6].Equals(""))
PictureUrl = contactArr[6];
}
/// <summary>
/// Create a new Contacts object and initialize the data structures responsible for storing multiple addresses, phone numbers, and emails.
/// </summary>
/// <param name="firstName">New contact's first name</param>
/// <param name="lastName">New contact's last name</param>
/// <param name="type">If null, defaults to "Other"</param>
public Contact(string firstName, string lastName, ContactCategory? type)
{
this.FirstName = firstName;
this.LastName = lastName;
this.Type = type ?? ContactCategory.Other;
Addresses = new List<Address>();
Numbers = new List<Phone>();
Emails = new List<string>();
attributes = new List<string>();
}
/// <summary>
/// Create a new Contacts object.
/// </summary>
/// <param name="firstName"></param>
/// <param name="lastName"></param>
/// <param name="bday"></param>
/// <param name="addresses"></param>
/// <param name="numbers"></param>
/// <param name="emails"></param>
/// <param name="type"></param>
public Contact(string firstName, string lastName, Birthday bday, List<Address> addresses, List<Phone> numbers,
List<string> emails, ContactCategory? type)
{
this.FirstName = firstName;
this.LastName = lastName;
this.Bday = bday;
this.Addresses = addresses;
this.Numbers = numbers;
this.Emails = emails;
this.Type = type ?? ContactCategory.Other;
attributes = new List<string>();
}
public Contact()
{
}
/// <summary>
/// If first = true, update only the first name, otherwise update the last name.
/// </summary>
/// <param name="name">Updated name</param>
/// <param name="first">First or last name</param>
public void UpdateName(string name, bool first)
{
if (first)
FirstName = name;
else
LastName = name;
}
/// <summary>
/// Update both the first name and the last name.
/// </summary>
/// <param name="fName">Updated first name</param>
/// <param name="lName">Updated last name</param>
public void UpdateName(string fName, string lName)
{
FirstName = fName;
LastName = lName;
}
/// <summary>
/// Associate a birthday with the contact.
/// </summary>
/// <param name="bday">Birthday object to save</param>
public void UpdateBDay(Birthday bday)
{
this.Bday = bday;
}
/// <summary>
/// Associate a new address with the contact.
/// </summary>
/// <param name="a">Address object to add</param>
public void AddAddress(Address a)
{
Addresses.Add(a);
}
/// <summary>
/// Disassociate an address from a contact.
/// </summary>
/// <param name="addrToRemove">Address object to find and remove.</param>
/// <exception cref="ArgumentException">Thrown if the address is not associated with the contact.</exception>
public void RemoveAddress(Address addrToRemove)
{
if (!Addresses.Remove(addrToRemove))
throw new ArgumentException("Address does not exist.");
}
/// <summary>
/// Add a new Phone to the contact, if it does not already exist.
/// </summary>
/// <param name="newPhone">Phone object to add.</param>
public void AddPhone(Phone newPhone)
{
bool canAdd = true;
foreach (Phone p in Numbers)
{
if (newPhone.Equals(p))
canAdd = false;
}
if (canAdd)
Numbers.Add(newPhone);
}
/// <summary>
/// Disassociate a phone from a contact.
/// </summary>
/// <param name="phoneToRemove">Phone object to find and remove.</param>
/// <exception cref="ArgumentException">Thrown if the phone is not associated with the contact.</exception>
public void RemovePhone(Phone phoneToRemove)
{
if (!Numbers.Remove(phoneToRemove))
throw new ArgumentException("Phone number does not exist.");
}
/// <summary>
/// Add a new email to the contact.
/// </summary>
/// <param name="email">Email to add.</param>
public void AddEmail(string email)
{
Emails.Add(email);
}
/// <summary>
/// Disassociate an email from a contact.
/// </summary>
/// <param name="emailToRemove">Email to search and remove.</param>
/// <exception cref="ArgumentException">Thrown if the email is not associated with this contact.</exception>
public void RemoveEmail(string emailToRemove)
{
if (!Emails.Remove(emailToRemove))
throw new ArgumentException("Email does not exist.");
}
/// <summary>
/// Updates the contact type, ie. the relationship to the contact.
/// </summary>
/// <param name="type">Type to update to</param>
public void SetContactType(ContactCategory type)
{
this.Type = type;
}
// TODO: Need overloaded Equals methods for different situations. This is only checking if two Contacts objects are equal, but an imported Contacts may not be detected.
/// <summary>
/// Determines if two contacts are equal, to avoid potential duplication.
/// </summary>
/// <param name="contactToCompare">Contacts to compare to. If null, returns false.</param>
/// <returns>Whether or not the two contacts are the same.</returns>
public bool Equals(Contact? contactToCompare)
{
if (contactToCompare == null)
return false;
return this.GetHashCode() == contactToCompare.GetHashCode();
}
/// <summary>
/// Calculates the hashcode of a contact by combining the hashcodes of each field of a contact.
/// </summary>
/// <returns>The Contacts's hashcode</returns>
public override int GetHashCode()
{
int code = 17;
code *= FirstName.GetHashCode();
code *= LastName.GetHashCode();
code *= Bday.GetHashCode();
foreach (Address a in Addresses)
{
code *= a.GetHashCode();
}
foreach (Phone p in Numbers)
{
code *= p.GetHashCode();
}
foreach (string e in Emails)
{
code *= e.GetHashCode();
}
code *= Type.GetHashCode();
return code;
}
/// <summary>
/// Formats the contact in a parsable string, designed to be saved to a file.
/// </summary>
/// <returns>Parsable string.</returns>
public string SaveString()
{
attributes.Clear();
attributes.Add(FirstName);
attributes.Add(LastName);
//attributes.Add(Bday.ToString()); // TODO: Need to implement and test birthdates.
attributes.Add(String.Join(",", Addresses));
List<string> nums = new List<string>();
foreach (Phone n in Numbers)
{
nums.Add(n.DisplayString());
}
attributes.Add(String.Join(",", nums));
attributes.Add(String.Join(",", Emails));
attributes.Add("" + Type);
attributes.Add(String.Join(",", PictureUrl));
return String.Join("|", attributes);
}
// TODO: Implement this method once the GUI is created, formatting contacts to best integrate into the GUI.
/// <summary>
/// Standard string representation of a Contact, for use while still using the console with no other GUI elements.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return FirstName + (LastName.Equals("") ? "" : ", " + LastName) + ": " + String.Join(", ", Addresses) + " || " +
String.Join(", ", Numbers) + " || " + String.Join(", ", Emails) + " || " + Type + " || " + PictureUrl;
}
//full name needs to be firstname lastname
public static void RemoveContact(string fullName)
{
fullName = fullName.ToLower();
string[] arguments = fullName.Split(" ");
string firstName = arguments[0];
string lastName = arguments[1];
string filePath = "yourContacts.save";
List<string> linesToKeep = new List<string>();
try
{
using (StreamReader reader = new StreamReader(filePath))
{
string line;
while ((line = reader.ReadLine()) != null) // Read line by line until EOF
{
if (!(line.ToLower().Contains(firstName) && line.ToLower().Contains(lastName)))
{
linesToKeep.Add(line);
}
}
}
using (StreamWriter writer = new StreamWriter(filePath))
{
foreach (string line in linesToKeep)
{
writer.WriteLine(line);
}
}
Console.WriteLine("Contact removed successfully.");
}
catch (Exception ex)
{
Console.WriteLine("Error reading or writing the file: " + ex.Message);
}
}
public static void AddContact(string firstName, string lastName, string phoneNumber, string ContactCategory)
{
string filePath = "yourContacts.save";
string contactLine = $"{firstName}|{lastName}|{phoneNumber}|{ContactCategory}";
try
{
using (StreamWriter writer = new StreamWriter(filePath, true)) // Append mode is set to true
{
writer.WriteLine(contactLine);
}
Console.WriteLine("Contact added successfully.");
}
catch (Exception ex)
{
Console.WriteLine("Error writing to the file: " + ex.Message);
}
}
}
}
+10
View File
@@ -0,0 +1,10 @@
namespace Contacts
{
public enum ContactCategory
{
Family,
Friends,
Work,
Other
}
}
+13
View File
@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Crayon" Version="2.0.69" />
</ItemGroup>
</Project>
+16
View File
@@ -0,0 +1,16 @@
Microsoft Visual Studio Solution File, Format Version 12.00
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Contacts", "Contacts.csproj", "{300D68D7-C6ED-4FB6-8387-6ECE80CFE236}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{300D68D7-C6ED-4FB6-8387-6ECE80CFE236}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{300D68D7-C6ED-4FB6-8387-6ECE80CFE236}.Debug|Any CPU.Build.0 = Debug|Any CPU
{300D68D7-C6ED-4FB6-8387-6ECE80CFE236}.Release|Any CPU.ActiveCfg = Release|Any CPU
{300D68D7-C6ED-4FB6-8387-6ECE80CFE236}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal
+77
View File
@@ -0,0 +1,77 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Contacts
{
/// <summary>
/// Manages the contacts database and facilitates viewing the database via searching and sorting. Contains methods to update the current view.
/// </summary>
public class FileIO
{
public IEnumerable<Contact> currentState { get; set; }
private readonly List<Contact> _contacts = new();
//private string _filepath = "~/.contacts";
/// <summary>
/// Create the FileIo object and set default view.
/// </summary>
public FileIO()
{
currentState =
from c in _contacts
select c;
}
/// <summary>
/// Facilitates incoming compatability with .vcf, .card, and .csv filetypes for contacts into this console-based
/// contacts manager.
/// </summary>
/// <param name="resolver"></param>
public void Import(Resolver resolver)
{
resolver.Parse();
List<Contact> contacts = resolver.Contacts;
foreach (Contact c in contacts)
_contacts.Add(c);
}
/// <summary>
/// Facilitates outgoing compatability with .vcf, .card, and .csv filetypes for contacts into this console-based contacts manager.
/// </summary>
/// <param name="onIos"></param>
public void Export(bool onIos)
{
// TODO
}
/// <summary>
/// Save the contacts in the database to a file.
/// </summary>
/// <param name="targetFilePath">Path to the file on computer</param>
public void Save()
{
using (StreamWriter writer = new StreamWriter("yourContacts.save"))
{
foreach (Contact c in _contacts)
{
writer.WriteLine($"{c.SaveString()}");
}
}
}
/// <summary>
/// Load the saved contacts in the database.
/// </summary>
public void Load()
{
using (StreamReader reader = new StreamReader("yourContacts.save"))
{
while (!reader.EndOfStream)
{
_contacts.Add(new Contact(reader.ReadLine()));
}
}
}
}
}
+60
View File
@@ -0,0 +1,60 @@
using System;
/// <summary>
/// Represents a phone number for a contact. Contains methods to determine if two phone numbers are the same.
/// </summary>
namespace Contacts
{
public class Phone : IEquatable<Phone>
{
public string number { get; }
public PhoneType? Type { get; }
/// <summary>
/// Accepts an input string in the format "1234567890" to create a new Phone object for a Contacts.
/// </summary>
/// <param name="number"></param>
/// <param name="type">If null, defaults to "Other"</param>
/// <exception cref="ArgumentException">Thrown if input has an invalid format.</exception>
public Phone(string number, PhoneType? type)
{
if (number.Length != 10)
throw new ArgumentException("Input phone number should be in the format 1234567890.");
this.number = number;
this.Type = type;
}
/// <summary>
/// Determines if two phone numbers are equal, to avoid potential duplication.
/// </summary>
/// <param name="numberToCompare">Phone number to compare to. If null, returns false.</param>
/// <returns>Whether or not the two phone numbers are the same.</returns>
public bool Equals(Phone? numberToCompare)
{
if (numberToCompare == null)
return false;
return this.ToString().Equals(numberToCompare.ToString());
}
/// <summary>
/// Returns the phone number without any formatting, for use in saving contacts to a file.
/// </summary>
/// <returns>Unformatted phone number</returns>
public string DisplayString()
{
return number;
}
/// <summary>
/// Formats the phone number to "(123) 456 - 7890"
/// </summary>
/// <returns>Formatted phone number</returns>
public override string ToString()
{
return "(" + number.Substring(0, 3) + ") " + number.Substring(3, 3) + " - " + number.Substring(6);
}
}
}
+10
View File
@@ -0,0 +1,10 @@
namespace Contacts
{
public enum PhoneType
{
Cell,
Work,
Home,
Other
}
}
+266
View File
@@ -0,0 +1,266 @@
using System.Diagnostics;
using System.Drawing;
using System.IO;
using Contacts;
using static Crayon.Output;
using Crayon;
/// <summary>
/// Test program for the contacts manager. Currently, to use, export a contacts list from your Google account or iCloud, in a CSV format. Save this file to bin/Debug/net7.0/testResources.
/// This will allow you to test with your own contacts.
/// Please remove this file prior to any pushes to Github.
/// </summary>
public class Program
{
public static void Main(string[] args)
{
OperatingSystem os = Environment.OSVersion; // checking what OS is running
Console.WriteLine("Platform: {0}", os.Platform);
Console.WriteLine("Version: {0}", os.Version);
Console.WriteLine("Service Pack: {0}", os.ServicePack);
bool isMacOS = (os.Platform == PlatformID.MacOSX || os.Platform == PlatformID.Unix);
FileIO fileIO = new FileIO();
Resolver? resolver;
Console.Clear();
Console.ResetColor();
var rainbow = new Rainbow(0.5);
Console.WriteLine(Bold("""
___ _ _
/ __\ ___ _ __ | |_ __ _ ___ | |_ ___ /\/\ ___ _ __ __ _ ___ _ __
/ / / _ \ | '_ \ | __|/ _` | / __|| __|/ __| / \ / _ \| '__|/ _` | / _ \| '__|
/ /___| (_) || | | || |_| (_| || (__ | |_ \__ \ / /\/\ \| __/| | | (_| || __/| |
\____/ \___/ |_| |_| \__|\__,_| \___| \__||___/ \/ \/ \___||_| \__, | \___||_|
|___/
"""));
// DrawLines();
Console.WriteLine($"\n{Output.Background.Red(White(new string('~', Console.BufferWidth - 2)))}");
Console.Write("> ");
Point point = new Point(Console.CursorLeft, Console.CursorTop);
bool isDebug = false;
bool isExported = false;
writeHelpCommand(Console.BufferWidth / 2, 9);
Console.SetCursorPosition(point.X, point.Y);
string? commandString = Console.ReadLine();
while (commandString != "exit")
{
List<String> arguments = commandString.Split(" ").ToList<String>();
string command = arguments[0];
arguments.RemoveAt(0);
switch (command.ToLower())
{
case "add":
if (arguments.Count < 4)
{
Console.WriteLine("This command requires an argument. Use \"help\" for more info.");
break;
}
Contact.AddContact(arguments[0], arguments[1], arguments[2], arguments[3]);
break;
case "remove":
if (arguments.Count < 2)
{
Console.WriteLine("This command requires an argument. Use \"help\" for more info.");
break;
}
string fullname = arguments[0];
fullname += " " + arguments[1];
Contact.RemoveContact(fullname);
break;
case "view":
if (!isDebug)
{
if (isExported)
{
if (isMacOS)
{
Process.Start("/System/Applications/TextEdit.app/Contents/MacOS/TextEdit", Path.Combine(Directory.GetCurrentDirectory(), "yourContacts.save"));
}
else
{
Process.Start("notepad.exe", "yourContacts.save");
}
}
else
{
Console.WriteLine($"The database hasn't been exported to a {Red(".save")} file. Use {Cyan("EXPORT")} before using this command");
}
}
else
{
if (isMacOS)
{
Process.Start("/System/Applications/TextEdit.app/Contents/MacOS/TextEdit", Path.Combine(Directory.GetCurrentDirectory(), "yourContacts.save"));
}
else
{
Process.Start("notepad.exe", "yourContacts.save");
}
}
break;
case "import":
if (arguments.Count <= 0)
{
System.Console.WriteLine("This command requires an argument. Use \"help\" for more info.");
break;
}
resolver = new Resolver(@arguments[0]);
fileIO.Import(resolver);
break;
case "export":
fileIO.Save();
isExported = true;
Console.WriteLine($"Your new {Red(".save")} file has been saved @ {Path.Combine(Directory.GetCurrentDirectory(), "yourContacts.save")}");
// TODO: Some way to tell them that it was saved to a certain spot in their computer
break;
case "help":
writeHelpCommand(0, 0);
break;
case "clear":
Console.Clear();
break;
case "debug":
if (arguments.Count <= 0)
{
System.Console.WriteLine("This command requires an argument. Use \"help\" for more info.");
break;
}
if (arguments[0] == "true")
{
isDebug = true;
Console.WriteLine(Yellow("ABSOLUTE FILE PATH TO yourContacts.save: {0}"), Path.Combine(Directory.GetCurrentDirectory(), "yourContacts.save"));
}
else if (arguments[0] == "false")
{
isDebug = false;
}
else
{
Console.WriteLine("Invalid argument. Try again.");
}
break;
case "":
break;
default:
Console.WriteLine("Invalid Opperation. Try again.");
break;
}
// DEAD LAST DO NOT TOUCHY
Console.Write(rainbow.Next().Bold().Text("> "));
commandString = Console.ReadLine();
}
}
public static void DrawLines()
{
for (int i = 0; i < 1; i++)
{
if (i % 2 == 0)
{
Console.Write($"{Red(new string('*', 1))}");
Console.Write($"{Magenta(new string('*', 1))}");
Console.Write($"{Yellow(new string('*', 1))}");
}
else
{
Console.Write($"{Yellow(new string('*', 1))}");
Console.Write($"{Magenta(new string('*', 1))}");
Console.Write($"{Red(new string('*', 1))}");
}
}
for (int i = 0; i < 51; i++)
{
if (i % 2 == 0)
{
Console.Write($"{Red(new string('*', 1))}");
Console.Write($"{Magenta(new string('*', 1))}");
Console.Write($"{Yellow(new string('*', 1))}");
}
else
{
Console.Write($"{Yellow(new string('*', 1))}");
Console.Write($"{Magenta(new string('*', 1))}");
Console.Write($"{Red(new string('*', 1))}");
}
//Console.Write($"{Cyan(new string('*', i))}");
// Console.WriteLine($"{('*', Console.BufferWidth - i))}");
}
for (int i = 0; i < 33; i++)
{
if (i % 2 == 0)
{
Console.SetCursorPosition(153, 6 + i);
Console.Write($"{Magenta(new string('*', 1))}");
Console.Write($"{Yellow(new string('*', 1))}");
}
else
{
Console.SetCursorPosition(153, 6 + i);
Console.Write($"{Red(new string('*', 1))}");
Console.Write($"{Yellow(new string('*', 1))}");
}
// Console.WriteLine($"{('*', Console.BufferWidth - i))}");
if (i == 31)
{
}
}
Console.SetCursorPosition(1, 7);
}
private static void writeHelpCommand(int left, int top)
{
if (left == 0 && top == 0)
{
Console.WriteLine("Contacts Merger Help\n");
Console.WriteLine(Bold(Green("ADD {0} {1}")), new string('.', 8), "<FirstName> <LastName> <Phone#> <PhoneCategory>");
Console.WriteLine("Adds a new contact to the final save file");
Console.WriteLine(Bold(Yellow("REMOVE {0} {1}")), new string('.', 5), "<FirstName> <LastName>");
Console.WriteLine("Removes contact from final save file");
Console.WriteLine(Bold(Blue("IMPORT {0} {1}")), new string('.', 5), "<filePath (.csv) or (.vcf)>");
Console.WriteLine($"Brings in contacts from either a {Red(".csv")} file or a {Red(".vcf")} file.");
Console.WriteLine(Bold(Cyan("EXPORT {0}")), new string('.', 5));
Console.WriteLine($"Takes all contacts taken from {Blue("IMPORT")} and compiles them-");
Console.WriteLine("-into a pipe-separated file.");
Console.WriteLine(Bold(Magenta("VIEW {0}")), new string('.', 5));
Console.WriteLine($"Opens the .save file that has been exported.");
Console.WriteLine(Bold(Yellow("EXIT {0}")), new string('.', 7));
Console.WriteLine($"Exits the program");
}
else
{
Console.SetCursorPosition(left, top);
Console.WriteLine("Contacts Merger Help\n");
Console.SetCursorPosition(left, top++);
Console.WriteLine(Bold(Green("ADD {0} {1}")), new string('.', 8), "<FirstName> <LastName> <Phone#> <PhoneCategory> ");
Console.SetCursorPosition(left, top++);
Console.WriteLine("Adds a new contact to the final save file");
Console.SetCursorPosition(left, top++);
Console.WriteLine(Bold(Yellow("REMOVE {0} {1}")), new string('.', 5), "<FirstName> <LastName>");
Console.SetCursorPosition(left, top++);
Console.WriteLine("Removes contact from final save file");
Console.SetCursorPosition(left, top++);
Console.WriteLine(Bold(Blue("IMPORT {0} {1}")), new string('.', 5), "<filePath (.csv) or (.vcf)>");
Console.SetCursorPosition(left, top++);
Console.WriteLine($"Brings in contacts from either a {Red(".csv")} file or a {Red(".vcf")} file.");
Console.SetCursorPosition(left, top++);
Console.WriteLine(Bold(Cyan("EXPORT {0}")), new string('.', 5));
Console.SetCursorPosition(left, top++);
Console.WriteLine($"Takes all contacts taken from {Blue("IMPORT")} and compiles-.");
Console.SetCursorPosition(left, top++);
Console.WriteLine("-into a pipe-separated file.");
Console.SetCursorPosition(left, top++);
Console.WriteLine(Bold(Magenta("VIEW {0}")), new string('.', 5));
Console.SetCursorPosition(left, top++);
Console.WriteLine($"Opens the .save file that has been exported.");
}
}
}
+272
View File
@@ -0,0 +1,272 @@
using Microsoft.VisualBasic.FileIO;
using System.Collections.Generic;
using System.IO;
using System;
namespace Contacts
{
/// <summary>
/// Represents a file, and provides implementations for parsing contacts from a file.
/// </summary>
public class Resolver
{
public List<Contact> Contacts { get; set; }
internal string _filepath;
private bool isGoogleCsv;
public Resolver(string filepath)
{
_filepath = filepath;
if (!File.Exists(_filepath))
throw new InvalidOperationException("File does not exist.");
Contacts = new List<Contact>();
}
/// <summary>
/// Manages the parsing process and determines the correct parser to use based upon the filetype.
/// </summary>
public void Parse()
{
string filetype = _filepath.Substring(_filepath.LastIndexOf('.'));
switch (filetype)
{
case ".csv":
ParseCsv();
break;
case ".vcf":
ParseVCF();
break;
case ".card":
ParseVCF();
break;
}
}
/// <summary>
/// Convert a CSV file into a List<string>, and determine if the input csv is in the Google contact format or the Outlook contact format.
/// </summary>
private void ParseCsv()
{
List<string> contactInfo = new List<string>();
using (TextFieldParser parser = new TextFieldParser(_filepath))
{
if (parser.PeekChars(5).Equals("Name,"))
isGoogleCsv = true;
else
isGoogleCsv = false;
parser.ReadLine(); // skip header row
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters(",");
while (!parser.EndOfData)
{
//Processing row
string[] fields = parser.ReadFields();
foreach (string field in fields)
if (!field.Equals("")) // skip blank fields
contactInfo.Add(field);
parser.ReadLine(); // move to next line to read the next contact.
ConvertToContact(contactInfo); // with current contact information, generate and add the new contact.
contactInfo.Clear(); // clear contact information for next contact.
}
}
}
/// <summary>
/// Parse the information contained by a Google formatted .csv file to generate a new Contacts object.
/// </summary>
private void ConvertToContact(List<string> csv)
{
Phone home = null;
Phone work = null;
Phone cell = null;
Phone other = null;
Contact c;
string[] contact = csv.ToArray();
// Check if the csv is a google or outlook formatted csv.
if (isGoogleCsv)
c = new Contact(contact[1], contact[2].Contains("*") ? "" : contact[2], null);
else
c = new Contact(contact[0], contact[1].Contains("*") ? "" : contact[1], null);
// iterate through csv array
for (int i = 0; i < contact.Length; i++)
{
// if current element is labeled as a number,
switch (contact[i])
{
case "Home":
home = ParsePhone(PhoneType.Home, contact[i + 1]);
if (home != null)
c.AddPhone(home);
break;
case "Work":
work = ParsePhone(PhoneType.Work, contact[i + 1]);
if (work != null)
c.AddPhone(work);
break;
case "Job":
work = ParsePhone(PhoneType.Work, contact[i + 1]);
if (work != null)
c.AddPhone(work);
break;
case "Mobile":
cell = ParsePhone(PhoneType.Cell, contact[i + 1]);
if (cell != null)
c.AddPhone(cell);
break;
case "Cell":
cell = ParsePhone(PhoneType.Cell, contact[i + 1]);
if (cell != null)
c.AddPhone(cell);
break;
case "Other":
other = ParsePhone(PhoneType.Other, contact[i + 1]);
if (other != null)
c.AddPhone(other);
break;
default:
other = ParsePhone(PhoneType.Other, contact[i]);
if (other != null)
c.AddPhone(other);
break;
}
if (contact[i].Contains("@")) // detect an email address and add to the current contact.
c.AddEmail(contact[i]);
if (contact[i].Contains("http") ||
contact[i].Contains("www.")) // detect a URL and add to the current contact.
c.PictureUrl = contact[i];
}
Contacts.Add(c);
}
/// <summary>
/// Parse the information contained by the .vcf file to generate a new Contacts object.
/// </summary>
private void ParseVCF()
{
using (StreamReader reader = new StreamReader(_filepath))
{
string line;
Contact contact = null;
while ((line = reader.ReadLine()) != null)
{
if (line.StartsWith("BEGIN:VCARD"))
{
contact = new Contact();
}
else if (line.StartsWith("FN:") && contact != null)
{
//mabye wrong
string myLine = line;
int i = 0;
while (true)
{
if (myLine[i].Equals(" "))
{
break;
}
else
{
contact.FirstName += myLine[i];
i++;
}
}
//now at last name
while (true)
{
//mabye change
if (i == myLine.Length)
{
break;
}
else
{
contact.LastName += myLine[i];
}
}
}
else if (line.StartsWith("TEL;TYPE=") && contact != null)
{
int typeEndIndex = line.IndexOf(':', 9);
string phoneType = line.Substring(9, typeEndIndex - 9).ToUpper();
string phoneNumber = line.Substring(typeEndIndex + 1);
PhoneType parsedPhoneType = PhoneType.Other;
switch (phoneType)
{
case "HOME":
parsedPhoneType = PhoneType.Home;
break;
case "WORK":
parsedPhoneType = PhoneType.Work;
break;
case "CELL":
parsedPhoneType = PhoneType.Cell;
break;
case "OTHER":
parsedPhoneType = PhoneType.Other;
break;
}
Phone phone = ParsePhone(parsedPhoneType, phoneNumber);
if (phone != null)
{
contact.AddPhone(phone);
}
}
else if (line.StartsWith("EMAIL:") && contact != null)
{
string email = line.Substring(6);
contact.AddEmail(email);
}
else if (line.StartsWith("PHOTO;VALUE=URI:") && contact != null)
{
string pictureUrl = line.Substring(15);
contact.PictureUrl = pictureUrl;
}
else if (line.StartsWith("END:VCARD") && contact != null)
{
Contacts.Add(contact);
contact = null;
}
}
}
}
/// <summary>
/// Parses any format of a phone number into the acceptable format 1234567890.
/// </summary>
/// <param name="type"></param>
/// <param name="number"></param>
/// <returns></returns>
private Phone ParsePhone(PhoneType type, string number)
{
List<char> list = new List<char>();
char[] characters = number.ToCharArray();
for (int i = 0; i < characters.Length; i++)
if (char.IsDigit(characters[i])) // if the character is a digit, add it to the list
list.Add(characters[i]);
if (list.Count == 11) // remove the international code
list.RemoveAt(0);
string outputNumber = string.Join("", list);
if (outputNumber.Length > 10 ||
outputNumber.Length <
10) // detect if this was an email or address labeled as a generic category, ie. "Home".
return null;
return new Phone(outputNumber, type);
}
}
}
@@ -0,0 +1,67 @@
{
"format": 1,
"restore": {
"/home/jashton/dev/active/2410-Contacts/ContactApp/ContactApp/ContactApp.csproj": {}
},
"projects": {
"/home/jashton/dev/active/2410-Contacts/ContactApp/ContactApp/ContactApp.csproj": {
"version": "1.0.0",
"restore": {
"projectUniqueName": "/home/jashton/dev/active/2410-Contacts/ContactApp/ContactApp/ContactApp.csproj",
"projectName": "ContactApp",
"projectPath": "/home/jashton/dev/active/2410-Contacts/ContactApp/ContactApp/ContactApp.csproj",
"packagesPath": "/home/jashton/.nuget/packages/",
"outputPath": "/home/jashton/dev/active/2410-Contacts/ContactApp/ContactApp/obj/",
"projectStyle": "PackageReference",
"configFilePaths": [
"/home/jashton/.nuget/NuGet/NuGet.Config"
],
"originalTargetFrameworks": [
"net7.0"
],
"sources": {
"https://api.nuget.org/v3/index.json": {}
},
"frameworks": {
"net7.0": {
"targetAlias": "net7.0",
"projectReferences": {}
}
},
"warningProperties": {
"warnAsError": [
"NU1605"
]
}
},
"frameworks": {
"net7.0": {
"targetAlias": "net7.0",
"imports": [
"net461",
"net462",
"net47",
"net471",
"net472",
"net48",
"net481"
],
"assetTargetFallback": true,
"warn": true,
"downloadDependencies": [
{
"name": "Microsoft.AspNetCore.App.Ref",
"version": "[7.0.3, 7.0.3]"
}
],
"frameworkReferences": {
"Microsoft.NETCore.App": {
"privateAssets": "all"
}
},
"runtimeIdentifierGraphPath": "/usr/share/dotnet/sdk/7.0.103/RuntimeIdentifierGraph.json"
}
}
}
}
}
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Condition=" '$(ExcludeRestorePackageImports)' != 'true' ">
<RestoreSuccess Condition=" '$(RestoreSuccess)' == '' ">True</RestoreSuccess>
<RestoreTool Condition=" '$(RestoreTool)' == '' ">NuGet</RestoreTool>
<ProjectAssetsFile Condition=" '$(ProjectAssetsFile)' == '' ">$(MSBuildThisFileDirectory)project.assets.json</ProjectAssetsFile>
<NuGetPackageRoot Condition=" '$(NuGetPackageRoot)' == '' ">/home/jashton/.nuget/packages/</NuGetPackageRoot>
<NuGetPackageFolders Condition=" '$(NuGetPackageFolders)' == '' ">/home/jashton/.nuget/packages/</NuGetPackageFolders>
<NuGetProjectStyle Condition=" '$(NuGetProjectStyle)' == '' ">PackageReference</NuGetProjectStyle>
<NuGetToolVersion Condition=" '$(NuGetToolVersion)' == '' ">6.4.0</NuGetToolVersion>
</PropertyGroup>
<ItemGroup Condition=" '$(ExcludeRestorePackageImports)' != 'true' ">
<SourceRoot Include="/home/jashton/.nuget/packages/" />
</ItemGroup>
</Project>
@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" />
@@ -0,0 +1,70 @@
{
"format": 1,
"restore": {
"/Users/marcuswalker/Documents/2410-Contacts/Contacts.csproj": {}
},
"projects": {
"/Users/marcuswalker/Documents/2410-Contacts/Contacts.csproj": {
"version": "1.0.0",
"restore": {
"projectUniqueName": "/Users/marcuswalker/Documents/2410-Contacts/Contacts.csproj",
"projectName": "Contacts",
"projectPath": "/Users/marcuswalker/Documents/2410-Contacts/Contacts.csproj",
"packagesPath": "/Users/marcuswalker/.nuget/packages/",
"outputPath": "/Users/marcuswalker/Documents/2410-Contacts/obj/",
"projectStyle": "PackageReference",
"configFilePaths": [
"/Users/marcuswalker/.nuget/NuGet/NuGet.Config"
],
"originalTargetFrameworks": [
"net7.0"
],
"sources": {
"https://api.nuget.org/v3/index.json": {}
},
"frameworks": {
"net7.0": {
"targetAlias": "net7.0",
"projectReferences": {}
}
},
"warningProperties": {
"warnAsError": [
"NU1605"
]
}
},
"frameworks": {
"net7.0": {
"targetAlias": "net7.0",
"dependencies": {
"Crayon": {
"target": "Package",
"version": "[2.0.69, )"
}
},
"imports": [
"net461",
"net462",
"net47",
"net471",
"net472",
"net48",
"net481"
],
"assetTargetFallback": true,
"warn": true,
"frameworkReferences": {
"Microsoft.AspNetCore.App": {
"privateAssets": "none"
},
"Microsoft.NETCore.App": {
"privateAssets": "all"
}
},
"runtimeIdentifierGraphPath": "/usr/local/share/dotnet/sdk/7.0.203/RuntimeIdentifierGraph.json"
}
}
}
}
}
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Condition=" '$(ExcludeRestorePackageImports)' != 'true' ">
<RestoreSuccess Condition=" '$(RestoreSuccess)' == '' ">True</RestoreSuccess>
<RestoreTool Condition=" '$(RestoreTool)' == '' ">NuGet</RestoreTool>
<ProjectAssetsFile Condition=" '$(ProjectAssetsFile)' == '' ">$(MSBuildThisFileDirectory)project.assets.json</ProjectAssetsFile>
<NuGetPackageRoot Condition=" '$(NuGetPackageRoot)' == '' ">/Users/marcuswalker/.nuget/packages/</NuGetPackageRoot>
<NuGetPackageFolders Condition=" '$(NuGetPackageFolders)' == '' ">/Users/marcuswalker/.nuget/packages/</NuGetPackageFolders>
<NuGetProjectStyle Condition=" '$(NuGetProjectStyle)' == '' ">PackageReference</NuGetProjectStyle>
<NuGetToolVersion Condition=" '$(NuGetToolVersion)' == '' ">6.5.0</NuGetToolVersion>
</PropertyGroup>
<ItemGroup Condition=" '$(ExcludeRestorePackageImports)' != 'true' ">
<SourceRoot Include="/Users/marcuswalker/.nuget/packages/" />
</ItemGroup>
</Project>
@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" />
@@ -0,0 +1,4 @@
// <autogenerated />
using System;
using System.Reflection;
[assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute(".NETCoreApp,Version=v7.0", FrameworkDisplayName = ".NET 7.0")]
@@ -0,0 +1,22 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("ContactApp")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("ContactApp")]
[assembly: System.Reflection.AssemblyTitleAttribute("ContactApp")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Generated by the MSBuild WriteCodeFragment class.
@@ -0,0 +1 @@
179adf1247370440b107dc2dfb5bbe6de8400e1e
@@ -0,0 +1,11 @@
is_global = true
build_property.TargetFramework = net7.0
build_property.TargetPlatformMinVersion =
build_property.UsingMicrosoftNETSdkWeb =
build_property.ProjectTypeGuids =
build_property.InvariantGlobalization =
build_property.PlatformNeutralAssembly =
build_property.EnforceExtendedAnalyzerRules =
build_property._SupportedPlatformList = Linux,macOS,Windows
build_property.RootNamespace = ContactApp
build_property.ProjectDir = /home/jashton/dev/active/2410-Contacts/ContactApp/
@@ -0,0 +1,8 @@
// <auto-generated/>
global using global::System;
global using global::System.Collections.Generic;
global using global::System.IO;
global using global::System.Linq;
global using global::System.Net.Http;
global using global::System.Threading;
global using global::System.Threading.Tasks;
Binary file not shown.
@@ -0,0 +1,22 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("Contacts")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("Contacts")]
[assembly: System.Reflection.AssemblyTitleAttribute("Contacts")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Generated by the MSBuild WriteCodeFragment class.
@@ -0,0 +1 @@
ac8a5cca5cb465ad43c1acdee69302679ed547f9
@@ -0,0 +1,17 @@
is_global = true
build_property.TargetFramework = net7.0
build_property.TargetPlatformMinVersion =
build_property.UsingMicrosoftNETSdkWeb = true
build_property.ProjectTypeGuids =
build_property.InvariantGlobalization =
build_property.PlatformNeutralAssembly =
build_property.EnforceExtendedAnalyzerRules =
build_property._SupportedPlatformList = Linux,macOS,Windows
build_property.RootNamespace = Contacts
build_property.RootNamespace = Contacts
build_property.ProjectDir = /Users/marcuswalker/Documents/2410-Contacts/
build_property.RazorLangVersion = 7.0
build_property.SupportLocalizedComponentNames =
build_property.GenerateRazorMetadataSourceChecksumAttributes =
build_property.MSBuildProjectDirectory = /Users/marcuswalker/Documents/2410-Contacts
build_property._RazorSourceGeneratorDebug =
@@ -0,0 +1,17 @@
// <auto-generated/>
global using global::Microsoft.AspNetCore.Builder;
global using global::Microsoft.AspNetCore.Hosting;
global using global::Microsoft.AspNetCore.Http;
global using global::Microsoft.AspNetCore.Routing;
global using global::Microsoft.Extensions.Configuration;
global using global::Microsoft.Extensions.DependencyInjection;
global using global::Microsoft.Extensions.Hosting;
global using global::Microsoft.Extensions.Logging;
global using global::System;
global using global::System.Collections.Generic;
global using global::System.IO;
global using global::System.Linq;
global using global::System.Net.Http;
global using global::System.Net.Http.Json;
global using global::System.Threading;
global using global::System.Threading.Tasks;
Binary file not shown.
@@ -0,0 +1 @@
20479485776e2d1315de5d34b1bc77d2e424ee1f
@@ -0,0 +1,124 @@
/home/jashton/dev/active/2410Contacts/bin/Debug/net7.0/Contacts
/home/jashton/dev/active/2410Contacts/bin/Debug/net7.0/Contacts.deps.json
/home/jashton/dev/active/2410Contacts/bin/Debug/net7.0/Contacts.runtimeconfig.json
/home/jashton/dev/active/2410Contacts/bin/Debug/net7.0/Contacts.dll
/home/jashton/dev/active/2410Contacts/bin/Debug/net7.0/Contacts.pdb
/home/jashton/dev/active/2410Contacts/obj/Debug/net7.0/Contacts.csproj.AssemblyReference.cache
/home/jashton/dev/active/2410Contacts/obj/Debug/net7.0/Contacts.GeneratedMSBuildEditorConfig.editorconfig
/home/jashton/dev/active/2410Contacts/obj/Debug/net7.0/Contacts.AssemblyInfoInputs.cache
/home/jashton/dev/active/2410Contacts/obj/Debug/net7.0/Contacts.AssemblyInfo.cs
/home/jashton/dev/active/2410Contacts/obj/Debug/net7.0/Contacts.csproj.CoreCompileInputs.cache
/home/jashton/dev/active/2410Contacts/obj/Debug/net7.0/Contacts.dll
/home/jashton/dev/active/2410Contacts/obj/Debug/net7.0/refint/Contacts.dll
/home/jashton/dev/active/2410Contacts/obj/Debug/net7.0/Contacts.pdb
/home/jashton/dev/active/2410Contacts/obj/Debug/net7.0/Contacts.genruntimeconfig.cache
/home/jashton/dev/active/2410Contacts/obj/Debug/net7.0/ref/Contacts.dll
/home/jashton/dev/active/2410-Contacts/bin/Debug/net7.0/Contacts
/home/jashton/dev/active/2410-Contacts/bin/Debug/net7.0/Contacts.deps.json
/home/jashton/dev/active/2410-Contacts/bin/Debug/net7.0/Contacts.runtimeconfig.json
/home/jashton/dev/active/2410-Contacts/bin/Debug/net7.0/Contacts.dll
/home/jashton/dev/active/2410-Contacts/bin/Debug/net7.0/Contacts.pdb
/home/jashton/dev/active/2410-Contacts/obj/Debug/net7.0/Contacts.csproj.AssemblyReference.cache
/home/jashton/dev/active/2410-Contacts/obj/Debug/net7.0/Contacts.GeneratedMSBuildEditorConfig.editorconfig
/home/jashton/dev/active/2410-Contacts/obj/Debug/net7.0/Contacts.AssemblyInfoInputs.cache
/home/jashton/dev/active/2410-Contacts/obj/Debug/net7.0/Contacts.AssemblyInfo.cs
/home/jashton/dev/active/2410-Contacts/obj/Debug/net7.0/Contacts.csproj.CoreCompileInputs.cache
/home/jashton/dev/active/2410-Contacts/obj/Debug/net7.0/Contacts.dll
/home/jashton/dev/active/2410-Contacts/obj/Debug/net7.0/refint/Contacts.dll
/home/jashton/dev/active/2410-Contacts/obj/Debug/net7.0/Contacts.pdb
/home/jashton/dev/active/2410-Contacts/obj/Debug/net7.0/Contacts.genruntimeconfig.cache
/home/jashton/dev/active/2410-Contacts/obj/Debug/net7.0/ref/Contacts.dll
/home/jashton/dev/active/2410-contacts/bin/Debug/net7.0/appsettings.Development.json
/home/jashton/dev/active/2410-contacts/bin/Debug/net7.0/appsettings.json
/home/jashton/dev/active/2410-contacts/bin/Debug/net7.0/Contacts.staticwebassets.runtime.json
/home/jashton/dev/active/2410-contacts/obj/Debug/net7.0/Contacts.MvcApplicationPartsAssemblyInfo.cache
/home/jashton/dev/active/2410-contacts/obj/Debug/net7.0/Contacts.RazorAssemblyInfo.cache
/home/jashton/dev/active/2410-contacts/obj/Debug/net7.0/Contacts.RazorAssemblyInfo.cs
/home/jashton/dev/active/2410-contacts/obj/Debug/net7.0/staticwebassets/msbuild.Contacts.Microsoft.AspNetCore.StaticWebAssets.props
/home/jashton/dev/active/2410-contacts/obj/Debug/net7.0/staticwebassets/msbuild.build.Contacts.props
/home/jashton/dev/active/2410-contacts/obj/Debug/net7.0/staticwebassets/msbuild.buildMultiTargeting.Contacts.props
/home/jashton/dev/active/2410-contacts/obj/Debug/net7.0/staticwebassets/msbuild.buildTransitive.Contacts.props
/home/jashton/dev/active/2410-contacts/obj/Debug/net7.0/staticwebassets.pack.json
/home/jashton/dev/active/2410-contacts/obj/Debug/net7.0/staticwebassets.build.json
/home/jashton/dev/active/2410-contacts/obj/Debug/net7.0/staticwebassets.development.json
/home/jashton/dev/active/2410-contacts/obj/Debug/net7.0/scopedcss/Pages/Shared/_Layout.cshtml.rz.scp.css
/home/jashton/dev/active/2410-contacts/obj/Debug/net7.0/scopedcss/bundle/Contacts.styles.css
/home/jashton/dev/active/2410-contacts/obj/Debug/net7.0/scopedcss/projectbundle/Contacts.bundle.scp.css
C:/Users/Marcus/Desktop/contacts-console/bin/Debug/net7.0/Contacts.exe
C:/Users/Marcus/Desktop/contacts-console/bin/Debug/net7.0/Contacts.deps.json
C:/Users/Marcus/Desktop/contacts-console/bin/Debug/net7.0/Contacts.runtimeconfig.json
C:/Users/Marcus/Desktop/contacts-console/bin/Debug/net7.0/Contacts.dll
C:/Users/Marcus/Desktop/contacts-console/bin/Debug/net7.0/Contacts.pdb
C:/Users/Marcus/Desktop/contacts-console/obj/Debug/net7.0/Contacts.csproj.AssemblyReference.cache
C:/Users/Marcus/Desktop/contacts-console/obj/Debug/net7.0/Contacts.GeneratedMSBuildEditorConfig.editorconfig
C:/Users/Marcus/Desktop/contacts-console/obj/Debug/net7.0/Contacts.AssemblyInfoInputs.cache
C:/Users/Marcus/Desktop/contacts-console/obj/Debug/net7.0/Contacts.AssemblyInfo.cs
C:/Users/Marcus/Desktop/contacts-console/obj/Debug/net7.0/Contacts.csproj.CoreCompileInputs.cache
C:/Users/Marcus/Desktop/contacts-console/obj/Debug/net7.0/Contacts.MvcApplicationPartsAssemblyInfo.cache
C:/Users/Marcus/Desktop/contacts-console/obj/Debug/net7.0/staticwebassets/msbuild.Contacts.Microsoft.AspNetCore.StaticWebAssets.props
C:/Users/Marcus/Desktop/contacts-console/obj/Debug/net7.0/staticwebassets/msbuild.build.Contacts.props
C:/Users/Marcus/Desktop/contacts-console/obj/Debug/net7.0/staticwebassets/msbuild.buildMultiTargeting.Contacts.props
C:/Users/Marcus/Desktop/contacts-console/obj/Debug/net7.0/staticwebassets/msbuild.buildTransitive.Contacts.props
C:/Users/Marcus/Desktop/contacts-console/obj/Debug/net7.0/staticwebassets.pack.json
C:/Users/Marcus/Desktop/contacts-console/obj/Debug/net7.0/staticwebassets.build.json
C:/Users/Marcus/Desktop/contacts-console/obj/Debug/net7.0/staticwebassets.development.json
C:/Users/Marcus/Desktop/contacts-console/obj/Debug/net7.0/scopedcss/bundle/Contacts.styles.css
C:/Users/Marcus/Desktop/contacts-console/obj/Debug/net7.0/Contacts.dll
C:/Users/Marcus/Desktop/contacts-console/obj/Debug/net7.0/refint/Contacts.dll
C:/Users/Marcus/Desktop/contacts-console/obj/Debug/net7.0/Contacts.pdb
C:/Users/Marcus/Desktop/contacts-console/obj/Debug/net7.0/Contacts.genruntimeconfig.cache
C:/Users/Marcus/Desktop/contacts-console/obj/Debug/net7.0/ref/Contacts.dll
C:/Users/overw/source/repos/2410-Contacts/bin/Debug/net7.0/Contacts.exe
C:/Users/overw/source/repos/2410-Contacts/bin/Debug/net7.0/Contacts.deps.json
C:/Users/overw/source/repos/2410-Contacts/bin/Debug/net7.0/Contacts.runtimeconfig.json
C:/Users/overw/source/repos/2410-Contacts/bin/Debug/net7.0/Contacts.dll
C:/Users/overw/source/repos/2410-Contacts/bin/Debug/net7.0/Contacts.pdb
C:/Users/overw/source/repos/2410-Contacts/obj/Debug/net7.0/Contacts.csproj.AssemblyReference.cache
C:/Users/overw/source/repos/2410-Contacts/obj/Debug/net7.0/Contacts.GeneratedMSBuildEditorConfig.editorconfig
C:/Users/overw/source/repos/2410-Contacts/obj/Debug/net7.0/Contacts.AssemblyInfoInputs.cache
C:/Users/overw/source/repos/2410-Contacts/obj/Debug/net7.0/Contacts.AssemblyInfo.cs
C:/Users/overw/source/repos/2410-Contacts/obj/Debug/net7.0/Contacts.csproj.CoreCompileInputs.cache
C:/Users/overw/source/repos/2410-Contacts/obj/Debug/net7.0/Contacts.MvcApplicationPartsAssemblyInfo.cache
C:/Users/overw/source/repos/2410-Contacts/obj/Debug/net7.0/staticwebassets/msbuild.Contacts.Microsoft.AspNetCore.StaticWebAssets.props
C:/Users/overw/source/repos/2410-Contacts/obj/Debug/net7.0/staticwebassets/msbuild.build.Contacts.props
C:/Users/overw/source/repos/2410-Contacts/obj/Debug/net7.0/staticwebassets/msbuild.buildMultiTargeting.Contacts.props
C:/Users/overw/source/repos/2410-Contacts/obj/Debug/net7.0/staticwebassets/msbuild.buildTransitive.Contacts.props
C:/Users/overw/source/repos/2410-Contacts/obj/Debug/net7.0/staticwebassets.pack.json
C:/Users/overw/source/repos/2410-Contacts/obj/Debug/net7.0/staticwebassets.build.json
C:/Users/overw/source/repos/2410-Contacts/obj/Debug/net7.0/staticwebassets.development.json
C:/Users/overw/source/repos/2410-Contacts/obj/Debug/net7.0/scopedcss/bundle/Contacts.styles.css
C:/Users/overw/source/repos/2410-Contacts/obj/Debug/net7.0/Contacts.dll
C:/Users/overw/source/repos/2410-Contacts/obj/Debug/net7.0/refint/Contacts.dll
C:/Users/overw/source/repos/2410-Contacts/obj/Debug/net7.0/Contacts.pdb
C:/Users/overw/source/repos/2410-Contacts/obj/Debug/net7.0/Contacts.genruntimeconfig.cache
C:/Users/overw/source/repos/2410-Contacts/obj/Debug/net7.0/ref/Contacts.dll
C:/Users/Marcus/Desktop/contacts-console/bin/Debug/net7.0/Crayon.dll
C:/Users/Marcus/Desktop/contacts-console/obj/Debug/net7.0/Contacts.csproj.CopyComplete
C:/Users/overw/source/repos/2410-Contacts/bin/Debug/net7.0/Crayon.dll
C:/Users/overw/source/repos/2410-Contacts/obj/Debug/net7.0/Contacts.csproj.CopyComplete
/Users/marcuswalker/Documents/2410-Contacts/bin/Debug/net7.0/Contacts
/Users/marcuswalker/Documents/2410-Contacts/bin/Debug/net7.0/Contacts.deps.json
/Users/marcuswalker/Documents/2410-Contacts/bin/Debug/net7.0/Contacts.runtimeconfig.json
/Users/marcuswalker/Documents/2410-Contacts/bin/Debug/net7.0/Contacts.dll
/Users/marcuswalker/Documents/2410-Contacts/bin/Debug/net7.0/Contacts.pdb
/Users/marcuswalker/Documents/2410-Contacts/bin/Debug/net7.0/Crayon.dll
/Users/marcuswalker/Documents/2410-Contacts/obj/Debug/net7.0/Contacts.csproj.AssemblyReference.cache
/Users/marcuswalker/Documents/2410-Contacts/obj/Debug/net7.0/Contacts.GeneratedMSBuildEditorConfig.editorconfig
/Users/marcuswalker/Documents/2410-Contacts/obj/Debug/net7.0/Contacts.AssemblyInfoInputs.cache
/Users/marcuswalker/Documents/2410-Contacts/obj/Debug/net7.0/Contacts.AssemblyInfo.cs
/Users/marcuswalker/Documents/2410-Contacts/obj/Debug/net7.0/Contacts.csproj.CoreCompileInputs.cache
/Users/marcuswalker/Documents/2410-Contacts/obj/Debug/net7.0/Contacts.MvcApplicationPartsAssemblyInfo.cache
/Users/marcuswalker/Documents/2410-Contacts/obj/Debug/net7.0/staticwebassets/msbuild.Contacts.Microsoft.AspNetCore.StaticWebAssets.props
/Users/marcuswalker/Documents/2410-Contacts/obj/Debug/net7.0/staticwebassets/msbuild.build.Contacts.props
/Users/marcuswalker/Documents/2410-Contacts/obj/Debug/net7.0/staticwebassets/msbuild.buildMultiTargeting.Contacts.props
/Users/marcuswalker/Documents/2410-Contacts/obj/Debug/net7.0/staticwebassets/msbuild.buildTransitive.Contacts.props
/Users/marcuswalker/Documents/2410-Contacts/obj/Debug/net7.0/staticwebassets.pack.json
/Users/marcuswalker/Documents/2410-Contacts/obj/Debug/net7.0/staticwebassets.build.json
/Users/marcuswalker/Documents/2410-Contacts/obj/Debug/net7.0/staticwebassets.development.json
/Users/marcuswalker/Documents/2410-Contacts/obj/Debug/net7.0/scopedcss/bundle/Contacts.styles.css
/Users/marcuswalker/Documents/2410-Contacts/obj/Debug/net7.0/Contacts.csproj.CopyComplete
/Users/marcuswalker/Documents/2410-Contacts/obj/Debug/net7.0/Contacts.dll
/Users/marcuswalker/Documents/2410-Contacts/obj/Debug/net7.0/refint/Contacts.dll
/Users/marcuswalker/Documents/2410-Contacts/obj/Debug/net7.0/Contacts.pdb
/Users/marcuswalker/Documents/2410-Contacts/obj/Debug/net7.0/Contacts.genruntimeconfig.cache
/Users/marcuswalker/Documents/2410-Contacts/obj/Debug/net7.0/ref/Contacts.dll
Binary file not shown.
@@ -0,0 +1 @@
7a96de072f111734042ad45faa57d5c212ab845a
Binary file not shown.
BIN
View File
Binary file not shown.
Binary file not shown.
Binary file not shown.
+100
View File
@@ -0,0 +1,100 @@
{
"version": 3,
"targets": {
"net7.0": {
"Crayon/2.0.69": {
"type": "package",
"compile": {
"lib/netstandard2.0/Crayon.dll": {}
},
"runtime": {
"lib/netstandard2.0/Crayon.dll": {}
}
}
}
},
"libraries": {
"Crayon/2.0.69": {
"sha512": "eJHxoMTfhZs1782YUIMafXIDTPcTwAV5I3MNsl2d4Mn61/h3ABPMSzHwzigL/NO7BrCKRoP4gHJuERpLHdSCvg==",
"type": "package",
"path": "crayon/2.0.69",
"files": [
".nupkg.metadata",
".signature.p7s",
"crayon.2.0.69.nupkg.sha512",
"crayon.nuspec",
"lib/netstandard2.0/Crayon.dll"
]
}
},
"projectFileDependencyGroups": {
"net7.0": [
"Crayon >= 2.0.69"
]
},
"packageFolders": {
"/Users/marcuswalker/.nuget/packages/": {}
},
"project": {
"version": "1.0.0",
"restore": {
"projectUniqueName": "/Users/marcuswalker/Documents/2410-Contacts/Contacts.csproj",
"projectName": "Contacts",
"projectPath": "/Users/marcuswalker/Documents/2410-Contacts/Contacts.csproj",
"packagesPath": "/Users/marcuswalker/.nuget/packages/",
"outputPath": "/Users/marcuswalker/Documents/2410-Contacts/obj/",
"projectStyle": "PackageReference",
"configFilePaths": [
"/Users/marcuswalker/.nuget/NuGet/NuGet.Config"
],
"originalTargetFrameworks": [
"net7.0"
],
"sources": {
"https://api.nuget.org/v3/index.json": {}
},
"frameworks": {
"net7.0": {
"targetAlias": "net7.0",
"projectReferences": {}
}
},
"warningProperties": {
"warnAsError": [
"NU1605"
]
}
},
"frameworks": {
"net7.0": {
"targetAlias": "net7.0",
"dependencies": {
"Crayon": {
"target": "Package",
"version": "[2.0.69, )"
}
},
"imports": [
"net461",
"net462",
"net47",
"net471",
"net472",
"net48",
"net481"
],
"assetTargetFallback": true,
"warn": true,
"frameworkReferences": {
"Microsoft.AspNetCore.App": {
"privateAssets": "none"
},
"Microsoft.NETCore.App": {
"privateAssets": "all"
}
},
"runtimeIdentifierGraphPath": "/usr/local/share/dotnet/sdk/7.0.203/RuntimeIdentifierGraph.json"
}
}
}
}
+10
View File
@@ -0,0 +1,10 @@
{
"version": 2,
"dgSpecHash": "hLf4B0n+n6M/x10I7MS4T+MbxFSG+50xIg2qJF4KHIq49lAHX6cG+62zutm3rbOfEU/CZrsdUv0fn88Rt+TDaw==",
"success": true,
"projectFilePath": "/Users/marcuswalker/Documents/2410-Contacts/Contacts.csproj",
"expectedPackageFiles": [
"/Users/marcuswalker/.nuget/packages/crayon/2.0.69/crayon.2.0.69.nupkg.sha512"
],
"logs": []
}
+1
View File
@@ -0,0 +1 @@
"restore":{"projectUniqueName":"/home/jashton/dev/active/2410-contacts/Contacts.csproj","projectName":"Contacts","projectPath":"/home/jashton/dev/active/2410-contacts/Contacts.csproj","outputPath":"/home/jashton/dev/active/2410-contacts/obj/","projectStyle":"PackageReference","originalTargetFrameworks":["net7.0"],"sources":{"https://api.nuget.org/v3/index.json":{}},"frameworks":{"net7.0":{"targetAlias":"net7.0","projectReferences":{}}},"warningProperties":{"warnAsError":["NU1605"]}}"frameworks":{"net7.0":{"targetAlias":"net7.0","imports":["net461","net462","net47","net471","net472","net48","net481"],"assetTargetFallback":true,"warn":true,"downloadDependencies":[{"name":"Microsoft.AspNetCore.App.Ref","version":"[7.0.3, 7.0.3]"}],"frameworkReferences":{"Microsoft.AspNetCore.App":{"privateAssets":"none"},"Microsoft.NETCore.App":{"privateAssets":"all"}},"runtimeIdentifierGraphPath":"/usr/share/dotnet/sdk/7.0.103/RuntimeIdentifierGraph.json"}}
+1
View File
@@ -0,0 +1 @@
16816954560259051
+15
View File
@@ -0,0 +1,15 @@
# Contact Project A05
### Project Status
- [X] Imports from `.card`, and `.vcf`
- [-] Exporting into human readable (`.json`?)
- Making it into a `.save` file instead. No specific naming scheme in mind
- [X] Exporing into both Outlook and Google `.csv`s
- [ ] Exporting into `.card`
- [ ] Exporting into `.vcf`
- [X] Figure out what kind of UX should be given 👀
- [ ] Contact Merger??
### Third Party Libraries
- [Crayon by riezebosch](https://github.com/riezebosch/Crayon)
- helps out with the formatting of the command line
+3
View File
@@ -0,0 +1,3 @@
# Snake
Snake
CLI snake game. CSIS 2410 project A05.
+16
View File
@@ -0,0 +1,16 @@
Microsoft Visual Studio Solution File, Format Version 12.00
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Snake", "Snake\Snake.csproj", "{4A6995A3-4AC4-4954-A7CA-904A77D5AC85}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{4A6995A3-4AC4-4954-A7CA-904A77D5AC85}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4A6995A3-4AC4-4954-A7CA-904A77D5AC85}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4A6995A3-4AC4-4954-A7CA-904A77D5AC85}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4A6995A3-4AC4-4954-A7CA-904A77D5AC85}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal
+64
View File
@@ -0,0 +1,64 @@
namespace Snake
{
///
/// <summary>Represents a Console position in Left and Top coordinates, AKA (x, y).</summary>
///
/// <author>Josh Ashton</author>
///
public class Position
{
public int X1;
public int X2;
public int Y { get; }
private const ConsoleColor D_GREEN = ConsoleColor.DarkGreen;
private const ConsoleColor BLACK = ConsoleColor.Black;
private const ConsoleColor GREEN = ConsoleColor.Green;
private const ConsoleColor WHITE = ConsoleColor.White;
private const ConsoleColor YELLOW = ConsoleColor.Yellow;
public bool SnakeKiller { get; }
public bool Snake { get; set; }
public Position Next { get; set; }
public Position Prev { get; set; }
public Position(int x1, int x2, int y)
{
X1 = x1;
X2 = x2;
Y = y;
}
public Position(int x1, int x2, int y, bool snakeKiller)
{
X1 = x1;
X2 = x2;
Y = y;
SnakeKiller = snakeKiller;
}
public void Draw(bool isHead) {
if(SnakeKiller)
{
Console.BackgroundColor = D_GREEN;
Console.Write(" ");
Console.BackgroundColor = BLACK;
} else if (Snake)
{
Console.BackgroundColor = WHITE;
Console.Write(" ");
Console.BackgroundColor = BLACK;
} else if (isHead)
{
Console.BackgroundColor = GREEN;
Console.Write(" ");
Console.BackgroundColor = BLACK;
}
else
{
Console.Write(" ");
}
}
}
}
+228
View File
@@ -0,0 +1,228 @@
using System.ComponentModel;
using System.Timers;
using Timer = System.Timers.Timer;
namespace Snake;
public class Program
{
int leftMargin = 9;
int topMargin = 0;
private int height = 19;
private int width = 31;
private double difficulty;
private int time;
private Position[][] grid;
private Position bottom { get; set; }
private Position top { get; set; }
static void Main(string[] args)
{
Program p = new Program();
p.bottom = new Position(p.leftMargin, p.leftMargin + 1, p.topMargin + p.height);
p.top = new Position(p.leftMargin, p.leftMargin + 1, p.topMargin);
p.time = 0;
p.PrintIntro();
p.MenuInput();
}
void DrawSnake()
{
Snake s = new Snake(grid, 100);
Timer t = new Timer(100);
t.Elapsed += TimerAction;
t.Enabled = true;
if (!s.Move())
{
DisplayGameOver();
Thread.Sleep(3000);
PrintIntro();
MenuInput();
}
else
{
DisplayNextLevel();
}
}
void TimerAction(object? sender, ElapsedEventArgs elapsedEventArgs)
{
time++;
}
void PrintIntro()
{
string[] s =
{
"╔════════════════════════════════════════════════════════════╗",
" /^\\/^\\ ",
" _|__| O| ",
" \\/ /~ \\_/ \\ ",
" \\____|__________/ \\ ",
" \\_______ \\ ",
" '\\ \\ \\ ",
" | | \\ ",
" / / \\ ",
" / / \\\\ ",
" / / \\\\ ",
" / / \\ \\\\ ",
" / / _----_ \\ \\\\ ",
" / / _-~ ~-_ | | ",
" ( ( _-~ _--_ ~-_ _/ | ",
" \\ ~-____-~ _-~ ~-_ ~-_-~ / ",
" ~-_ _-~ ~-_ _-~ ",
" ~--______-~ ~-___-~ ",
"╚════════════════════════════════════════════════════════════╝"
};
PrintConsole(s);
}
// TODO: Can no longer press q or r after starting the game.
void MenuInput()
{
Console.SetCursorPosition(bottom.X1, bottom.Y);
Console.Write("Enter p to play, q to quit, r for rules: ");
char input = Console.ReadKey().KeyChar;
Console.SetCursorPosition(bottom.X1, bottom.Y);
while (input != 'q')
{
switch (input)
{
case 'p':
Console.SetCursorPosition(bottom.X1, bottom.Y);
Console.Write("Enter e for easy, m for medium, and h for hard: ");
char level = Console.ReadKey().KeyChar;
grid = new Position[height][];
switch (level)
{
case 'e':
grid = GenerateGameBoard(grid, 0.03);
break;
case 'm':
grid = GenerateGameBoard(grid, 0.06);
break;
case 'h':
grid = GenerateGameBoard(grid, 0.1);
break;
}
DrawGameBoard(grid);
DrawSnake();
break;
case 'q':
Environment.Exit(0);
break;
case 'r':
DisplayRules();
break;
}
}
}
void DrawGameBoard(Position[][] grid)
{
for (int i = 0; i < grid.Length; i++)
{
for (int j = 0; j < grid[i].Length; j++)
{
Console.SetCursorPosition(grid[i][j].X1, grid[i][j].Y);
grid[i][j].Draw(false);
}
Console.WriteLine();
}
time = 0;
}
void DisplayRules()
{
Position[][] grid = new Position[height][];
grid = GenerateGameBoard(grid, 0.03);
DrawGameBoard(grid);
string rules = (
"RULES:\n" +
" - Do not let the snake head touch walls or obstacles.\n" +
" - Use the arrow keys to control the snake."
//" - Collect all points in a level to move to the next level.",
//" - Levels increase difficulty."
);
PrintConsole(rules);
}
// TODO: ASCII art for game over screen
void DisplayGameOver()
{
string[] s =
{
"",
"",
"⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣠⡀⠀",
"⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣤⣤⠀⠀⠀⢀⣴⣿⡶⠀⣾⣿⣿⡿⠟⠛⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀",
"⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣀⣄⣀⠀⠀⠀⠀⣶⣶⣦⠀⠀⠀⠀⣼⣿⣿⡇⠀⣠⣿⣿⣿⠇⣸⣿⣿⣧⣤⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀",
"⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣴⣾⣿⡿⠿⠿⠿⠇⠀⠀⣸⣿⣿⣿⡆⠀⠀⢰⣿⣿⣿⣷⣼⣿⣿⣿⡿⢀⣿⣿⡿⠟⠛⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀",
"⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣴⣿⡿⠋⠁⠀⠀⠀⠀⠀⠀⢠⣿⣿⣹⣿⣿⣿⣿⣿⣿⡏⢻⣿⣿⢿⣿⣿⠃⣼⣿⣯⣤⣴⣶⣿⡤⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀",
"⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣼⣿⠏⠀⣀⣠⣤⣶⣾⣷⠄⣰⣿⣿⡿⠿⠻⣿⣯⣸⣿⡿⠀⠀⠀⠁⣾⣿⡏⢠⣿⣿⠿⠛⠋⠉⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀",
"⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿⣿⠲⢿⣿⣿⣿⣿⡿⠋⢰⣿⣿⠋⠀⠀⠀⢻⣿⣿⣿⠇⠀⠀⠀⠀⠙⠛⠀⠀⠉⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀",
"⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠹⢿⣷⣶⣿⣿⠿⠋⠀⠀⠈⠙⠃⠀⠀⠀⠀⠀⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀",
"⠀⠈⠉⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣤⣤⣴⣶⣦⣤⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀",
"⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⡀⠀⠀⠀⠀⠀⠀⠀⣠⡇⢰⣶⣶⣾⡿⠷⣿⣿⣿⡟⠛⣉⣿⣿⣿⠆⠀⠀⠀⠀⠀⠀⠀⠀⠀",
"⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣤⣶⣿⣿⡎⣿⣿⣦⠀⠀⠀⢀⣤⣾⠟⢀⣿⣿⡟⣁⠀⠀⣸⣿⣿⣤⣾⣿⡿⠛⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀",
"⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣠⣾⣿⡿⠛⠉⢿⣦⠘⣿⣿⡆⠀⢠⣾⣿⠋⠀⣼⣿⣿⣿⠿⠷⢠⣿⣿⣿⠿⢻⣿⣧⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀",
"⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣴⣿⣿⠋⠀⠀⠀⢸⣿⣇⢹⣿⣷⣰⣿⣿⠃⠀⢠⣿⣿⢃⣀⣤⣤⣾⣿⡟⠀⠀⠀⢻⣿⣆⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀",
"⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿⣿⡇⠀⠀⢀⣴⣿⣿⡟⠀⣿⣿⣿⣿⠃⠀⠀⣾⣿⣿⡿⠿⠛⢛⣿⡟⠀⠀⠀⠀⠀⠻⠿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀",
"⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠹⣿⣿⣶⣾⣿⣿⣿⠟⠁⠀⠸⢿⣿⠇⠀⠀⠀⠛⠛⠁⠀⠀⠀⠀⠀⠁⠀⠀⠀⠀⠀⠀⠀⠀",
"⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠙⠛⠛⠛⠋⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀",
""
};
// Prints score and time below ASCII art of same dimension as the snake drawing above
PrintConsole($"Score: {time * 100} | Time: {time / 10} seconds ");
PrintConsole(s);
time = 0;
}
void DisplayNextLevel()
{
grid = GenerateGameBoard(grid, difficulty * (1 + difficulty));
DrawGameBoard(grid);
DrawSnake();
}
void PrintConsole(string message)
{
Console.SetCursorPosition(bottom.X1, bottom.Y + 1);
Console.WriteLine(message);
}
void PrintConsole(string[] s)
{
Console.BackgroundColor = ConsoleColor.Black;
for (int i = 0; i < s.Length; i++)
{
Console.SetCursorPosition(top.X1, top.Y + i);
Console.WriteLine(s[i]);
}
}
private Position[][] GenerateGameBoard(Position[][] grid, double chance)
{
int xCounter = 0;
for (int y = 0; y < grid.Length; y++)
{
grid[y] = new Position[width];
for (int x = 0; x < grid[y].Length; x++)
{
if (x == 0 || x == grid[y].Length - 1 || y == 0 || y == grid.Length - 1 ||
new Random().NextDouble() <= chance)
{
grid[y][x] = new Position(xCounter++ + leftMargin, xCounter++ + leftMargin, y + topMargin, true);
}
else
{
grid[y][x] = new Position(xCounter++ + leftMargin, xCounter++ + leftMargin, y + topMargin, false);
}
}
xCounter = 0;
}
return grid;
}
}
+83
View File
@@ -0,0 +1,83 @@
namespace Snake
{
/// <summary>
/// Represents the in-game snake, which traverses the 2D array of Positions.
/// </summary>
public class Snake
{
private Queue<Position> body;
private int n;
private int capacity;
private Position[][] grid;
private bool Collided;
public Snake(Position[][] grid, int capacity)
{
this.grid = grid;
this.capacity = capacity;
n = 0;
Collided = false;
body = new Queue<Position>();
}
public bool Move()
{
Console.ForegroundColor = ConsoleColor.Black;
int x = 1;
int y = grid.Length / 2;
int direction = 0;
while (!Collided && x < grid[0].Length - 1 && y < grid.Length - 1 && x > 0 && y > 0)
{
if (Console.KeyAvailable)
{
char d = Console.ReadKey().KeyChar;
switch (d)
{
case 'w':
direction = 1;
break;
case 'a':
direction = 2;
break;
case 's':
direction = 3;
break;
case 'd':
direction = 0;
break;
}
}
Console.SetCursorPosition(grid[y][x].X1, grid[y][x].Y);
grid[y][x].Draw(false);
switch (direction)
{
case 0: // move right
x++;
break;
case 1: // move up
y--;
break;
case 2: // move left
x--;
break;
case 3: // move down
y++;
break;
}
if (grid[y][x].SnakeKiller)
{
Console.SetCursorPosition(grid[0][0].X1, grid[grid.Length - 1][0].Y + 1);
Console.ForegroundColor = ConsoleColor.White;
return false;
}
body.Enqueue(grid[y][x]);
body.Dequeue();
grid[y][x].Snake = true;
Thread.Sleep(150);
}
Console.ForegroundColor = ConsoleColor.White;
return true;
}
}
}
+10
View File
@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>