for (Keys k = Keys.A; k <= Keys.Z; k++)
{
if (KeyPress(k))
Text += k;
}
This code detects the key buttons I pressed in my keyboard and it will print out what key is pressed in the console. However, I pressed 'a' on the keyboard but it comes out as 'A'. How do I fix this?
This is an often encountered problem. The trouble is that XNA isn't geared towards getting textual input from a keyboard. It's geared towards getting the current state of each key on the keyboard.
While you could write custom code to check things like whether shift is held down etc, what about keyboards that aren't the one you're using (e.g. different language, different layout). What most people do is get windows to do it for you.
If you want text to appear as expected you need to basically re-create a few things and get windows to do it for you.
See Promit's post here: http://www.gamedev.net/topic/457783-xna-getting-text-from-keyboard/
Usage:
Add his code to your solution. Call EventInput.Initialize in your game'sInitialize` method and subscribe to his event:
EventInput.CharEntered += HandleCharEntered;
public void HandleCharEntered(object sender, CharacterEventArgs e)
{
var charEntered = e.Character;
// Do something with charEntered
}
Note: If you allow any character to be inputted (e.g. foreign ones with umlauts etc.) make sure your SpriteFont supports them! (If not, maybe just check your font supports it before adding it to your text string or get the spritefont to use a special 'invalid' character).
After looking at your provided code, it should be a simple modification:
[...]
for (Keys k = Keys.A; k <= Keys.Z; k++)
{
if (KeyPress(k))
{
if (keyboardState.IsKeyDown(Keys.LeftShift) || keyboardState.IsKeyDown(Keys.RightShift)) //if shift is held down
Text += k.ToString().ToUpper(); //convert the Key enum member to uppercase string
else
Text += k.ToString().ToLower(); //convert the Key enum member to lowercase string
}
}
[...]
Related
I'm trying to build a simple game of 'HangMan' using Win8 GUI. I've build the GUI with 26 buttons on screen, each represent one letter of the alphabet.
I want to connect all the buttons to the same method that checks whatever the value of the button that was pressed matches one of the letter in the selected word. I've looked at this question answers that supposed to help me in this but the one difference i think is that all the logic and methods in my game are on different class, the "Game Manager" class.
How can I subscribe multiple buttons to the same event handler and act according to what button was clicked?
Plus i didnt quit understood how, using this solution the method which i will assign all the buttons to will know which button was pressed. I hope i explaind my situation clear enough, if not i can provide parts of the code for better understanding.
It's a basic method for what you want:
static string key = "Level solution";
char[] chars = key.ToCharArray();
void check (object sender)
{
var button = sender as Button;
character = Convert.ToChar(button.Text);
int i = 0;
foreach (char c in chars)
{
//checks every character to mark them
if (c == character)
{
chars[i] = ' ';
//Makes character unusable for later use
//Anything you want now for true letters, for example showing pics or adding them to a label
}
i++;
}
//checks every character of key again, to see if player is won
int count = 0;
foreach (char c in chars) {
if (c != ' ') count++;
//Adds a number for anything expect space
}
if (count == 0)
{
MessageBox.Show("You won!");
}
}
You can paste it on top of your codes and then use just this code in any button:
check(sender);
I have a textbox which I'm trying to implement automatic formatting on for a phone number.
I would like to remove the last two characters of the textbox if the user presses the delete key and the last character of the string in the textbox is '-'.
I am attempting to do this through substring removal, but with no luck. Thanks
private void phoneNumberTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Back)
{
if (phoneNumberTextBox.Text.Length != 0)
{
if (Convert.ToChar(phoneNumberTextBox.Text.Substring(phoneNumberTextBox.Text.Length - 1)) == '-')
{
phoneNumberTextBox.Text.Substring(0, phoneNumberTextBox.Text.Length - 2);
}
}
}
Substring() returns a new string instance and leaves the current instance unchanged. Because of this, your call just creates a new temporary string but because you don't do anything with it, it gets thrown away immediately.
To make the change stick, you need to assign the result of Substring() back to the textbox, like so:
phoneNumberTextBox.Text = phoneNumberTextBox.Text.Substring(0,
phoneNumberTextBox.Text.Length - 2);
Make sure you check the length of the string first to avoid problems with handling short string (less than 2 characters).
Also, if you want to limit the number of characters in the textbox, just use the MaxLength property instead. You don't have to deal with handling length and typing that way.
For the 2 char removal could do:
phoneNumberTextBox.Text = phoneNumberTextBox.Text.Remove(phoneNumberTextBox.Text.Length - 2, 2);
For the key pressing part might be that you have to enable the KeyPreview on you form.
Wow sry for the editing doing mistakes all over.
I need to know how you can stop a tablet or mobile user from entering emojis in any input type="text" field as users abe able to submit my form but it causes errors in my middle tier as they come through as squares and also writes to my DB as squares.
Cant seem to find a solution on Google so thought id ask on here.
Is there an HTML attribute i can use of something?
It may be a better idea to make your database compatible by changing encoding.
That being said, you could loop over all characters in the textfield and make sure that their ordinal is between 32 and 255 inclusive. This would make it so that you only allow printable ASCII characters, more than enough for any English text.
Something like this: (untested, typed in textarea)
function stripNonAscii(input) {
let output = '';
for (var i = 0; i < input.length; i++) {
let c = input.charCodeAt(i);
if(c >= 32 && c <= 255) {
output += input.substring(i, 1);
}
}
return output;
}
I am currently making a text based game. I am drawing a map using ASCII. I want to place an "#" sign in the room where the player is located. the four square boxes are the rooms. Here is the code:
string map = #"
+--------+
| |
|| ||
| |
+---||---+
||
+-||-+
|| ||
+-||-+
||
+-||-+
|| ||
+-||-+
||
+-||-+
|| ||
+- -+";
//this doesn't work lol
map = map.Replace("||","#");
It is for an assignment.
To answer your direct question, assuming that there is a part of your map string that has two spaces after two vertical bars and you want to replace the second space with an # symbol, you could do this:
map.Replace("|| ", "|| #");
Which of course would replace every instance of the search string, scattering # symbols throughout your map, and I strongly doubt that you want this to happen.
In fact I don't think it's a good idea to change the map string at all. Instead you would be better served by keeping the map data separate from the player position data and handling the output differently.
For example, if you are allowed to use the Console object's positioning commands you can do something like this:
int playerX;
int playerY;
string map;
public void Draw()
{
Console.Clear();
Console.Write(map);
// save cursor position
int l = Console.CursorLeft;
int t = Console.CursorTop;
// display player marker
Console.SetCursorPosition(playerX, playerY);
Console.Write("#");
// restore cursor position
Console.SetCursorPosition(l, t);
}
You can use cursor positioning to do all sorts of fun things, just like we used to in the good old days of ANSI art. Ah, nostalgia.
If you can't use - or for some reason can't rely on - cursor positioning you will need to get a bit more creative. One method is to break the map down into lines and figure out which one needs to have the player mark added right before you do the output:
public void Draw()
{
string[] lines = map.Replace("\r", "").Split('\n');
for(int y = 0; y < lines.Length; y++)
{
string curr = lines[y];
if (y == playerY)
curr = curr.Substring(0, playerX) + "#" + curr.Substring(playerX + 1);
Console.WriteLine(curr);
}
}
Of course this will blow up as soon as the player movement goes outside of the area covered by the map string, or hits the right-most character of the line.
Another option would be to create an array of map cells with information in each cell about what is there. The map string is used as input for generating the map array, which is used for all operations after that. The draw loop for that would then test against the player position to determine whether it will draw the player's marker or whatever character the map cell is represented by. You can also use this array for testing whether a move is valid (empty map cell), adding things like cell content (treasure!), etc.
The code for which is well outside the scope of this answer.
I have been given the task of deserializing some data. The data has all been munged into a string which is in the following format:
InternalNameA8ValueDisplay NameA¬InternalNameB8ValueDisplay NameB¬ etc etc.
(ie, it has an internal name, '8', the value, the display name, followed by '¬' **). for example, you'd have FirstName8JoeFirst Name¬
I have no control over how this data is serialized, its legacy stuff.
I've thought of doing a bunch of splits on the string, or breaking it up into a char array and splitting down the text that way. But this just seems horrible. This way there is too much that could go wrong (e.g, if the value of a phone number (for example), could begin with '8'.
What I want to know is what peoples' approaches to this would be? Is there anything more clever i can do to break the data down
note: '¬' isn't actually the character, it looks more like an arrow pointing left. but I'm away from my machine at the moment. Doh!
Thanks.
Instead of using splits, I would recommend using a simple state machine. Walk over each characters until you hit a delimiter, then you know you're on the next field. That takes care of issues like an "8" in a phone number.
NOTE - untested code ahead.
var fieldValues = new string[3];
var currentField = 0;
var line = "InternalNameA8ValueDisplay NameA¬InternalNameB8ValueDisplay NameB¬";
foreach (var c in line)
{
if (c == '8' && currentField == 0)
{
currentField++; continue;
}
if (c == '¬')
{
currentField++; continue;
}
fieldValues[currentField] += c;
}
Dealing with wonky formats - always a good time!
Good luck,
Erick