I have a simple program, but I have an issue. I previously had a problem with the page displaying "Loading..." before, but I fixed that. Whenever I try to load now, I get "localhost refused to connect". I have tried the internet but all the fixes seem to be for the first error. How do I get it to load? Here is the code:
let pew;
let crosshair;
let imgConst = 100;
var imgSize = imgConst;
var imgChange = [4, (6 + 2/3), 10, -10, -10, -10, -10, -20, (-33 - 1/3), -50];
for(var i = 0; i = imgChange.length; i++) {
imgChange[i] = imgSize + imgConst/imgChange[i]
console.log(i)
}
function preload() {
crosshair = loadImage('crosshair.png')
}
function setup() {
createCanvas(windowWidth, windowHeight);
frameRate(10);
noStroke();
noCursor();
pew = new bullet();
}
function draw() {
background(50, 89, 100);
//Shrink bullets
pew.shrink()
//crosshair
image(crosshair, mouseX - imgSize/2, mouseY - imgSize/2, imgSize, imgSize);
}
// bullet class
class bullet {
constructor() {
this.x = [];
this.y = [];
this.size = [];
this.shrinkSpeed = 1;
this.diameter = 10;
}
shrink() {
fill(61, 41, 15)
for(var i = 0; i < this.x.length; i++) {
if(this.size[i] <= 1) {
this.size.splice(i);
} else {
ellipse(this.x[i], this.y[i], this.size[i], this.size[i]);
this.size[i] = this.size[i] - this.shrinkSpeed;
}
}
}
add() {
this.x.push(mouseX);
this.y.push(mouseY);
this.size.push(this.diameter)
for( i = 0; i < imgChange.length * 1; i ++) {
imgSize = imgChange[floor(i)]
console.log(imgSize);
}
}
}
function mousePressed() {
//add bullet
pew.add();
}
You have 2 problems in for loops.
First, in your first for loop, change i = imgChange.length to i < imgChange.length. Second, you are missing a var in the add() function of your bullet class: for( i = 0.
Now, your code should run.
Related
Maybe this is basic stuff and things I want to do is really simple, but being a bit junior in Javascript I cannot find any answer to my issue.
What I want to achieve is that from code (in runtime) I want a file to be generated containing all properties and methods (including parameters and if possible return values) described.
Console logging this.__proto__ and Object.keys(this) prints somewhat what I expect.
However, using the Object.keys(this.__proto__) does not return anything useable. I guess this is somehow connected to the fact that the __proto__ contains functions, which are fx. not parsable with JSON.parse().
Any ideas how to approach this?
Test code I used:
const fs = require('fs');
class Exporter {
constructor(name) {
this.filename = `./${name}.export`;
}
export(me) {
let file = '';
let d
d = Object.keys(me);
for (let i = 0; i < d.length; i++) { file += d[i] + '\n'; }
d = Object.keys(me.__proto__);
for (let i = 0; i < d.length; i++) { file += d[i] + '\n'; }
fs.writeFileSync(this.filename, file);
}
}
class Box {
constructor(name, length, width, height) {
this.name = name;
this.length = length;
this.width = width;
this.height = height;
this._export = new Exporter(this.name);
this._export.export(this);
}
volume() {
return this.length * this.height * this.width;
}
}
myBox = new Box('Matts', 2, 3, 4); //creates file Matts.export
console.log(myBox.volume()); //prints '24'
File "Matts.export" written contains:
name
length
width
height
_export
So basically the Objects.keys(me.__proto__) returned a zero length array. I did expect the volume function stated. Preferably with parameters and return value. But I guess the later is hard to achieve in JavaScript.
Because those properties are not enumerable, you can check by using Object.getOwnPropertyDescriptors()
class Box {
constructor(name, length, width, height) {
this.name = name;
this.length = length;
this.width = width;
this.height = height;
}
volume() {
return this.length * this.height * this.width;
}
}
let myBox = new Box("Matts",2,3,4);
console.log(Object.getOwnPropertyDescriptors(myBox.__proto__));
However,Object.getOwnPropertyDescriptors() returns an object which have the same keys as the given object. So you can get the keys from the descriptors:
class Box {
constructor(name, length, width, height) {
this.name = name;
this.length = length;
this.width = width;
this.height = height;
}
volume() {
return this.length * this.height * this.width;
}
}
let myBox = new Box("Matts",2,3,4);
console.log(Object.keys(Object.getOwnPropertyDescriptors(myBox.__proto__)));
I've been trying to fix this thing for a while now but it doesn't seem to work; "Could not run the sketch (Target VM failed to initialize)."
I'll post the full code down below.
In the draw(), there are three for loops.
for(int i = 0; i<objectAmount; i++) {
circles[i].drawObj();
}
The first one creates the circles, while the second nested ones take care of collision and drawing the lines;
for(int i = 0; i<rayAmount; i++) {
rays[i].update();
for(int j = 0; j<objectAmount; j++) {
rays[i].collide(circles[j]);
}
line(rays[i].xPos, rays[i].yPos, rays[i].xEnd, rays[i].yEnd);
}
the .collide takes point on the 'ray' and moves closer to the circle until it reaches some value, where it marks the line's end, which is then used by the line() function to draw it to the circle.
For some reason, when I implemented the .collide function, everything stopped working unless I set the amount of rays to one, in which case no rays would appear but the circle generation would follow along just fine.
int rayAmount = 45;
int angleCorrect = 360/rayAmount;
int objectAmount = 10;
Ray[] rays = new Ray[rayAmount];
Object[] circles = new Object[objectAmount];
void setup() {
size(600, 400, P2D);
for(int i = 0; i<rayAmount; i++) {
rays[i] = new Ray(i*angleCorrect);
}
for(int i = 0; i<objectAmount; i++) {
circles[i] = new Object(random(0, 600), random(0, 400), random(20, 100));
}
}
void draw() {
background(255);
stroke(100);
for(int i = 0; i<objectAmount; i++) {
circles[i].drawObj();
}
for(int i = 0; i<rayAmount; i++) {
rays[i].update();
for(int j = 0; j<objectAmount; j++) {
rays[i].collide(circles[j]);
}
line(rays[i].xPos, rays[i].yPos, rays[i].xEnd, rays[i].yEnd);
}
}
class Ray {
float xPos, yPos, Angle, xEnd, yEnd;
Ray(float angle) {
xPos = mouseX;
yPos = mouseY;
Angle = angle;
}
void update() {
xPos = mouseX;
yPos = mouseY;
//xEnd = xPos + 100 * cos(radians(Angle));
//yEnd = yPos + 100 * sin(radians(Angle));
}
void collide(Object other) {
float newXEnd = this.xEnd;
float newYEnd = this.yEnd;
float distToObject = sqrt(pow(other.xPos-this.xPos, 2) + pow(other.yPos-this.yPos, 2));
while(distToObject > 1) {
newXEnd = newXEnd + distToObject * cos(radians(Angle));
newYEnd = newYEnd + distToObject * sin(radians(Angle));
distToObject = sqrt(pow(other.xPos-newXEnd, 2) + pow(other.yPos-newYEnd, 2));
}
this.xEnd = newXEnd;
this.yEnd = newYEnd;
}
}
class Object {
float xPos, yPos, radius;
Object(float x, float y, float r) {
xPos = x;
yPos = y;
radius = r;
}
void drawObj() {
stroke(100);
circle(xPos, yPos, radius);
}
}
I'm trying to determine the points of the players based on the different frame that a bullet hits, is this possible? So basically I want to for example, give 100 points if figurapega matches figura, and 50 points if it does not, but I have not been please my code below.
///////Here I load the atlas
this.load.atlas('Monsters', 'asset/game1/Monstruos/monstruos.png', 'asset/game1/Monstruos/monstruos.json');
///this is the one I want to use as reference to compare
createFiguraCompare: function(){
//Figura para comparar
this.figuritaspega = this.game.add.sprite(800, 140, 'Monsters', this.rnd.integerInRange(0,4));
this.figuritaspega.scale.set(0.5, 0.5 );
},
/////////and this is the one generating sprites that need to be shot at
makeOneFigura: function() {
this.figura = this.game.add.group();
this.figura.enableBody = true;
this.figura.physicsBodyType = Phaser.Physics.P2JS;
// for (var i = 0; i < 5; i++){
this.figura.createMultiple(100, 'Monsters', 0, false);
// }
this.figura.setAll('anchor.x', 0.5);
this.figura.setAll('anchor.y', 0.5);
this.figura.setAll('outOfBoundsKill', true);
this.figura.setAll('checkWorldBounds', true);
},
makeFiguras: function(x, y){
if (this.timerFiguras) {
this.figuras = this.figura.getFirstExists(false);
if (this.figuras) {
this.figuras.reset(0, 350);
this.figuras.frame = this.game.rnd.integerInRange(0,4);
this.figuras.body.setCollisionGroup(this.figuraCG);
this.figuras.body.collides(this.bulletCG);
this.figuras.body.velocity.x = 1000;
}
};
},
/////and last but no least the collision handler which is where Im trying to compare but with no luck
collisionBulletFigura: function(bullet, figuras, score, scoreText, figuritaspega) {
if (this.figuras.frame === this.figuritaspega.frame){
figuras.sprite.kill();
bullet.sprite.kill();
this.score += 100;
this.scoreText.text = this.score;
}else {
figuras.sprite.kill();
bullet.sprite.kill()
this.score += 50;
this.scoreText.text = this.score;
}
},
I want to concatenate a bunch of different files of a single type into one large file. For example, many javascript files into one large file, many css files down to one etc. I want to create a sourcemap of the files pre concatenation, but I do not know where to start. I am working in Node, but I am also open to solutions in other environments.
I know there are tools that can do this, but they seem to be on a language by language basis (uglifyjs, cssmin or whatever its called these days), but I want a tool that is not language specific.
Also, I would like to define how the files are bound. For example, in javascript I want to give each file its own closure with an IIFE. Such as:
(function () {
// File
}());
I can also think of other wrappers I would like to implement for different files.
Here are my options as I see it right now. However, I don't know which is best or how to start any of them.
Find a module that does this (I'm working in a Node.js environment)
Create an algorithm with Mozilla's source-map module. For that I also see a couple options.
Only map each line to the new line location
Map every single character to the new location
Map every word to its new location (this options seems way out of scope)
Don't even worry about source maps
What do you guys think about these options. I've already tried options 2.1 and 2.2, but the solution seemed way too complicated for a concatenation algorithm and it did not perform perfectly in the Google Chrome browser tools.
I implemented code without any dependencies like this:
export interface SourceMap {
version: number; // always 3
file?: string;
sourceRoot?: string;
sources: string[];
sourcesContent?: string[];
names?: string[];
mappings: string | Buffer;
}
const emptySourceMap: SourceMap = { version: 3, sources: [], mappings: new Buffer(0) }
var charToInteger = new Buffer(256);
var integerToChar = new Buffer(64);
charToInteger.fill(255);
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='.split('').forEach((char, i) => {
charToInteger[char.charCodeAt(0)] = i;
integerToChar[i] = char.charCodeAt(0);
});
class DynamicBuffer {
buffer: Buffer;
size: number;
constructor() {
this.buffer = new Buffer(512);
this.size = 0;
}
ensureCapacity(capacity: number) {
if (this.buffer.length >= capacity)
return;
let oldBuffer = this.buffer;
this.buffer = new Buffer(Math.max(oldBuffer.length * 2, capacity));
oldBuffer.copy(this.buffer);
}
addByte(b: number) {
this.ensureCapacity(this.size + 1);
this.buffer[this.size++] = b;
}
addVLQ(num: number) {
var clamped: number;
if (num < 0) {
num = (-num << 1) | 1;
} else {
num <<= 1;
}
do {
clamped = num & 31;
num >>= 5;
if (num > 0) {
clamped |= 32;
}
this.addByte(integerToChar[clamped]);
} while (num > 0);
}
addString(s: string) {
let l = Buffer.byteLength(s);
this.ensureCapacity(this.size + l);
this.buffer.write(s, this.size);
this.size += l;
}
addBuffer(b: Buffer) {
this.ensureCapacity(this.size + b.length);
b.copy(this.buffer, this.size);
this.size += b.length;
}
toBuffer(): Buffer {
return this.buffer.slice(0, this.size);
}
}
function countNL(b: Buffer): number {
let res = 0;
for (let i = 0; i < b.length; i++) {
if (b[i] === 10) res++;
}
return res;
}
export class SourceMapBuilder {
outputBuffer: DynamicBuffer;
sources: string[];
mappings: DynamicBuffer;
lastSourceIndex = 0;
lastSourceLine = 0;
lastSourceCol = 0;
constructor() {
this.outputBuffer = new DynamicBuffer();
this.mappings = new DynamicBuffer();
this.sources = [];
}
addLine(text: string) {
this.outputBuffer.addString(text);
this.outputBuffer.addByte(10);
this.mappings.addByte(59); // ;
}
addSource(content: Buffer, sourceMap?: SourceMap) {
if (sourceMap == null) sourceMap = emptySourceMap;
this.outputBuffer.addBuffer(content);
let sourceLines = countNL(content);
if (content.length > 0 && content[content.length - 1] !== 10) {
sourceLines++;
this.outputBuffer.addByte(10);
}
let sourceRemap = [];
sourceMap.sources.forEach((v) => {
let pos = this.sources.indexOf(v);
if (pos < 0) {
pos = this.sources.length;
this.sources.push(v);
}
sourceRemap.push(pos);
});
let lastOutputCol = 0;
let inputMappings = (typeof sourceMap.mappings === "string") ? new Buffer(<string>sourceMap.mappings) : <Buffer>sourceMap.mappings;
let outputLine = 0;
let ip = 0;
let inOutputCol = 0;
let inSourceIndex = 0;
let inSourceLine = 0;
let inSourceCol = 0;
let shift = 0;
let value = 0;
let valpos = 0;
const commit = () => {
if (valpos === 0) return;
this.mappings.addVLQ(inOutputCol - lastOutputCol);
lastOutputCol = inOutputCol;
if (valpos === 1) {
valpos = 0;
return;
}
let outSourceIndex = sourceRemap[inSourceIndex];
this.mappings.addVLQ(outSourceIndex - this.lastSourceIndex);
this.lastSourceIndex = outSourceIndex;
this.mappings.addVLQ(inSourceLine - this.lastSourceLine);
this.lastSourceLine = inSourceLine;
this.mappings.addVLQ(inSourceCol - this.lastSourceCol);
this.lastSourceCol = inSourceCol;
valpos = 0;
}
while (ip < inputMappings.length) {
let b = inputMappings[ip++];
if (b === 59) { // ;
commit();
this.mappings.addByte(59);
inOutputCol = 0;
lastOutputCol = 0;
outputLine++;
} else if (b === 44) { // ,
commit();
this.mappings.addByte(44);
} else {
b = charToInteger[b];
if (b === 255) throw new Error("Invalid sourceMap");
value += (b & 31) << shift;
if (b & 32) {
shift += 5;
} else {
let shouldNegate = value & 1;
value >>= 1;
if (shouldNegate) value = -value;
switch (valpos) {
case 0: inOutputCol += value; break;
case 1: inSourceIndex += value; break;
case 2: inSourceLine += value; break;
case 3: inSourceCol += value; break;
}
valpos++;
value = shift = 0;
}
}
}
commit();
while (outputLine < sourceLines) {
this.mappings.addByte(59);
outputLine++;
}
}
toContent(): Buffer {
return this.outputBuffer.toBuffer();
}
toSourceMap(sourceRoot?: string): Buffer {
return new Buffer(JSON.stringify({ version: 3, sourceRoot, sources: this.sources, mappings: this.mappings.toBuffer().toString() }));
}
}
I, at first, implemented "index map" from that spec, only to find out that it is not supported by any browser.
Another project that could be useful to look at is magic string.
I want to create a list of operation's in a grid view. For example visit this URL.
http://cdn-static.cnet.co.uk/i/product_media/40000186/nokia1616_01.jpg
You can look at this question or this page(and use LWUIT or CustomItems) or extend "canvas".In this way you need to two pictures for every operation in grid view.One for normal state and another for highlighted.Here is a simple canvas that represents 4 operations in 2*2 grid:
public class GridCanvas extends Canvas {
int highlightedRow = 0;
int highlightedColumn = 0;
Image[][] normalImageMat;
Image[][] highlightedImageMat;
Image[][] imageMat;
int gridColumnNo;
int gridRowNo;
/**
* constructor
*/
public GridCanvas() {
gridColumnNo = 2;
gridRowNo = 2;
normalImageMat = new Image[gridRowNo][gridColumnNo];
highlightedImageMat = new Image[gridRowNo][gridColumnNo];
imageMat = new Image[gridRowNo][gridColumnNo];
try {
for (int i = 0; i < gridRowNo; i++) {
for (int j = 0; j < gridColumnNo; j++) {
normalImageMat[i][j] = Image.createImage("/hello/normalImage" + i + j + ".png");
}
}
for (int i = 0; i < gridRowNo; i++) {
for (int j = 0; j < gridColumnNo; j++) {
highlightedImageMat[i][j] = Image.createImage("/hello/highlightedImage" + i + j + ".png");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* paint
*/
public void paint(Graphics g) {
g.setColor(255, 255, 255);
g.fillRect(0, 0, getWidth(), getHeight());
for (int i = 0; i < gridRowNo; i++) {
System.arraycopy(normalImageMat[i], 0, imageMat[i], 0, 2);
}
imageMat[highlightedRow][highlightedColumn] = highlightedImageMat[highlightedRow][highlightedColumn];
int width = 0;
int height = 0;
for (int i = 0; i < gridRowNo; i++) {
for (int j = 0; j < gridColumnNo; j++) {
g.drawImage(imageMat[i][j], width, height, 0);
width = width + imageMat[i][j].getWidth();
}
width = 0;
height = height + imageMat[0][0].getHeight();
}
}
/**
* Called when a key is pressed.
*/
protected void keyPressed(int keyCode) {
int gameAction = this.getGameAction(keyCode);
if (gameAction == RIGHT) {
highlightedColumn = Math.min(highlightedColumn + 1, gridColumnNo - 1);
} else if (gameAction == LEFT) {
highlightedColumn = Math.max(highlightedColumn - 1, 0);
} else if (gameAction == UP) {
highlightedRow = Math.max(0, highlightedRow - 1);
} else if (gameAction == DOWN) {
highlightedRow = Math.min(gridRowNo - 1, highlightedRow + 1);
}
repaint();
}
}
In real samples you would to detect gridColumnNo and gridRowNo due to screen and your icons dimensions.
If you can not go with LWUIT (license, library size, etc) and do not want to leave the screen rendering to LCDUI (CustomItem), you should extend Canvas.
I have shared code for an adaptive grid at http://smallandadaptive.blogspot.com.br/2010/12/touch-menu.html Feel free to use it.
At this sample all items are Strings, but you can change the TouchItem to draw Images instead.