unexpected token error line 41-"y:Math.round(Math.random()*(h-cw)/cw);" - javascript

I am trying to re-create the classic mobile game "Snake" using HTML/CSS3 and Javascript. When I run what I have in chrome I get the unexpected token error on line 41. Why is the semi-colon unexpected? The code I have so far is below.
$(document).ready(function(){
//define vars
var canvas = $('#canvas')[0];
var ctx = canvas.getContext("2d");
var w = canvas.width();
var h = canvas.height();
var cw = 15;
var d = "right";
var food;
var score;
var speed = 130;
//Snake Array
var snake_array;
//initalizer
function init(){
create_snake();
create_food();
score = 0;
if(typeof game_loop != "undefined") clearInterval(game_loop);
game_loop = setInterval(paint, speed);
}
init();
function create_snake(){
var length = 5;
snake_array =[];
for(var i = length-1;i >=0;i--){
snake_array.push({x: i,y :0});
}
}
//Create Food
function create_food(){
food = {
x:Math.round(Math.random()*(w-cw)/cw),
y:Math.round(Math.random()*(h-cw)/cw); // <-- line 41
};
}
});
HTML CODE
<!DOCTYPE html>
<html>
<head>
<title>Snake Game</title>
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
<div class="container">
<div id ="overlay">
Your final score: <span id = "final_score">
</span>
<br>
<a onclick="window.location.reload()" href="#">Click to play again!</a>
</div>
<canvas id="canvas" width="600" height="400">
</canvas>
<div id="stats">
<div class="score"></div>
<div class="score"></div>
<button onclick="resetScore()" id="reset_score">Reset high score</button>
</div>
</div>
<!-- JQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<!-- Main JS -->
<script src="C:\Users\student\Desktop\SnakeGame\script.js"></script>
</body>
</html>

When defining a variable like this x: (typically used in objects) you cannot put a ; after the last defined variable like you did:
food = {
x:Math.round(Math.random()*(w-cw)/cw),
y:Math.round(Math.random()*(h-cw)/cw); // <-- remove this semi-colon
};
Do this instead
food = {
x:Math.round(Math.random()*(w-cw)/cw),
y:Math.round(Math.random()*(h-cw)/cw)
};
I hope I was to any help :3

Related

Why is require('fs') causing my js variables to not show in html?

I'm trying to make an electron app that increments and reduces a number and updates that number to a local .txt file.
I have the numbers displaying and counting up/down but as soon as I introduce the fs node it reverts to the placeholder text of "ScoreA"
var fs = require('fs');
//Score A initialise
var scoreAOriginal = 0;
var dx = scoreAOriginal;
//Score A button functions
function incA(num){
dx = dx + num;
}
function decA(num){
if (dx >= 1){
dx = dx - num;
}
}
//Score B initialise
var scoreBOriginal = 0;
var dy = scoreBOriginal;
//Score B button functions
function incB(num){
dy = dy + num;
}
function decB(num){
dy = dy - num;
}
// Refresher and value assignment to div classes in index.html
setInterval(function(){ document.getElementById("scoreA").innerHTML = dx; document.getElementById("scoreB").innerHTML = dy; }, 100);
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Peppy - by Doug</title>
<script src="./main.js"></script>
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<h1>Peppy</h1>
<div class="scoreConsoles">
<div>
<button class="button button5" onclick="incA(1)">+</button>
<div id="scoreA">scoreA</div>
<button class="button button5" onclick="decA(1)">-</button>
</div>
<div>
<button class="button button5" onclick="incB(1)">+</button>
<div id="scoreB">scoreB</div>
<button class="button button5" onclick="decB(1)">-</button>
</div>
</div>
<!-- You can also require other files to run in this process -->
<script src="./renderer.js"></script>
</body>
</html>
How did you create the window? You know you need to enable node integration:
const mainWindow = new BrowserWindow({
webPreferences: {
nodeIntegration: true
}
});

I can't see progress in the browsr when trying to make a game

