how to showing what key is being pressed [duplicate] - javascript

This question already has answers here:
How to find out what character key is pressed?
(10 answers)
Closed 7 years ago.
so I need to show what key is being pressed in my web app , I want to put it in html 5 canvas.
when I'm pressing Q , it will show the Q button.
Here my code(i'm using javascript):
window.addEventListener("keypress",onKeyPress);
function onKeyPress(e)
{
console.log(e.keyCode);
var str = String.fromCharCode(e.keyCode);
console.log(str+":"+e.keyCode);
var tune = new Audio();
if (e.keyCode == 113)
{
tune = new Audio("Assets/Tune/C.mp3");
tune.play();
}
}
can anyone tell me what function do I need to show the key ?
If there's already solution, please give me the link, I've tried to search before but can't find anything.
Thanks

You have a problem...
The key code changes in different operation systems.
Here you get a table with some key codes:
http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

You can show each key pressed with something like this I guess:
var str = String.fromCharCode(e.keyCode);
var c = document.getElementById("Canvas");
var ctx = c.getContext("2d");
ctx.font = "30px Arial";
ctx.fillText(str,10,50);

You're almost there.
I have made a slight tweak to your javascript below:
window.addEventListener("keypress",onKeyPress);
function onKeyPress(e) {
var keyPressed = e.which || e.keyCode;
console.log(keyPressed);
var str = String.fromCharCode(keyPressed);
console.log(str+":"+keyPressed);
var tune = new Audio();
if (e.keyCode == 113)
{
tune = new Audio("Assets/Tune/C.mp3");
tune.play();
}
}

Related

How to remap keyboard within the same textarea

Currently i am doing a project with remapping characters to words by detecting the keyup function. Unfortunately, i have only been able to retrieve the first character and remap to the word i want. In my project, i need to directly retrieve all of my keyboard input and directly convert it to the word that i want within the same textarea. For example when i type in the textarea, it will convert to "are" directly. I don't know why it stopped retrieving the second character and remapping not function. Below is my code, hope someone can tell me my error. Thank you.
<textarea class="width-100" id="translated-text" onkeyup="myFunctionkey(event);" rows="10"></textarea>
<script>
function myFunctionkey(e) {
conversion();
}
function conversion(){
var x = document.getElementById('translated-text');
if(x.value == 'a'){
x.value='yes';
}
if(x.value == 'q'){
x.value = 'are';
}
}
</script>
From what I understand, you only want to grab the input and replace a key stroke with a complete word.
Maybe this will do. I've changed onkeyup to onkeypress because this is more reliable from what I remember.
<textarea id="translated-text" cols="50" rows="10" onkeypress="replaceInputChar(event);"></textarea>
<script type="text/javascript">
//create replacement map
var map = {
"a": "and",
"b": "bold",
"c": "change"
};
function replaceInputChar(e)
{
var ctl = document.getElementById("translated-text"); //control
var char = String.fromCharCode(e.keyCode); //typed char
if (char in map) //check if letter is defined in map
{
//insert replacement instead of letter
if("selectionStart" in ctl)
{
//in modern browsers we can easily mimic default behavior at cursor position
var pos = ctl.selectionStart;
ctl.value = ctl.value.substr(0, pos) + map[char] + ctl.value.substr(ctl.selectionEnd);
ctl.selectionStart = pos + map[char].length;
ctl.selectionEnd = ctl.selectionStart;
}
else
ctl.value += map[char];
if ("preventDefault" in e) //modern browser event cancelling
e.preventDefault();
else
{
//old browser event cancelling
e.returnValue = false; //IE8
return false;
}
}
}
</script>
You should use comparison operator '==' instead of assignment operator '=' while remapping the value, like this:
x.value=='a'
Edit:
You should check the updated code for your problem here:
https://jsfiddle.net/o4coLr5t/1/
Now, the characters you choose to remap in javascript will display the string, that you map the character to. Otherwise it will display nothing on pressing keys. So, try and add all the character keycodes to the javascript code. Hope that helps.

"parsing" a text document to specific javascript format?

Edit - I think parsing it the wrong word to use, I'm actually looking to format that text file into the format I provided.
I'm working on a project and I've ran into a slight problem. I need help with mass editing a text file into a certain format. I don't really know how to do this. For example, here is the text file: http://frankerfacez.com/users.txt
That has the list of users and emotes (users without periods, emotes with). I would need that to be changed into the format of
//user
"emote":["cdn.frankerfacez.com/channel/ user / emote.png"],
For reference, this is what I need the format to be: https://dl.dropboxusercontent.com/u/23313911/CustomEmotes.js
I really don't know how easy this will be or if it is even possible, but any help would be greatly appreciated!
lines = txtFile.responseText.split("\n");
var user = null;
var emote = null;
var o = {};
for (i in lines) {
var line = lines[i];
if (line.charAt(0) != ".")
user = line;
else {
try{
emote = line.substring(1, line.legth);
var a = new Array();
eval("var cnd = new String('cdn.frankerfacez.com/channel/'+user+'/'+emote+'.png');");
a.push(cnd.toString());
eval("o."+emote+" = a;");
}catch(e){
console.error(emote + " - " + user);
console.error(e);
}
}
}
console.log(o);

Better way to create text based game [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Right, i was uncertain if I should post this as it is a little vague but I really would like some help with this so I will try explain as best as possible.
The Idea:
To create a text based game using Javascript/jQuery, the game will be that of one where a story is being told and you get to pick the options.
My idea was to use a textarea to allow input from the user (select a option) and output text (from the story).
How far have I got?
Well this is what I have created so far.
JavaScript/jQuery:
var current, text, location, option1, option2;
location = ''; // house, car, moon
current = 0;
gameOver = false;
pick = false;
jQuery("textarea").keypress(function (e) {
if (e.which == 13) {
var content = this.value;
var lastLine = content.substr(content.lastIndexOf("\n") + 1);
// Story
if (current == 0 && pick == false) {
option1 = 'Look around';
option2 = 'Check you have arms (Check arms)';
text = 'You open your eyes \n\nOptions: \n' + option1 + '\n' + option2;
pick = true;
} else if (current == 0 && lastLine == 'Check arms' && pick == true) {
text = 'You check your arms, they seem fine';
pick = false;
} else if (current == 0 && lastLine == 'Look around' && pick == true || current == 2 && lastLine == 'Get Out') {
option1 = 'Walk to a nearby house';
option2 = 'Get in a rocket that is next to you (Get in rocket)';
text = 'You do a 360 spin, you see you have limited options \n\nOptions: \n' + option1 + '\n' + option2;
pick = false;
if (current == 2 && lastLine == 'Get Out') {
current = 1;
} else {
current++;
}
}
//House Story
else if (current == 1 && lastLine == 'Walk to house' && pick == false) {
option1 = 'Knock on the front door';
option2 = 'Jump through the front window';
text = 'You walk to the house and see there are no lights on, the building is old and appears to be burnt out\n\nOptions: \n ' + option1 + '\n ' + option2;
pick = false;
current++;
}
// Rocket story
else if (current == 1 && lastLine == 'Get in rocket' && pick == false) {
option1 = 'Get out of the rocket(Get out)';
option2 = 'Hit the biggest button you can find(Hit Button)';
text = 'You hop into the rocket, there are a lot of buttons infront of you\n\nOptions: \n ' + option1 + '\n ' + option2;
pick = false;
current++;
}
$('textarea ').val($('textarea ').val() + '\n\n ' + text + '\n ');
}
});
It works (kinda) but it is getting complicated to code like this. To me its very messy and I have tried to re-write it but I cannot find a way to make this neat/ easier to code.
Have a look at the demo:
Please do take a look at the demo if you wish to try and help me as you will get a good idea what I am trying to achieve.
Demo walk-through:
DEMO HERE
In the textarea click enter to start
Type one of the options to progress in the game (Options: Check arms or Look around)
Type one of the options to progress in the game (Options: Walk to a nearby house or Get in rocket)
End of demo
Note: After typing a option click enter to continue. At the moment all options must be typed exactly as seen (If option has brackets you type that instead)
This is a short demo but you should get the point. I have searched around and cant find/think of a suitable method to code this game.
Get to the point, what's the question?
My questions is: What is a suitable method to code this game?
Suitable: Easy to maintain/read + add new story "parts" etc.
I would go with some kind of strategy pattern. Create i.e. a Game constructor
var Game = new function(strategy) {
this.strategy = strategy;
}
Game.prototyp.playScene = function() {
return this.strategy();
}
Then you can create scenes where you would place your logic
var sceneOne = function() {
console.log('First scene logic here');
}
var sceneTwo = function() {
console.log('Second scene logic here');
}
and finally you can call these logics as follows:
var game;
if(e.which == 13) {
if(condition1) {
game = new Game(sceneOne);
} else {
game = new Game(sceneTwo);
}
game.playScene();
}
fiddle
The biggest issue I see here is that your code is going to grow and grow as your game/story expands. You're actually writing the logic of your game in the code itself.
As an alternative I would suggest splitting out your logic into steps and logic. For example:
var allTiles =
[
{location: 'Forest', description: 'Deep, dark and scary'},
{location: 'Castle', description: 'High, made from stone and very dramatic'},
];
var currentState =
{
equipment: ['Sword', 'Bow', '3 gold coins'];
currentLocationIndex: 0
};
These may of course be in different files so you can add locations to your world.
Next you need your core logic class, this will look a lot like the one you've already got:
jQuery("textarea").keypress(function (e) {
var currentLocation = allTiles[currentState.currentLocationIndex];
printDescription(currentLocation.Description);
// process commands... into pseudo code territory
if(userDoesAction1){
currentLocation.doAction1();
}
}
I've not gone into massive detail here - it will depend very much on the structure of your game. Personally I like the idea of creating an array functions in your location which are things you can do at your location... actually, JS is a very nice language to do this sort of game!
You can use my jQuery terminal. Then you can write core of the game that act on data in JSON object. If you write something like this you will be able to change the data (update or replace) without need to change the code, it's called data driven programming (Eric Raymond write nice chapter in his book about it)
When making games i think that an Object Oriented approach is the best to keep things separated and easy to code and find:
For example you could separate the different rooms in your game in different function structures.
var parentFunction = function(){
var protectedValue = ‘variable’;
var childFunction = function(){
alert(protectedValue);
}
childFunction();
}
var object = new parentFunction();
You initialize the function every time you move to the related ambient, and put the possible actions that the player can take in child-functions.
But i guess the answer would be too big here: you should spend some time before starting to make a scheme of the logic that your game will follow and how you want to separate things (and how they relate to each other).

Jquery Negative Values

i'm having a problem with a bit of jquery right now. I've got a navigation code (EG pressing the up arrow and down arrow alters a $_GET variable in the URL). It's working fine in the positive numbers but the moment I try to go past -1 it unsets the variable and causes the page to reset.
Below is the Jquery Function in question.
function arrowbuttons()
{
$(document).keydown(function(e){
var full_url = document.URL; // Get current url
var split = location.search.replace('?, &');
var y = split[7];
var x = split[3];
var down = +split[7]-1;
var up = +split[7]+1;
var left = +split[3]+1;
var right = +split[3]-1;
if (e.keyCode == 37) {
window.location = 'index.php?X='+left+'&Y='+y+'&Z=0';
return false;
}
if(e.keyCode == 38) {
window.location = 'index.php?X='+x+'&Y='+up+'&Z=0';
return false;
}
if(e.keyCode == 39) {
window.location = 'index.php?X='+right+'&Y='+y+'&Z=0';
return false;}
if(e.keyCode == 40) {
window.location = 'index.php?X='+x+'&Y='+down+'&Z=0';
return false;}
});
}
If either of the effected URL variables (X or Y) are attempting to go below -1, like i said before, everything is redirected back to the start (X=0&Y=0&Z=0) by my php redirect code. This is strictly a Jquery issue, as the links that i've hardcoded into my site i'm fully capable of going as low as -16. Furthermore, I've noticed that I cannot go above +10 on any of the directions; when i go above +10 i resets me to (X=2 or Y=2 depending on which variable has been affected)
You've got a couple of issues happening here:
1st: replace takes 2 parameters. It looks for the first string and replaces it with the 2nd. You're call won't replace anything because it doesn't find the string "?,&" in your location.search string. So split will be X=1&Y=0&Z=0 (for example) after your replace.
2nd: you are hard coding the exact locations in the string that you are expecting the values. If any of the values are 2 digits or a negative number, it doesn't work because the values are no longer at split[7] and split[3]. Since the string is now X=-1&Y=10&Z=0 (for example)
This is a good discussion on getting query params in javascript How can I get query string values in JavaScript?,
But I generally just have php set the variables in my javascript for me.
Adding a fiddle, for you to play with: http://jsfiddle.net/bhlaird/M3Ub7/
function getParameterByName(name,location_search) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location_search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var location_search = '?X=-1&Y=10&Z=0' // replace this string with location.search
var y = getParameterByName('X',location_search);
var x = getParameterByName('Y',location_search);
var down = +y - 1;
var up = +y + 1;
var left = +x + 1;
var right = +x - 1;

How to remove $ from javascript variable? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Remove characters from a string
I have a variable p which I would like to remove the $ from. This variable will be a number such as $10.56. How can I do this? I thought it could be done using .replace('$','') but i'm not quite sure how to implement this.
Here is my javascript code:
function myFunction() {
var p = parseFloat(document.getElementById('p_input').value);
var q = parseFloat(document.getElementById('q_input').value);
if (!q){
document.getElementById('t').value = '';
}
else {
var t = q * p;
document.getElementById('t_output').value = t;
}
}
It's pretty simple:
var myString = "$15.62"
console.log(myString.replace('$', ''));
//Logs: "15.62"
Please note that this new value is not actually "saved" to myString, you'll have to assign it to a variable, yourself:
var newString = myString.replace('$', '');
Try this, assuming that the values of p_input and q_input will be the money values:
var p = parseFloat(document.getElementById('p_input').value.replace('$', ''));
var q = parseFloat(document.getElementById('q_input').value.replace('$', ''));

Categories

Resources