Having a problem with my code here. My code is supposed to (what I want it to do) is after the game ends a spritefont appears that allows you to enter text and once that text is entered then it would write that score to the text file. But of course it does not do that. If anyone could help, would be grand.
EDIT
This is what I am using to try and input text after the game is over (Game is Space Invaders) Perhaps there is something wrong here also.
SpriteFont Label;
string txt = ".";
Keys PrevKey;
string[] HighScores = new string[5];
int count = 0;
KeyboardState ks = Keyboard.GetState();
Keys[] k = ks.GetPressedKeys();
Keys tempKey = Keys.None;
string keyChar = "";
foreach (Keys q in k)
{
Keys currentKey = q;
if (ks.IsKeyUp(PrevKey))
{
if (!(q == Keys.None))
{
switch (q)
{
case Keys.Space: keyChar = " "; break;
case Keys.Delete: txt = ""; break;
case Keys.Back: txt = txt.Remove(txt.Length - 1); break;
case Keys.Enter: HighScores[count] = txt; count++; txt = "";
if (count == 5) count = 0; break;
case Keys.End: WriteScores(); break;
case Keys.Home: ReadScores(); break;
default: keyChar = q.ToString(); break;
}
txt += keyChar;
}
}
if (currentKey != Keys.None && ks.IsKeyDown(currentKey))
{
tempKey = currentKey;
}
}
PrevKey = tempKey;
base.Update(gameTime);
}
}
}
}
public void WriteScores()
{
StreamWriter Rite = new StreamWriter(#"C:\TheScores.txt");
for (int i = 0; i < HighScores.Length; i++)
{
Rite.WriteLine(HighScores[i]);
}
Rite.Close();
}
public void ReadScores()
{
if (File.Exists(#"C:\TheHighScores.txt"))
{
StreamReader Reed = new StreamReader(#"C:\TheScores.txt");
for (int i = 0; i < HighScores.Length; i++)
{
txt += Reed.ReadLine() + "\n";
}
Reed.Close();
}
}
Change the path to a user folder like Documents or AppData. Your code as it is will throw an access violation for insufficient permissions unless you run your program as administrator, as the root of C:\ is only available from an elevated context.
Related
I am making simple PRG in console.
In my MenuSystem Console.Clear() does not clear text from other methods.
Any ideas?
class MenuSystem
{
public static void Controll(int count, List<String> texts)
{
Console.Clear();
int index = 0;
bool isEnter = false;
Write(0, texts);
while (!isEnter)
{
ConsoleKey key = Console.ReadKey().Key;
switch (key)
{
case ConsoleKey.UpArrow:
index -= 1;
break;
case ConsoleKey.DownArrow:
index += 1;
break;
}
if (index > (count - 1))
index = 0;
else if (index < 0)
index = count - 1;
Write(index, texts);
}
}
private static void Write(int index, List<String> texts)
{
Console.Clear();
texts[index] = "[ " + texts[index] + " ]";
foreach (String text in texts)
{
Console.WriteLine(text);
}
}
Console.Clear() in Write() does not clear console.
I think the problem you're having is not with Console.Clear (whose only purpose is to clear the screen, not "clear text from other methods" as you suggested.
The problem is that you're modifying an element in your array, then modifying a new element in the array without un-modifying the previous one. If you wanted to solve this problem using your current method, then you would need to track which item you previously modified in a class-level variable so you can un-modify it when the user changes the selection.
However, I would suggest a different approach. Instead of modifying the strings in your list, you should just change the way you display the information, not the information itself.
So, after applying your logic to detect which index to select, you just loop through the menu items and write them to the screen, and when you get to the index of the item that's selected, you write the "[" and "]" characters around it. For the other menu items, you should surround them with an empty space character, so they aren't moving all over the place as the selections change.
Note that I also made a small change to have the menu display horizontally:
class MenuSystem
{
public static void Control(List<string> menuItems)
{
var selectedIndex = 0;
var exitMenu = false;
while (!exitMenu)
{
DisplayMenu(selectedIndex, menuItems);
switch (Console.ReadKey().Key)
{
case ConsoleKey.LeftArrow:
selectedIndex -= 1;
if (selectedIndex < 0) selectedIndex = menuItems.Count - 1;
break;
case ConsoleKey.RightArrow:
selectedIndex += 1;
if (selectedIndex > menuItems.Count - 1) selectedIndex = 0;
break;
case ConsoleKey.Enter:
exitMenu = true;
break;
}
}
}
private static void DisplayMenu(int selectedIndex, List<string> menuItems)
{
Console.Clear();
for (int i = 0; i < menuItems.Count; i++)
{
if (i == selectedIndex)
{
Console.Write("[" + menuItems[i] + "]");
}
else
{
Console.Write(" " + menuItems[i] + " ");
}
Console.Write(" ");
}
}
}
This is really an answer to your question but merely a demonstration that the code you have posted does work.
private static void Main()
{
Console.Write("Some Text");
Console.Read(); //Console shows Show Text
MenuSystem.Controll(1, new List<string>() { "string" });
Console.Read(); //Console shows string
}
...
class MenuSystem
{
public static void Controll(int count, List<String> texts)
{
Write(count, texts);
}
private static void Write(int index, List<String> texts) //I don't know why you are passing index as it is never used here.
{
Console.Clear(); //Console is now cleared
foreach (String text in texts)
{
Console.WriteLine(text);
}
}
}
As the code you have provided is working I can only presume that there is some other logic in your full code that is causing the issue.
Please update your question with code that demonstrates your issue.
The example is far from perfect, but you will get the sense of using Console.Clear():
class Program
{
static void DrawPlayer(int x, int y)
{
for (int i = 0; i < y; i++)
Console.WriteLine();
for (int j = 0; j < x; j++)
Console.Write(' ');
Console.Write("\u25A0");
}
static void Main()
{
int playerX = 0, playerY = 0;
while (true)
{
DrawPlayer(playerX, playerY);
var keyInfo = Console.ReadKey(true);
switch (keyInfo.Key)
{
case ConsoleKey.W:
playerY--;
break;
case ConsoleKey.A:
playerX--;
break;
case ConsoleKey.S:
playerY++;
break;
case ConsoleKey.D:
playerX++;
break;
}
Console.Clear();
}
}
}
using System;
public class ReadWriteTxt // Read and write to/from text files
{
public static string cipherTxt()
{
return System.IO.File.ReadAllText(#"myfile1");
}
internal static void decipherTxt(string result)
{
System.IO.File.WriteAllText(#"myfile2", result);
}
}
public class LetterArray
{
internal static string[] Alphabet()
{
var letterValues = new string[26];
letterValues[0] = "A";
letterValues[1] = "B";
letterValues[2] = "C";
letterValues[3] = "D";
letterValues[4] = "E";
letterValues[5] = "F";
letterValues[6] = "G";
letterValues[7] = "H";
letterValues[8] = "I";
letterValues[9] = "J";
letterValues[10] = "K";
letterValues[11] = "L";
letterValues[12] = "M";
letterValues[13] = "N";
letterValues[14] = "O";
letterValues[15] = "P";
letterValues[16] = "Q";
letterValues[17] = "R";
letterValues[18] = "S";
letterValues[19] = "T";
letterValues[20] = "U";
letterValues[21] = "V";
letterValues[22] = "W";
letterValues[23] = "X";
letterValues[24] = "Y";
letterValues[25] = "Z";
return letterValues;
}
}
public class Decipher
{
public static void Main() //Main method
{
int res = 34;
string[] letterValues = LetterArray.Alphabet();
//Create for loop that runs through every possible shift value
for (int shift = 0; shift <= 25; shift++)
{
Console.WriteLine("\nShift Value = " + shift + ": ");
// For each character in the text file
foreach (var ch in ReadWriteTxt.cipherTxt())
{
string result = string.Empty;
if (ch == ' ')
{
}
else
{
for (int i = 0; i <= 25; i++)
{
if ((ch.ToString().ToUpper()) == letterValues[i])
{
res = i;
if (shift > res)
{
// print results out
Console.Write(letterValues[26 - (shift - res)][0]);
}
else
{
Console.Write(letterValues[res - shift][0]);
}
}
}
ReadWriteTxt.decipherTxt(result);
}
}
}
}
}
I'm working on a Caesar Cipher program that decrypts cipher text that it reads in from a file.
It lists all the possible shifts throughout the alphabet.
I need to be able allow the user to enter the 'correct' shift value (e.g. the one closest to what the decrypted text should translate too) and then have the corresponding string written to a file.
What is the best to go about this?
P.S. My understanding of C# is a bit basic so please be gentle with me ;).
Basically, continuing from this question, when the user presses shift + either left or right I need it to select the entire character group.
The current code I have (under the PreviewKeyDown Event):
string s;
int caretLocation = textBox1.SelectionStart;
string txt = textBox1.Text;
if (e.Shift)
{
switch (e.KeyCode)
{
#region Right
case Keys.Right:
{
s = txt.Substring(caretLocation);
foreach (string combo in charCombinations)
{
if (s.StartsWith(combo))
{
textBox1.SelectionLength = combo.Length - 1;
break;
}
}
break;
}
#endregion
#region Left
case Keys.Left:
{
s = txt.Substring(0, caretLocation);
foreach (string combo in charCombinations)
{
if (s.EndsWith(combo))
{
textBox1.SelectionStart = caretLocation - combo.Length + 1;
textBox1.SelectionLength = combo.Length + 1
break;
}
}
break;
}
#endregion
}
}
The first issue lies with the right key, where if there are two of such character groups in a row, the caret does not move right any further from the position shown below:
The second issue lies with the left key, where the left key selection just doesn't select the entire character:
For this case, the entire word sin( should be selected.
Thanks in advance!
charCombinations has been defined as:
private static readonly string[] charCombinations = new string[] { "asinh(", "acosh", "atanh(",
"sinh(", "cosh(", "tanh(", "asin(", "acos(", "atan(", "sin(", "cos(", "tan(",
"log(", "ln(", "PI", "e", "Phi"};
You must add next text length to previous length.
I fixed your codes this model:
case Keys.Right:
{
s = txt.Substring(caretLocation);
foreach (string combo in charCombinations)
{
if (s.StartsWith(combo))
{
textBox1.SelectionLength += combo.Length - 1;
break;
}
}
break;
}
The important line is: textBox1.SelectionLength += combo.Length - 1;
in that I use += instead =
I've been working with OpenDesign Specification for .dwg files about two weeks. And now, i've got all information except non-entity object and entity object. Maybe i can't understand how this information written. Concretely i need to know how to differ non-entity object and entity object. Work on C#. http://opendesign.com/files/guestdownloads/OpenDesign_Specification_for_.dwg_files.pdf on the page 98.
This is how i found out non-entity object format:
private bool ReadNonEntityObject(FileReader fileReader, DWGVersion version, long handle, long fileLoc)
{
long oldPos = fileReader.BufferPosition;
BaseTypes bReader = new BaseTypes(fileReader);
fileReader.SeekAbsolute(fileLoc);
var size = bReader.GetModularShort();
if (version.IsLaterOrEqual(DWGVersion.VersionEnum.R2010))
{
var HandleSize = bReader.GetModularChar(false);
}
var objectType = bReader.GetObjectType(version);
Console.WriteLine(BitConverter.ToString(BitConverter.GetBytes(objectType), 0).Substring(0, 2));
if (version.IsLaterOrEqual(DWGVersion.VersionEnum.R2000) && version.IsEarlier(DWGVersion.VersionEnum.R2010))
{
var ObjectSize = bReader.GetLongRaw();
}
var handl = bReader.GetHandle();
if (handl != handle)
throw new Exception("DWG file is corrupted or incorrect");
var extendedSize = bReader.GetShort();
int size1 = 0;
bool isGraphic = fileReader.GetBits(1, true)[0];
if (isGraphic)
size1 = bReader.GetLongRaw();
if (extendedSize != 0)
{
var appHandle = bReader.GetHandle();
var endPos = fileReader.BufferPosition + extendedSize;
string data = "";//DEBUG for testing
while (fileReader.BufferPosition < endPos)
{
int byteCode = bReader.GetByteRaw();
object val = null;
switch (byteCode) //TODO add all byteCode
{
case 0:
{
if (version.IsEarlier(DWGVersion.VersionEnum.R2007))
{
int N = bReader.GetByteRaw();
var codePage = bReader.GetShortRaw();
val = bReader.GetStringAscii(N);
}
if (version.IsLaterOrEqual(DWGVersion.VersionEnum.R2007))
{
//TODO
}
}
break;
case 1:
val = bReader.GetText();
break;
case 8:
{
break;
}
case 2:
val = bReader.GetCharAscii() == 0 ? '{' : '}';
break;
case 40:
bReader.Get3DDouble();
break;
case 145:
{
val = bReader.GetDouble();
break;
}
case 70:
val = bReader.GetShortRaw();
break;
case 71:
val = bReader.GetLongRaw();
break;
default:
val = "";
break;
}
data += val + " ";
//Console.WriteLine(data);
}
}
if (version.Equals(DWGVersion.VersionEnum.R13_R14))
{
var DataSize = bReader.GetLongRaw();
var persistentNum = bReader.GetByteRaw();
}
if (version.IsLaterOrEqual(DWGVersion.VersionEnum.R2004))
{
}
fileReader.SeekAbsolute(oldPos);
return true;
}
There is no isGraphic bit in non-entity object.
Extended data only. it is loop-like, see page 254.
in my experience most types - are entity objects.
i have base class for object and some heder reader in it. Many types extends from each other.
Use crc check, where it is for check you proof.
I am developing a WPF application.
In this application I read from multiple txt files using Taks(thread) and display them.
Sometimes I get an exception
Destination array is not long enough to copy all the items in the collection. Check array index and length.
And in detail I can read:
C:\Windows\mscorlib.pdb: Cannot find or open the PDB file.
And:
A first chance exception of type 'System.ArgumentException' occurred in mscorlib.dll
I have no Idea were to start debugging and there is no pattern over this weird exception.
UPDATE: The code for reading txt file:
public void LoadCompassLogFile(String fileName) {
//Thread.CurrentThread.Priority = ThreadPriority.Highest;
if (!fileName.Contains("Compass")) {
throw new FileLoadException("Wrong File");
}
CompassLogLoadCompleted = false;
CompassLogLoadPercent = 0;
_compassLogCollection.Clear();
int numberOfSingleLineLog = 0;
String[] lines = new string[] {};
String temp = "";
DateTime dateTime = new DateTime();
LoggingLvl loggingLvl = new LoggingLvl();
LoggingLvl.ELoggingLvl eLoggingLvl = new LoggingLvl.ELoggingLvl();
char[] delimiters = new[] {' '};
string threadId = "";
string loggingMessage = "";
int ff = 0;
// Read the File and add it to lines string
try {
lines = File.ReadAllLines(fileName);
} catch (Exception e) {
CompassLogLoadCompleted = true;
CoreServiceLogLoadCompleted = true;
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
string[] parts;
for (int j = 0; j < lines.Count(); j++) {
string dateAndTimestamp = "";
if (!CompassLogLoadCompleted) {
try {
lock (_myLock) {
parts = lines[j].Split(delimiters,
StringSplitOptions.
RemoveEmptyEntries);
}
numberOfSingleLineLog++;
foreach (string t in parts) {
switch (ff) {
case 0:
dateAndTimestamp = t;
break;
case 1:
dateAndTimestamp += " " + t.Replace(",", ".");
dateTime = DateTime.Parse(dateAndTimestamp);
dateAndTimestamp = "";
break;
case 2:
eLoggingLvl = loggingLvl.ParseLoggingLvl(t);
break;
case 3:
threadId = t;
break;
default:
temp += t;
break;
}
ff++;
}
loggingMessage = temp;
temp = "";
ff = 0;
loggingLvl = new LoggingLvl(eLoggingLvl);
CompassLogData cLD = new CompassLogData(
numberOfSingleLineLog,
dateTime,
loggingLvl, threadId,
loggingMessage);
_compassLogCollection.Add(cLD);
//loggingMessage = "";
} catch (Exception ex) {
Console.Out.WriteLine("Shit Happens");
Console.Out.WriteLine(ex.StackTrace);
}
CompassLogLoadPercent = ((double) j
/lines.Count())*100;
}
}
CompassLogLoadCompleted = true;
Console.Out.WriteLine("Compass LOADING DONE");
Console.Out.WriteLine("numberOfSingleLineLog: " +
numberOfSingleLineLog);
Console.Out.WriteLine("");
}
I think the lenght of an array is max 2GB in .net so depending on what type you are putting in it you need to divide (2^31)/8 for a long[] and for a byte i think its (2^31)/4 so thats around 500 MB. Are your files larger than that?
On your second problem that it cannot find th PDB go to Tools --> Options --> Debugging --> Symbols and select Microsoft Symbol Servers this can fix the problem.
If you have enough information this can fix your last problem also...