Hi I'm trying to learn game dev with javascript .... When I ope my html file in my browser, it's blank and this is the error I keep on getting...
createjs-2013.12.12.min.js:13 Uncaught TypeError: f.isVisible is not a functionb.draw
# createjs-2013.12.12.min.js:13b.update
# createjs-2013.12.12.min.js:13window.onload # init.js:25 "
var canvas;
var stage ;
var img = new Image();
var bmpSeq;
var text;
window.onload = function()
{
canvas = document.getElementById("myCanvas");
context = canvas.getContext('2d');
context.canvas.width = 900;
context.canvas.height = 500;
stage = new createjs.Stage(canvas);
text = new Text("TEXT HERE","36px Ariel","black");
text.x =100;
text.y = 200;
stage.addChild(text);
var circle = new createjs.Shape();
circle.graphics.beginFill("red").drawCircle(0, 0, 50);
circle.x = 100;
circle.y = 100;
stage.addChild(circle);
stage.update();
//img.onload = ImageLoaded;
//img.src = "assets/dude.png" ;
}
function ImageLoaded(e)
{
//stage = new createjs.Stage("canvas");
var ss = new createjs.SpriteSheet({
images : [img],
frames : {width:32,height:64},
animations: {
face : 4,
walk : [4,8] }
});
//bitmap sequence
//bmp = new createjs.BitmapAnimation(ss);
//bmp.regX = bmp.spriteSheet.frameWidth/2|0; //reg pt in the center of the frame
// bmp.regY = bmp.spriteSheet.frameHeight/2|0;
//bmp.gotoAndPlay("w_r");
//bmp.x = canvas.width/2;
//bmp.y = canvas.height/2;
stage.addChild(ss); //won't do anything yet
//stage.update();
}
<!DOCTYPE html>
<html>
<head>
<title>GAme Trial</title>
<link href="normalize.css" type="text/css" rel="stylesheet" />
<script language="javascript" type="text/javascript" src="http://code.createjs.com/createjs-2013.12.12.min.js" ></script> <!--Getting the Library-->
<script language="javascript" type="text/javascript" src="init.js" ></script>
</head>
<body>
<canvas id="myCanvas"></canvas> <!--graphical surface in which the game is played-->
</body>
</html>
You created a new Text() object, instead of the createjs.Text() object.
Change this
text = new Text("TEXT HERE","36px Ariel","black");
to this
text = new createjs.Text("TEXT HERE","36px Ariel","black");
And you're good to go. Take care to add createjs. before the objects that were made available by that library.

Running processing code in canvas by getting the code from textarea

