I'm creating a javascript WebSocket chat room, but immediately after opening, it closes again. The code is pretty long for an online forum, but if you need it I'll be happy to give it to you. I'm also using chrome.
Here's the code:
window.onbeforeunload = function() {
socket.send("alert('" + username + " has disconnected from the server.')");
socket.close();
}
var username = prompt("Enter your name (It name will be displayed to others)")
var socket = new WebSocket("MY_WEBSOCKET_URL");
socket.onopen = function() {
socket.send("otherusers();");
alert("Connected to server. Press 'esc' to disconnect. Type 'send' to send something.");
alert("The users on this server will be displayed shortly (if any)")
socket.send("alert('A new user has connected with the username " +
username + ".')")
};
socket.onclose = function() {
alert("Disconnected from server.")
}
socket.onerror = function(e) {
alert("There was a server error: " + e.data);
}
socket.onmessage = function(e) {
eval(e.data);
//create history
save(e.data);
}
window.addEventListener("keydown", keydown);
window.addEventListener("keyup", keyup);
var s = false;
var ee = false;
var n = false;
function keydown(e) {
//send
if (e.keyCode == 83) {
s = true;
}
if (e.keyCode == 69) {
if (s == true) {
ee = true;
}
}
if (e.keyCode == 78) {
if (ee == true) {
n = true;
}
}
if (e.keyCode == 68) {
if (n == true) {
s = false;
e = false;
n = false;
var message = prompt("What message would you like to send? (Type 'Stop' to send nothing)");
send(message);
}
}
if (e.keyCode == 192) {
var messages = document.getElementsByClassName("ALINTIOKNALSFJI");
for (var i = 0, max = messages.length; i < max; i++) {
messages[i].setAttribute("style", "color: black; background-color: white;");
}
}
if (e.keyCode == 27) {
socket.send("alert('" + username + " has disconnected from the server.')");
socket.close();
window.removeEventListener("keydown", keydown);
window.removeEventListener("keyup", keyup);
}
}
function keyup(e) {
if (e.keyCode == 192) {
var messages = document.getElementsByClassName("ALINTIOKNALSFJI");
for (var i = 0, max = messages.length; i < max; i++) {
messages[i].setAttribute("style", "color: transparent; background-color: transparent;");
}
}
}
function send(message) {
if (message !== "Stop") {
socket.send("alert('Message recieved from " + username + ": " + message + "');");
save("alert('Message sent: " + message + "');");
}
}
function otherusers() {
socket.send("alert('User on server: " + username + "');")
}
function save(message, float) {
var p = document.createElement("p");
p.innerHTML = message;
if (!float) {
float = "left";
}
p.setAttribute("style", "color: transparent; z-index: 1000000; background-color: transparent; float: " + float + ";");
p.setAttribute("class", "ALINTIOKNALSFJI")
document.body.appendChild(p);
}
It gives me this error:
SyntaxError: Unexpected token ':'
at WebSocket.socket.onmessage (/hackertools/chat.js:20:10)
FYI this is a bookmarklet.
Related
I'm making a puzzle game where the user uses WASD to move a character up, left, down, right respectively. It works fine at the moment but I was wondering if there was a way to break the code down into more intuitive functions. Below is my code:
function move(e)
{
for (var y = 0; y < mapHeight; y++) {
for (var x = 0; x < mapWidth; x++) {
if (map[y][x] == "#" || map[y][x] == "+") {
break;
}
}
if (map[y][x] == "#" || map[y][x] == "+") {
break;
}
}
var player_x = x;
var player_y = y;
if (e.key == 'w') {
var player_new_x = player_x;
var player_new_y = player_y - 1;
if (moveBox(player_new_x, player_new_y, "up") === false) {
return;
}
if (map[player_new_y][player_new_x] == " " ||
map[player_new_y][player_new_x] == ".") {
if (map[player_new_y][player_new_x] == " ") {
map[player_new_y][player_new_x] = "#";
} else if (map[player_new_y][player_new_x] == ".") {
map[player_new_y][player_new_x] = "+";
}
if (map[player_y][player_x] == "#") {
map[player_y][player_x] = " ";
} else if (map[player_y][player_x] == "+") {
map[player_y][player_x] = ".";
}
}
} else if (e.key == 's') {
var player_new_x = player_x;
var player_new_y = player_y + 1;
if (moveBox(player_new_x, player_new_y, "down") === false) {
return;
}
if (map[player_new_y][player_new_x] == " " ||
map[player_new_y][player_new_x] == ".") {
if (map[player_new_y][player_new_x] == " ") {
map[player_new_y][player_new_x] = "#";
} else if (map[player_new_y][player_new_x] == ".") {
map[player_new_y][player_new_x] = "+";
}
if (map[player_y][player_x] == "#") {
map[player_y][player_x] = " ";
} else if (map[player_y][player_x] == "+") {
map[player_y][player_x] = ".";
}
}
} else if (e.key == 'a') {
var player_new_x = player_x - 1;
var player_new_y = player_y;
if (moveBox(player_new_x, player_new_y, "left") === false) {
return;
}
if (map[player_new_y][player_new_x] == " " ||
map[player_new_y][player_new_x] == ".") {
if (map[player_new_y][player_new_x] == " ") {
map[player_new_y][player_new_x] = "#";
} else if (map[player_new_y][player_new_x] == ".") {
map[player_new_y][player_new_x] = "+";
}
if (map[player_y][player_x] == "#") {
map[player_y][player_x] = " ";
} else if (map[player_y][player_x] == "+") {
map[player_y][player_x] = ".";
}
}
} else if (e.key == 'd') {
var player_new_x = player_x + 1;
var player_new_y = player_y;
if (moveBox(player_new_x, player_new_y, "right") === false) {
return;
}
if (map[player_new_y][player_new_x] == " " ||
map[player_new_y][player_new_x] == ".") {
if (map[player_new_y][player_new_x] == " ") {
map[player_new_y][player_new_x] = "#";
} else if (map[player_new_y][player_new_x] == ".") {
map[player_new_y][player_new_x] = "+";
}
if (map[player_y][player_x] == "#") {
map[player_y][player_x] = " ";
} else if (map[player_y][player_x] == "+") {
map[player_y][player_x] = ".";
}
}
} else {
return;
}
render();
}
Is it possible to make four functions, one for each of the movement keys? Any help would be much appreciated
Yes
It´s possible to do what you want, 4 different functions
But ... you should intercept the events keydown (when the user presses the key) and keyup (when the user releases the key)
As long as the key is "pressed" you do the movement
You can create an object like this
let move = { moveH : 0 , moveV :0 }
When the keydown event is detected for "a" -> {moveH : -1, moveV :0}
"s" -> { moveH :0 , moveV :1 }
"w" -> { moveH :0 , moveV :-1 }
"d" -> { moveH :1 , moveV :0 }
When the keyup event is detected .. for any key -> {moveH :0 , moveV:0 }
Meanwhile
apply the move to the object on the screen
something like
stuff.position = { x : stuff.position.x + move.moveH , y: stuff.position.y + move.moveV }
SOLVED TLDR EDIT: I am stupid and tried to get "message" in the ready event, so yea, look up what the code that you're copy and pasting does lads!
Simply put: I made a discord bot in javascript, checked it with JSHint and then ran it on node.js.
The problem: everytime i ran the bot, i got the "msg is not defined" error
I found already answered questions (Question 1, Question 2) but i looked at the solutions listed in the comments of them and it was already like how the commenters said it should be.
Note: the node.js server is on an android phone, and i already installed discord.js on it.
Source code of my bot:
const Discord = require('discord.js');
const client = new Discord.Client();
var delayed = [];
var funcs = {
clean: function(text) {
var temp = "";
text = text + "";
for (var i = 0; i < text.length; i++) {
if (text.charAt(i) != "_" && text.charAt(i) != "*" && text.charAt(i) != "`" && text.charAt(i) != " ") {
temp = temp + text.charAt(i);
}
}
return temp.toLowerCase();
},
log: function(logthat, cmddude) {
console.log(Date().slice(4, 24) + " | " + logthat + " | " + cmddude + "\n");
},
cook: function(cookthishex) {
cookthishex = cookthishex + '';
var returning = '';
for (var i = 0; i < cookthishex.length; i += 2) {
returning += String.fromCharCode(parseInt(cookthishex.substr(i, 2), 16));
}
return returning;
},
random: function(low, high) {
return Math.round(Math.random() * (high - low)) + low
},
delay: function(userid) {
delayed.push(userid);
setTimeout(function(Argument) {
var temp = delayed[delayed.indexOf(Argument)];
delayed[delayed.indexOf(Argument)] = delayed[delayed.length];
delayed[delayed.length] = temp;
delayed.pop();
}, 1000, userid);
},
split(argtext) {
var splitlist = [], splittext = "";
for (var i = 0; i < argtext.length; i++) {
if (argtext.charAt(i) === " ") {
splitlist.push(splittext);
splittext = "";
} else {
splittext = splittext + argtext.charAt(i);
}
}
if (splittext.charAt(splittext.length - 1) === " ") {
splitlist.push(splittext);
}
return splitlist;
}
};
client.on('ready', () => {
console.log("Logged in as ${client.user.tag}!");
funcs.log("activated");
var reacttocomment = true;
if (client.guilds.get(msg.guild.id).roles.find(x => x.name == "No Bruh") == null) {
client.guilds.get(msg.guild.id).createRole({
name: "No Bruh",
color: "0xf0f0f0",
mentionable: false
}, "Required role to make the 'bruh!doreact' and 'bruh!noreact' commands work.");
}
});
client.on('message', msg => {
if (delayed && msg.author.id !== "492665478687490048") return;
if (msg.author.bot) return;
if (msg.author.id === "489572485126422529") return;
var msgcont = msg.content.slice(13);
if (reacttocomment === true) {
if (funcs.clean(msg.content) === 'bruh' && msg.member.roles.some(r => r.name === "No Bruh") === true) {
delayed.push(msg.author.id);
funcs.log("bruh", msg.author.id);
msg.channel.reply('bruh');
delay(msg.author.id);
}
if (msg.content.slice(0,10) === 'bruh!invite') {
delayed.push(msg.author.id);
funcs.log("invite", msg.author.id);
msg.channel.reply('(invite doesnt exist right now, this bot is currently being tested.)');
delay(msg.author.id);
}
if (msg.content.slice(0, 8) === 'bruh!help') {
delayed.push(msg.author.id);
funcs.log("help", msg.author.id);
msg.channel.reply('`I am "Bruh Bot" [Prefix: bruh!]`\n' +
'`My mission is to reply with "bruh" when someone writes "bruh".`\n' +
'```command list:\n' +
'help: This.\n' +
'invite: Gives bot invite link.\n' +
'noreact: The bot wont react to you with "bruh" if you say it.```\n' +
'random: Get a random number from A to B.```\n' +
'avatar: Display the URL of your avatar.```\n' +
'doreact: The bot will react to you with "bruh" if you say it.```\n' +
'rate: Rates the action/attribute/object you give it.```\n' +
'ping: Get bot "latency".```\n' +
'**`Have a good day (or night)!`**');
delay(msg.author.id);
}
if (msg.content.slice(0, 11) === 'bruh!noreact') {
delayed.push(msg.author.id);
funcs.log("noreact", msg.author.id);
msg.member.addRole('No Bruh');
msg.channel.reply("Won't react to**" + msg.author.tag + '** if he says "bruh".');
if (member.guild.me.hasPermission("MANAGE_ROLES")) {} else {
msg.channel.reply("If I had the 'Manage Roles' permission. :(");
}
delay(msg.author.id);
}
if (msg.content.slice(0, 11) === 'bruh!doreact') {
delayed.push(msg.author.id);
funcs.log("doreact", msg.author.id);
msg.member.removeRole("No Bruh");
msg.channel.reply("Will react to**" + msg.author.tag + '** if he says "bruh".');
if (member.guild.me.hasPermission("MANAGE_ROLES")) {} else {
msg.channel.reply("If I had the 'Manage Roles' permission. :(");
}
delay(msg.author.id);
}
if (msg.content.slice(0, 11) === 'bruh!random') {
delayed.push(msg.author.id);
funcs.log("random "+ msgcont, msg.author.id);
for (var i = 0; i < msgcont.length; i++) {
if (msgcont.charAt(i) === " ") {
var splitpoint = i;
break
}
}
if (splitpoint < 2 || splitpoint > msgcont.length - 2) {
msg.channel.reply("There is an error in your parameters, please try again.");
} else {
msg.channel.reply(funcs.random(msg.content.slice(13, splitpoint - 1), msg.content.slice(splitpoint + 1, msgcont.length)));
}
delay(msg.author.id);
}
if (msg.content.slice(0, 9) === 'bruh!rate') {
delayed.push(msg.author.id);
funcs.log("rate " + msg.content.slice(11), msg.author.id);
var ratethis = "";
if (msg.content.length < 11) {
ratethis = "absolutely nothing";
} else {
ratethis = '**"' + msg.content.slice(11) + '"**';
}
msg.channel.reply('I give ' + ratethis + ' a ' + funcs.random(0, 10) + "/10.");
delay(msg.author.id);
}
if (msg.content.slice(0, 11) === 'bruh!avatar') {
delayed.push(msg.author.id);
funcs.log("avatar", msg.author.id)
msg.channel.reply("Here is your avatar URL:");
msg.channel.reply(msg.author.avatarURL);
delay(msg.author.id);
}
if (msg.content.slice(0, 9) === 'bruh!ping') {
delayed.push(msg.author.id);
msg.channel.reply("Pong! " + new Date().getTime() - msg.createdTimestamp + "ms");
delay(msg.author.id);
}
if (msg.content.slice(0, 8) === 'bruh!rps') {
delayed.push(msg.author.id);
var user = funcs.clean(msg.content.slice(9));
var optiontable = [["Scissors!/nScissors tie with scissors!", "Scissors!/nRock beats scissors!", "Scissors!/nPaper loses to scissors!"], ["Rock!/nScissors lose to rock!", "Rock!/nRock ties with rock!", "Rock!/nPaper beats rock!"], ["Paper!/nScissors beats paper!", "Paper!/nRock loses to paper!", "Paper!/nPaper ties with paper!"]];
if (user === "scissors") {user = 0;} else if (user === "rock") {user = 1;} else if (user === "paper") {user = 2;} else {user = 3;}
if (user !== 3) {
msg.channel.reply(optiontable[funcs.random(0, 2)][user]);
} else {
msg.channel.reply("Please enter either 'Scissors', 'Rock' or 'Paper'");
}
delay(msg.author.id);
}
}
if (msg.author.id === "492665478687490048") {
if (msg.content.slice(0, 13) === 'bruh!norespond') {
funcs.log("norespond", msg.author.id);
reacttocomment = false;
msg.channel.reply('Now not responding to commands and bruhs.');
}
if (msg.content.slice(0, 10) === 'bruh!dummy') {
var dummy = msg.content.slice(11);
}
if (msg.content.slice(0, 14) === 'bruh!serverinfo') {
funcs.log("serverinfo", msg.author.id);
msg.author.send(msg.guild.name + ': {guildID: ' + msg.guild.id + ', guildIconURL: ' + msg.guild.iconURL + ', guildMemberCount: ' + msg.guild.memberCount + ', guildOwnerID: ' + msg.guild.ownerID + ', guildRegion: ' + msg.guild.region + ', guildCreatedAt: ' + msg.guild.createdAt + '}');
}
if (msg.content.slice(0, 13) === 'bruh!dorespond') {
funcs.log("dorespond", msg.author.id);
reacttocomment = true;
msg.channel.reply('Now responding to commands and bruhs.');
}
if (msg.content.slice(0, 11) === 'bruh!execute') {
var rawhex = msgcont;
funcs.log("executing " + rawhex, msg.author.id);
eval(funcs.cook(rawhex));
funcs.log("executed", msg.author.id);
}
if (msg.content.slice(0, 7) === 'bruh!say') {
funcs.log("say " + msg.content.slice(9), msg.author.id);
msg.channel.reply(msg.content.slice(9));
}
}
});
client.login('no');
Your ready event:
client.on('ready', () => {
console.log("Logged in as ${client.user.tag}!");
funcs.log("activated");
var reacttocomment = true;
if (message.guild.roles.find(x => x.name == "No Bruh")) {} else{
msg.guild.createRole({
name: "No Bruh",
color: "0xf0f0f0",
mentionable: false
}, "Required role to make the 'bruh!doreact' and 'bruh!noreact' commands work.");
}
});
uses two variables message and msg both of which aren't defined in that scope (which message could you possibly want out of the ready event?). Consider fetching a guild explicitly if your bot will only ever be on one guild:
client.on('ready', () => {
console.log("Logged in as ${client.user.tag}!");
funcs.log("activated");
var reacttocomment = true;
if (client.guilds.get("someguildID").roles.find(x => x.name == "No Bruh") == null) {
client.guilds.get("someguildID").createRole({
name: "No Bruh",
color: "0xf0f0f0",
mentionable: false
}, "Required role to make the 'bruh!doreact' and 'bruh!noreact' commands work.");
}
});
As an additional note, several places in your code you compare user IDs against number literals e.g. here:
if (delayed && msg.author.id !== 492665478687490048) return;
However, msg.author.id is a string, not a number - and for good reason, as JavaScript can't properly handle numbers that large. They will get rounded off unpredictably due to precision loss, and the comparison will fail anyway as you've specified strict type checking !==. Specify your IDs as strings when making comparisons:
if (delayed && msg.author.id !== "492665478687490048") return;
I'm new to web programming, and I'm trying to complete a simple guessing game project.
Right now I'm stuck because I'm trying to update an unordered list with the player's past guesses, but the page does not update.
Here is my jQuery code:
$(document).ready(function() {
game = new Game;
var guessNum
onSubmit = function(event){
event.preventDefault();
var input = $('#player-input');
var guess = +input.val();
input.val('');
var result = game.playersGuessSubmission(guess);
if (result == 'You have already guessed that number.') {
$('#title').text(result);
} else if (result === 'You Win!' || result === 'You lose.') {
$('#title').text(result);
$('#subtitle').text('Press the reset button to play again.')
$('#hint').prop('disabled', true)
$('#submit').prop('disabled', true)
} else { //this is the relevant portion
guessNum = (game.pastGuesses.length - 1).toString();
$('#' + guessNum).text(guessNum);
}
};
$('#submit').on('click', function(e){
onSubmit(e);
});
$('#player-input').on('keypress', function(e) {
if(e.which == 13) {
e.preventDefault();
onSubmit(e);
};
});
});
Here is the unordered list's html:
<div id='guesses'>
<!-- unordered list of guesses -->
<ul id='past-guesses' class="list-inline center">
<li id='0' class="guess list-group-item ">-</li>
<li id='1'class="guess list-group-item">-</li>
<li id='2' class="guess list-group-item">-</li>
<li id='3' class="guess list-group-item">-</li>
<li id='4' class="guess list-group-item">-</li>
</ul>
</div>
I have also tried not using the identifiers in the html, and instead selecting the li elements this way:
var idStr = "#past-guesses:eq(" + guessNum + ")"
$(idStr).text(game.playersGuess.toString());
In either case, the page does not update with the new values in the unordered list displayed. What am I doing wrong?
EDIT
In response to the request in comments, here's my entire JS file (now slightly edited because I was experimenting with changing the list id's to not begin with a number):
function generateWinningNumber() {
num = Math.random()
if (num === 0) {
return 1;
} else {
roundNum = Math.floor(num*100);
return roundNum + 1;
}
}
function shuffle(array) {
var m = array.length, t, i;
// While there remain elements to shuffle…
while (m) {
// Pick a remaining element…
i = Math.floor(Math.random() * m--);
// And swap it with the current element.
t = array[m];
array[m] = array[i];
array[i] = t;
}
return array;
}
function Game(){
this.winningNumber = generateWinningNumber();
this.playersGuess = null;
this.pastGuesses = [];
}
Game.prototype.difference = function() {
return Math.abs(this.playersGuess - this.winningNumber);
}
Game.prototype.isLower = function() {
if (this.playersGuess < this.winningNumber) {
return true;
} else {
return false;
}
}
Game.prototype.checkGuess = function() {
if (this.playersGuess === this.winningNumber) {
return "You Win!";
}
if (this.pastGuesses.indexOf(this.playersGuess) > -1) {
return "You have already guessed that number.";
}
this.pastGuesses.push(this.playersGuess);
if (this.pastGuesses.length >= 5) {
return "You Lose.";
} else if (this.difference() < 10) {
return "You're burning up!";
} else if (this.difference() < 25) {
return "You're lukewarm.";
} else if (this.difference() < 50) {
return "You're a bit chilly.";
} else {
return "You're ice cold!";
}
}
Game.prototype.playersGuessSubmission = function(num) {
if (num < 1 || num > 100 || typeof num != 'number') {
throw "That is an invalid guess."
} else {
this.playersGuess = num;
return this.checkGuess();
}
}
Game.prototype.provideHint = function() {
return shuffle([generateWinningNumber(), generateWinningNumber(), this.winningNumber]);
}
newGame = function() {
game = new Game;
return game;
}
$(document).ready(function() {
var game = new Game;
var guessNum
onSubmit = function(event){
event.preventDefault();
var input = $('#player-input');
var guess = +input.val();
input.val('');
var result = game.playersGuessSubmission(guess);
if (result == 'You have already guessed that number.') {
$('#title').text(result);
} else if (result === 'You Win!' || result === 'You lose.') {
$('#title').text(result);
$('#subtitle').text('Press the reset button to play again.')
$('#hint').prop('disabled', true)
$('#submit').prop('disabled', true)
} else {
guessNum = (game.pastGuesses.length - 1).toString();
$('#l' + guessNum).text(guessNum);
}
};
$('#submit').on('click', function(e){
onSubmit(e);
});
$('#player-input').on('keypress', function(e) {
if(e.which == 13) {
e.preventDefault();
onSubmit(e);
};
});
});
});
You need to escape the CSS selector.
try to replace this line:
$('#' + guessNum).text(guessNum);
with this:
var selector = "#\\" + guessNum.toString().charCodeAt(0).toString(16) + " " + guessNum.toString().substr(1);
$(selector).text(guessNum);
you can read more at:
https://www.w3.org/International/questions/qa-escapes
I am making a game of tic-tac toe in javascript. I have laid out some of what I believe to be the basic building blocks:
var board = [
0, 0, 0,
0, 0, 0,
0, 0, 0
];
gameOn = true;
player1Move = true;
counter = 0;
player1 = [];
player2 = [];
var ask = console.log(prompt('where would you like to go?'));
var drawBoard = function(){
console.log(" A " + (board[0]) + "| B " + (board[1]) + "| C " + (board[2]));
console.log(" ------------- ");
console.log(" D " + (board[3]) + "| E " + (board[4]) + "| F " + (board[5]));
console.log(" ------------- ");
console.log(" G " + (board[6]) + "| H " + (board[7]) + "| I " + (board[8]));
console.log(" ------------- ");
};
var solutions = [
(board[0] && board[1] && board[2]) || (board[3] && board[4] && board[5]) ||
(board[6] && board[7] && board[8]) || (board[0] && board[3] && board[6]) ||
(board[1] && board[4] && board[7]) || (board[2] && board[5] && board[8]) ||
(board[0] && board[4] && board[8]) || (board[2] && board[4] && board[6])
];
while (gameOn === true){
// for loop for game logic
for (var i = 0 ; i < 9; i++){
if (player1Move === true) {
player1.push(ask);
drawBoard();
player1Move = false;
} else if (player1Move === false){
player2.push(ask);
drawBoard();
player1Move = true;
} else if ((player1 || player2) === solutions){
gameOn = false;
console.log((player1 || player2) + "wins!");
} else {
gameOn = false;
console.log("Tie Game!");
}
}
}
I know that the syntax of my main loop is incorrect. Why can't I do what is currently written? If you had this existing code, what type of loop setup would you use to accomplish this? Sorry if this seems not specific enough, I am just lost in the logic of it all!
With this existing loop all I am trying to do is go through and prompt the 2 users 9 times(because maximum moves = 9) in total for now. Once that works than I will keep adding more game logic into it. Why can't I get the prompt to come up 9 times? The current result is that it prompts me once, prints out the board 9 times and false after all of it.
This just needs to work in a terminal window for now too by the way.
I changed your code as little as possible, but a few things are different, which I am explaining bit by bit.
var board = {
A: null,
B: null,
C: null,
D: null,
E: null,
F: null,
G: null,
H: null,
I: null
};
gameOn = true;
player1Move = true;
var drawBoard = function(){
console.log(" A " + (board.A || '') + "| B " + (board.B || '') + "| C " + (board.C || ''));
console.log(" ------------- ");
console.log(" D " + (board.D || '') + "| E " + (board.E || '') + "| F " + (board.F || ''));
console.log(" ------------- ");
console.log(" G " + (board.G || '') + "| H " + (board.H || '') + "| I " + (board.I || ''));
console.log(" ------------- ");
};
var solutions = function() {
return (board.A && (board.A == board.B && board.A == board.C))
|| (board.D && (board.D == board.E && board.D == board.F))
|| (board.G && (board.G == board.H && board.G == board.I));
};
drawBoard();
var currentPlayer;
while (gameOn === true){
// for loop for game logic
for (var i = 0 ; i < 9; i++){
if (solutions()){
console.log(currentPlayer + " wins!");
gameOn = false;
break;
}
//else {
// gameOn = false;
// console.log("Tie Game!");
//}
currentPlayer = 'Player 1';
if(!player1Move)
currentPlayer = 'Player 2';
var ask = prompt(currentPlayer + ': where would you like to go (A or B or C or ..)?');
if(ask == 'exit') {
gameOn = false;
break;
}
if (player1Move === true) {
//player1.push(ask);
board[ask] = 'X';
drawBoard();
player1Move = false;
} else if (player1Move === false){
board[ask] = 'O';
drawBoard();
player1Move = true;
}
}
}
It's not completely finished, but then that's something you can do afterwards, and probably you didn't want me to do it all for you.
This all works in a Chrome console.
There were a couple of basic things that were holding you back:
var ask = console.log(prompt('where would you like to go?')); should be var ask = prompt(currentPlayer + ': where would you like to go?'); - your version was filling ask with null.
This prompt was also in the wrong place: it needs to be in the loop, and after drawBoard(), so that the player has something to look at.
I've changed the board from an array into an object, so that player answers like 'A' refer directly to the object fields. And that way the player arrays could be removed.
The solutions() function needs completing, as you can see, and there may be a neater way of doing this.
I added the possibility of writing 'exit' in the prompt, otherwise there's no way of exiting the game early.
I didn't finish the 'Tie game!' code.
Make sure you understand the global object is, and what window.prompt is, and what console.log is in your context. It is absolutely necessary to get to know a debugger for your environment. In Chrome it's called Developer Tools.
window.prompt is not very useful in code sandboxes like jsfiddle, or the Stack overflow bulit-in ones. I suggest using HTML for your user interface.
function init() {
trapForm();
trapInput();
toggleCurrentUser();
askUser();
}
var game = [
[null,null,null],
[null,null,null],
[null,null,null]
];
var trapInput = function() {
// capture input and use to to create a play in the game
document.querySelector('#go').addEventListener('click',function(ev) {
var position = document.querySelector('#square').valueAsNumber;
if (position < 10 && position > 0) {
// render X or O to the HTML
var td = document.querySelectorAll('#t3 td')[position-1];
td.innerHTML = currentUser;
// modify the corresponding game array
var row = Math.floor( (position-1) / 3 );
var col = ( (position+2) % 3) ;
game[row][col] = currentUser;
// this helps us visualize what's happening
debug(game);
checkGameStatus();
toggleCurrentUser();
} else {
debug({"msg":"illegal move"});
}
});
};
var trapForm = function() {
// prevent form from submitting
var f = document.querySelector('#f');
f.addEventListener('submit',function(ev) {
ev.preventDefault();
trapInput();
});
};
;(function(window,document,undefined){
"use strict";
function init() {
trapForm();
trapInput();
toggleCurrentUser();
askUser();
}
var currentUser = 'Y';
var toggleCurrentUser = function(){
if (currentUser === 'X') {
currentUser = 'Y';
} else {
currentUser = 'X';
}
document.querySelector('#currentuser').value = currentUser;
};
var isVirginal = function(game) {
return game.every(function(row) {
return row.every(function(cell) { return (cell === null); });
});
};
var isStaleMate = function(game){
return game.every(function(row){
return row.every(function(cell){
return (cell === 'X' || cell === 'Y');
});
});
};
var horizontalWinner = function(game) {
var r = false;
return game.some(function(row){
var firstletter = row[0];
if (firstletter === null) {
return false;
} else {
return row.every(function(cell){
return ( cell !== null && cell === firstletter);
});
}
});
};
var verticalWinner = function(game) {
var r = false;
for (var i = 0; i < 4; i++) {
if (game[0][i] === null) {
continue;
}
if (game[0][i] === game[1][i] && game[1][i] === game[2][i]) {
r = game[0][i];
break;
}
};
return r;
};
var diagonalWinner = function(game) {
var r = false;
if (game[0][0] !== null && (game[0][0] === game[1][1] === game[2][2])) {
r = game[0][0];
}
if (game[0][2] !== null && (game[0][2] === game[1][1] === game[2][0])) {
r = game[0][2];
}
return r;
};
var checkGameStatus = function(){
var r = 'unknown';
if (isVirginal(game)) {
r = 'Virginal Game';
} else {
r = 'In Play';
}
if (isStaleMate(game)) {
r = 'Stale Mate';
}
if (diagonalWinner(game)){
r = 'Diagonal Winner: ' + diagonalWinner(game);
}
if (verticalWinner(game)) {
r = 'vertical Winner: ' + verticalWinner(game);
}
if (horizontalWinner(game)) {
r = 'Horizontal Winner: ' + horizontalWinner(game);
}
document.querySelector('#status').value = r;
};
var debug = function(stuff) {
document.querySelector('#debug').innerHTML = JSON.stringify(stuff);
};
var game = [
[null,null,null],
[null,null,null],
[null,null,null]
];
var trapInput = function() {
// capture input and use to to create a play in the game
document.querySelector('#go').addEventListener('click',function(ev) {
var position = document.querySelector('#square').valueAsNumber;
if (position < 10 && position > 0) {
// render X or O to the HTML
var td = document.querySelectorAll('#t3 td')[position-1];
td.innerHTML = currentUser;
// modify the corresponding game array
var row = Math.floor( (position-1) / 3 );
var col = ( (position+2) % 3) ;
game[row][col] = currentUser;
// this helps us visualize what's happening
debug(game);
checkGameStatus();
toggleCurrentUser();
} else {
debug({"msg":"illegal move"});
}
});
};
var trapForm = function() {
// prevent form from submitting
var f = document.querySelector('#f');
f.addEventListener('submit',function(ev) {
ev.preventDefault();
trapInput();
});
};
document.addEventListener('DOMContentLoaded',init);
})(window,document);
#t3 {
font-family: "Courier New";
font-size: xx-large;
}
#t3 td {
border: 1px solid silver;
width: 1em;
height: 1em;
vertical-align: middle;
text-align: center;
}
#f {
position: relative;
}
#f label, input, button {
float: left;
width: 200px;
}
#f label, button {
clear: left;
}
hr {
clear: both;
visibility: hidden;
}
<form id="f">
<label for="currentuser">Current User</label>
<input type="text" readonly id="currentuser" name="currentuser" />
<label for="square">What Square (1-9)?</label>
<input type="number" step="1" min="1" max="9" id="square" name="square" />
<label for="status">Game Status</label>
<input type="text" readonly id="status" name="status" value="Virgin Game" />
<button type="button" id="go">make move</button>
</form>
<hr />
<table id="t3">
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
</table>
<pre id="debug"></pre>
I have a typing speed test with a textarea and I have I paragraph split into spans. Every time the user hits space, it highlights the next span. Then I split the textarea val() and compare the two at the end. I have everything working except I cannot get the enter key to do what I want it to do. I need it to act like the space bar(in the background) and act as the enter key on screen.
$(function() {
//APPEARANCE
$('#error').hide();
$('#oldTextOne').hide();
$('#oldTextTwo').hide();
$('#oldTextThree').hide();
$('#oldTextFour').hide();
$('#oldTextFive').hide();
$('.linkBox').hover(function() {
$(this).removeClass('linkBox').addClass('linkHover');
}, function() {
$(this).removeClass('linkHover').addClass('linkBox');
});
//FUNCTIONALITY VARIABLES
var min = '5';
var sec = '00';
var realSec = 0;
var errorTest = "hasn't started yet";
var oldTextVal;
var para;
// PICK A RANDOM PARAGRAPH
function pickRandom() {
var date = new Date();
date = date.getTime();
date += '';
var dateSplit = date.split('');
var temp = dateSplit.length - 1;
var picker = dateSplit[temp];
if (picker === '0' || picker === '1') {
para = $('#oldTextOne').text();
}
else if (picker === '2' || picker === '3') {
para = $('#oldTextTwo').text();
}
else if (picker === '4' || picker === '5') {
para = $('#oldTextThree').text();
}
else if (picker === '6' || picker === '7') {
para = $('#oldTextFour').text();
}
else {
para = $('#oldTextFive').text();
}
var splitPara = para.split(' ');
for (i in splitPara) {
$('#oldTextBox').append('<span id="pw' + i + '">' + splitPara[i] + '</span> ');
}
}
pickRandom();
//FUNCTION FOR TIMER
//APPEARANCE
function show() {
$('#timer').text(min + ' : ' + sec);
}
show();
//COUNT-DOWN
var count = function() {
sec = +sec - 1;
sec += '';
realSec++;
if (+sec === -1) {
sec = '59';
min -= 1;
min += '';
}
if (sec.length === 1) {
sec = '0' + sec;
}
show();
if (sec === '00' && min === '0') {
clearInterval(run);
checkIt();
}
};
// TYPE THE TEXT INTO #TYPEDTEXTBOX
$('#pw0').addClass('green');
var lastLetter;
$('#typedTextBox').focus().keypress(function() {
if (errorTest === "hasn't started yet") {
errorTest = 'running';
run = setInterval(count, 1000);
}
//STOP ERRORS FROM PEOPLE HITTING SPACE BAR TWICE IN A ROW !!NOT WORKING IN IE8
var thisLetter = event.which;
if (lastLetter === 32 && event.which === 32) {
event.preventDefault();
}
lastLetter = thisLetter;
}).keyup(function() {
//STOP ERRORS FROM BACKSPACE NOT REGISTERING WITH KEYPRESS FUNCTION
if (event.which === 8) {
lastLetter = 8;
}
if (event.which === 13) {
?????????????????????????????????????????????
}
//SPLIT THE TYPED WORDS INTO AN ARRAY TO MATCH THE OLD TXT SPANS (TO HIGHLIGHT THE CURRENT WORD IN OLDTXT)
var typedWords = $(this).val().split(' ');
var temp = typedWords.length - 1;
var oldTemp = temp - 1;
var stopErrors = temp + 1;
$('span:nth(' + temp + ')').addClass('green');
$('span:nth(' + oldTemp + ')').removeClass('green');
$('span:nth(' + stopErrors + ')').removeClass('green');
//SCROLL
if (typedWords.length < 50) {
return;
}
else if (typedWords.length > 50 && typedWords.length < 100) {
$('#oldTextBox').scrollTop(30);
}
else if (typedWords.length > 100 && typedWords.length < 150) {
$('#oldTextBox').scrollTop(60);
}
else if (typedWords.length > 150 && typedWords.length < 200) {
$('#oldTextBox').scrollTop(90);
}
else if (typedWords.length > 200) {
$('#oldTextBox').scrollTop(120);
}
//KEEP FOCUS IN THE TYPING AREA
}).blur(function() {
if (errorTest !== 'done') {
$(this).focus();
}
});
//COMPARE
//MAKE AN ARRAY OF THE OLDTEXT
var oldWords = para.split(' ');
//FUNCTION TO DISPLAY RESULTS
var checkIt = function() {
errorTest = 'done';
var correct = 0;
var typed = $('#typedTextBox').val();
var typedWords = typed.split(' ');
$('#typedTextBox').blur();
for (i = 0; i < typedWords.length; i++) {
if (typedWords[i] === oldWords[i]) {
correct += 1;
}
}
var errors = typedWords.length - correct;
var epm = (errors / realSec) * 60;
var wpm = Math.round(( ($('#typedTextBox').val().length / 5 ) / realSec ) * 60);
var realWpm = Math.round(wpm - epm);
//SHOW RESULTS
$('#oldTextBox').html('<br><span id="finalOne">WPM : <strong>' + realWpm + ' </strong></span><span class="small">(error adjusted)</span><br><br><span id="finalTwo">You made ' + errors + ' errors </span><br><span id="finalThree">Total character count of ' + $('#typedTextBox').val().length + '</span><br><span id="finalFour">Gross WPM : ' + wpm + '</span>');
};
//STOP BUTTON APPEARANCE AND FUNCTIONALITY
$('#stop').mouseover(function() {
$(this).addClass('stopHover');
}).mouseout(function() {
$(this).removeClass('stopHover');
}).click(function() {
if (errorTest === 'running') {
checkIt();
clearInterval(run);
errorTest = 'done';
}
});
});
try this:
//ENTER KEY
if (event.which === 13) {
//event.stopPropagation(); or
event.preventDefault();
//simulate spacebar
$(window).trigger({type: 'keypress', which: 32, keyCode: 32});
}
#james - Thanks for the help. I found a better way of thinking about the problem. Instead of changing the enter key action, I changed the split function to var typedWords = typed.split(/[ \r\n]+/);