I am trying to get the processing code from textbox and make it running in canvas but i don't know what is happening can someone help me? When i debug it's says ctx.compile(); is not a function how can i make it work propperly? Here is the code i use.
<!DOCTYPE Html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="styles/style2.css" >
<script src="processing-1.4.1.js"></script>
<script type="text/javascript">
function submitTryit() {
var text = document.getElementById("textareaCode").value;
var ifr = document.createElement("iframe");
ifr.setAttribute("frameborder", "0");
ifr.setAttribute("id", "iframeResult");
document.getElementById("iframewrapper").innerHTML = "";
document.getElementById("iframewrapper").appendChild(ifr);
var ifrw = (ifr.contentWindow) ? ifr.contentWindow : (ifr.contentDocument.document) ? ifr.contentDocument.document : ifr.contentDocument;
ifrw.document.open();
ifrw.document.write(text);
ifrw.document.close();
canvas();
if (ifrw.document.body && !ifrw.document.body.isContentEditable) {
ifrw.document.body.contentEditable = true;
ifrw.document.body.contentEditable = false;
}
function canvas() {
var ifrr = document.getElementById('iframeResult');
var iframediv = (ifrr.contentWindow.document) ? ifrr.contentWindow.document : (ifrr.contentDocument.document) ? ifrr.contentDocument.document : ifrr.contentDocument;
var canv = document.createElement('CANVAS');
canv.setAttribute('id', 'mycanvas');
var ctx = canv.getContext("2d");
ctx.compile();
iframediv.body.appendChild(canv);
}
}
function compile(){
var processingCode = document.getElementById('textCode').value;
var jsCode = Processing.compile(processingCode).sourceCode;
}
</script>
</head>
<body>
<div class="container">
<!--Iframe-->
<div class="iframecontainer">
<div id="iframewrapper" class="iframewrapper">
</div>
</div>
<!--PJS text field-->
<div class="PJStextwraper">
<div class="overPJStext">
</div>
<textarea id="textCode" spellcheck="false" autocomplete="off" wrap="logical"> int x,y,w;
float vx,vy;
void setup() {
size(300,200);
x = int(random(width));
y = int(random(height));
vx = random(5);
vy = random(5);
w = int(10+random(10));
}
void draw() {
background(140,70,60);
ellipse(x,y,w,w);
x += vx;
y += vy;
//
if(x > width || x < 0) {
vx *= -1;
}
if(y > height || y < 0) {
vy *= -1;
}
}
</textarea>
</div>
<button class="BT" type="button" onclick="submitTryit()">Run ยป</button>
</div> <!-- End container-->
</body>
</html>
The error "ctx.compile(); is not a function" is expected since you are trying to call a function that does not exist on the 2d canvas context. If I understand correctly, you are trying to run your own compile function and render it on the canvas you just created.
To do so, you need to change a few things, try the following and see if it works:
function canvas() {
var ifrr = document.getElementById('iframeResult');
var iframediv = (ifrr.contentWindow.document) ? ifrr.contentWindow.document : (ifrr.contentDocument.document) ? ifrr.contentDocument.document : ifrr.contentDocument;
var canv = document.createElement('canvas');
canv.setAttribute('id', 'mycanvas');
// The ctx will be created in an instance of Processing.
// So no need for the following line.
// var ctx = canv.getContext("2d");
compile(canv);
iframediv.body.appendChild(canv);
}
// Here you can pass the canvas where you want to render the code.
function compile(canv) {
var processingCode = document.getElementById('textCode').value;
var jsCode = Processing.compile(processingCode).sourceCode;
// Now that you have the code in JS, you can create an instance of Processing.
// But, what you get from the compiler is a string,
// so you need to convert the string to JS.
// For instance, I use here eval(jsCode)
var processingInstance = new Processing(canv, eval(jsCode));
}

randomise array html5 java script

<!-- with thanks to http://stackoverflow.com/questions/25407926/spawn-random-images-
in-canvas-in-javascript-->
<!--http://www.freesfx.co.uk/download/?type=mp3&id=11028
--audio loader--
http://stackoverflow.com/questions/18826147/javascript-audio-play-on-
click-->
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<title>Street</title>
<script type="text/javascript">
var can, ctx;
var sprite = new Array();
var counter = 0;
var rot = 0;
var centerX = -320;
var centerY = -170;
var sprite = new Array(id); // Array to hold the filenames
function init() {
can = document.getElementById("can");
ctx = can.getContext("2d");
// get images into array
sprite[0] = document.getElementById("b1");
sprite[1] = document.getElementById("b2");
sprite[2] = document.getElementById("b3");
sprite[3] = document.getElementById("b4");
// draw lights out
draw();
// wait 3 sec, then begin animation
var t = setTimeout(light, 30);
}
function light() {
var wait = 600;
counter++;
if (counter == 4) {
counter = 0;
wait += (Math.random() * 1500);
rot += .01;
}
draw();
setTimeout(light, wait);
}
function draw() {
ctx.clearRect(0, 0, can.width, can.height);
ctx.save();
ctx.translate(can.width / 2, can.height / 2);
ctx.drawImage(sprite[counter], centerX, centerY);
ctx.restore();
}
function choseRandom(range) {
if (Math.random)
return Math.round(Math.random() * (range-1));
else {
var now = new Date();
return (now.getTime() / 1000) % range;
}
}
var choice = choseRandom(id);
</script>
</head>
<body onload="init()">
<audio id="Mp3Me" autoplay autobuffer controls>
<source src="au1.mp3">
<source src="au1.ogg">
</audio>
<img id="b1" style="display:none" src="1.png" >
<img id="b2" style="display:none" src="2.png" >
<img id="b3" style="display:none" src="3.png" >
<img id="b4" style="display:none" src="4.png" >
<canvas class="canvas" id="can" width="640" height="350" style=" border:1px solid #6F2E0D; ">
</canvas>
<script>
function play(){
var audio = document.getElementById("audio");
audio.play();
}
</script>
<input type="button" value="PLAY" onclick="play()">
<audio id="audio" src="door.mp3" ></audio>
<div id="container"></div>
<script language="JavaScript">
document.writeln('<td' + '><img src="'
+ ranimage[choice] + '" height="180" width="160" border="0" ><' +
'/td>');
</script>
<div id='container'>
<img id = "image2" src='door.png' />
</body>
</html>
The above code works with thanks to stack overflow.
Basically at the moment this code displays images in sequence non randomly, it uses the array to fetch them, and show them. The code then regulates the speed of the image display. There is also a sound player, and a button with a sound.
I managed after some considerable searching to animate a simple sequence of png files. However I have been trying to ad start stop button and a math random function (preferably the music on-click would start everything going).
I want to add a random function to the array,so that it displays images randomly. however the best I could do was, not to brake the code, or to get is to speed up the animation. Can some one please modify my code to add these functions or please point me to some place that would help.
The randomized array would be really useful.
Demo: http://jsfiddle.net/techsin/dtz0yj4y/
Code
function shuffle (arr) {
arr.forEach(function(e,i){
var rand = ~~(Math.random()*(arr.length-1));
arr[i] = arr[rand];
arr[rand] = e;
});
}
var myArr = [1,2,3,4,5];
shuffle(myArr); //myArr is now shuffled!
Example...
(there was a mistake, updated)
For example,
var array = [1,2,3,4,5]
for(i=0; i<array.length;i++){
var dist = Math.floor( Math.random() * array.length )
var swp = array[i]
array[i] = array[dist]
array[dist] = swp
}
console.log(array) //=> shuffled

Why doesn't incPixel work as expected?

<!DOCTYPE html>
<html>
<head>
<meta lang="EN" />
<script type="text/javascript" src="jquery-1.4.4.min.js"></script>
<script type="text/javascript">
// Don't resize the window
function _(str){
return document.getElementById(str);
}
function incPixel(imageData, x, y){
var index = (x + y * imageData.width) * 4;
imageData.data[index + 0] = 155;
imageData.data[index + 1] = 155;
imageData.data[index + 2] = 155;
imageData.data[index + 3] = 155;
}
$(document).ready(function(){
// collect mouse position data
var history = [];
$(document).mousemove(function(e){
history.push([e.pageX, e.pageY]);
});
// when the button is clicked
$("#button").click(function(){
// 1. disable mouse position data collection
$(document).unbind("mousemove");
// 2. draw pixels on the canvas
var width = $(document).width();
var height = $(document).height();
$("#canvas").height(height).width(width);
var canvas = document.getElementById("canvas");
if(canvas.getContext){
var context = canvas.getContext("2d");
var imageData = context.createImageData(width, height);
for(var i=0; i<history.length; i++){
incPixel(imageData, history[i][0], history[i][1]);
}
context.putImageData(imageData, 0, 0);
alert(JSON.stringify(history));
}else{
alert("no context");
}
});
});
</script>
</head>
<body>
<h1>Hello, Worlds!</h1>
<div id="width"></div>
<div id="height"></div>
<input type="button" id="button" value="Click me" /><br />
<canvas id="canvas" />
</body>
</html>
You're missing the context type parameter from getContext(), it should be:
var context = canvas.getContext('2d');
You can test out a demo here with only the change above.

Categories