Need help printing 2 Fractal trees - javascript

Yesterday, I had asked for help in printing out a Fractal tree. That question was answered, but now I am trying to implement one more rule into my code. And while implementing it in my code, it is printing the tree, but not at the right coordinates. Here is a link to my previous question. I would like to print both the trees side-by-side instead of on top of each other. So my question is how do I achieve that? Thanks for all the help.
Here is the new code:
var sentence = "F";
var sentence2 = "F";
var sentence3 = "X";
var rules = [];
rules[0] = {
a: "F",
b: "F[+F]F[-F]F"
}
var rulesB = [];
rulesB[0] = {
a: "F",
b: "FF-[-F+F+F]+[+F-F-F]"
}
/*
var rulesC = [];
rulesC[0] = {
a: "F",
b: "FF"
}
rulesC[1] = {
a: "X",
b: "F-[[X]+X]+F[+FX]-X"
}
*/
var x = 50; // starting x
var y = 400; // starting y
var y_stack = []; // save & restore don't handle coordinates
var y_stack2 = []
draw();
function turtle(sentence, context){
for (var i = 0; i < sentence.length; i++) {
var current = sentence.charAt(i);
if (current == "F") {
y -= 20;
context.lineTo(x, y);
context.stroke();
} else if (current == "+") {
context.translate(x, y);
context.rotate((20 * Math.PI) / 180);
context.translate(-x, -y);
} else if (current == "-") {
context.translate(x, y);
context.rotate((-20 * Math.PI) / 180);
context.translate(-x, -y);
} else if (current == "[") {
context.save();
y_stack.push(y);
} else if (current == "]") {
context.restore();
y = y_stack.pop();
context.moveTo(x, y)
}
}
}
function generate(sentence){
var nextSentence = "";
for (var i = 0; i < sentence.length; i++) {
var current = sentence.charAt(i);
var found = false;
for (var j = 0; j < rules.length; j++ ) {
if (current == rules[j].a) {
found = true;
nextSentence += rules[j].b;
break;
}
}
if (!found) {
nextSentence += current;
}
}
return nextSentence;
}
function turtle2(sentence2, context){
for (var i = 0; i < sentence2.length; i++) {
var current = sentence2.charAt(i);
if (current == "F") {
y -= 20;
context.lineTo(x, y);
context.stroke();
} else if (current == "+") {
context.translate(x, y);
context.rotate((22.5 * Math.PI) / 180);
context.translate(-x, -y);
} else if (current == "-") {
context.translate(x, y);
context.rotate((-22.5 * Math.PI) / 180);
context.translate(-x, -y);
} else if (current == "[") {
context.save();
y_stack2.push(y);
} else if (current == "]") {
context.restore();
y = y_stack2.pop();
context.moveTo(x, y)
}
}
}
function generate2(sentence2){
var nextsentence2 = "";
for (var i = 0; i < sentence2.length; i++) {
var current = sentence2.charAt(i);
var found = false;
for (var j = 0; j < rulesB.length; j++ ) {
if (current == rulesB[j].a) {
found = true;
nextsentence2 += rulesB[j].b;
break;
}
}
if (!found) {
nextsentence2 += current;
}
}
return nextsentence2;
}
function draw() {
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext('2d');
// context.moveTo(x, y);
for (i = 0; i < 2; i++) {
sentence = generate(sentence);
}
console.log(sentence);
turtle(sentence, context);
//context.moveTo(100,400);
for(i = 0; i < 2; i++) {
sentence2 = generate2(sentence2);
}
console.log(sentence2);
turtle2(sentence2, context);
}
/*
function turtle3(){
//resetMatrix();
context.translate(width/6, height);
for (var n = 0; n < sentence3.length; n++){
var current = sentence3.charAt(n);
if (current == "F"){
context.stroke("#28b232");
context.lineTo(0, -len3);
context.translate(0, -len3);
}else if (current == "X"){
context.stroke("#024d08");
context.lineTo(-len3, 0);
context.translate(0, -len3);
}else if (current == "+"){
context.rotate(angle2);
}else if (current == "-"){
context.rotate(-angle2);
}else if (current == "["){
save();
}else if (current == "]"){
restore();
}
}
}
*/
/*
function generate3(){
len2 *= .5;
var nextSentence3 = "";
for (var i = 0; i < sentence3.length; i++){
var current3 = sentence3.charAt(i);
var found3 = false;
for (var j = 0; j < rulesC.length; j++ ){
if (current3 == rulesC[j].a){
found3 = true;
nextSentence3 += rulesC[j].b;
break;
}
}
if (!found3){
nextSentence3 += current3;
}
}
sentence3 = nextSentence3;
turtle3();
}*/

Related

How can I make this collision detection possible?

I'm using a number of boxes that are floating around the screen, I want for them to bounce away from each other when they collide and I am testing this by just changing their colours instead when they collide, for some reason their colour changes at the start(their starting colour is white and if they collide it should change to red but they start and stays red). Is there something I am doing wrong? I would also like for everything to be done within the constructor function. I am sorry for not commenting my code as yet.
function BoxSplash()
{
this.sample = [];
var test = false;
this.col = color(129)
this.changeColour = function()
{
this.col = color(random(0,255),random(0,128),random(0,255))
}
this.intersect = function(other)
{
for(var i = 0; i < numberss; i++)
{ var currentBox = this.sample[i]
var d = dist(currentBox.x,currentBox.y,other.x,other.y)
if(d < currentBox.width + other.width)
{
return true;
}
else
{
return false
}
}
noLoop()
}
this.draw = function()
{
stroke(255)
line(0,windowHeight/2,windowWidth,windowHeight/2)
stroke(0)
for(var i = 0; i < numberss; i++)
{
var box = {
x:random(0,windowWidth - 50),
y:random(windowHeight/2 ,windowHeight - 50),
width:50,
height:50,
speedX:random(1,5),
speedY:random(1,5)
}
this.sample.push(box)
}
//use numberss variable to work with gui
for(var i = 0; i < numberss; i++)
{
fill(this.col)
rect(this.sample[i].x,this.sample[i].y,50,50)
}
this.move()
}
this.move = function()
{
for(var i = 0; i < numberss; i++)
{
var shape = this.sample[i]
shape.x += shape.speedX
shape.y += shape.speedY
if(shape.x + shape.width >= windowWidth || shape.x <= 0 )
{
shape.speedX = -shape.speedX
}
if(shape.y + shape.height >= windowHeight || shape.y <= windowHeight/2)
{
shape.speedY = -shape.speedY;
}
for(var j = 0; j < numberss; j++)
{
var others = this.sample[j]
var d = dist(shape.x,shape.y,others.x,others.y)
if( i != j && d < shape.width + others.width)
{
test = true;
}
else
{
test = false
}
if(test)
{
this.col = color(255,0,0)
}
}
}
}
}
You should visit this link and transform their circles into your boxes.
1st: Calculate dist(object1.x, object.y, object2.x, object2.y) and save into a variable called d
2nd:
if (d < object1.h + object2.h) {
// Enter your code here
}

Despite using an array for keydown (or keyup) functions my code still refuses to let me move while jumping

My code is as follows:
var map = [];
document.body.onkeydown = document.body.onkeyup = function(e){
e = e || event; // to deal with IE
map[e.key] = e.type == 'keydown';
console.log(map)
if (map["ArrowLeft"]) {move("left")}
if (map["ArrowRight"]) {move("right")}
if (map["Spacebar"] || map[" "]) {jump()};
However if i hold down the right arrow key and then press space the character jumps without changing the x pos.
My jumping code is:
async function jump() {
var jh = j;
var i;
for (i = jh * 2; i > -Math.abs(jh) * 2 - 0.5; i -= 0.5) {
rem_rect(70, py, 30, 30)
py -= i
rect(70, py, 30, 30)
await sleep(15)
}
}
My moving code is:
async function move(d) {
var i;
for (i = 0; i < p.length; i++) {
if (d === "right") {
var j;
for (j = 0; j <= 5; j++) {
rem_rect(p[i][0], p[i][1], p[i][2], p[i][3]);
p[i][0] -= ms / 5;
rect(p[i][0], p[i][1], p[i][2], p[i][3])
await sleep(0)
}
}
else if (d === "left") {
var j;
for (j = 0; j <= 5; j++) {
rem_rect(p[i][0], p[i][1], p[i][2], p[i][3]);
p[i][0] += ms / 5;
rect(p[i][0], p[i][1], p[i][2], p[i][3])
await sleep(0)
}
}
}
}

player.js:1 Uncaught SyntaxError: Identifier 'Player' has already been declared laravel-6

i have an laravel project and just implemented some scripts in it
and i keep gettinf this error
Uncaught SyntaxError: Identifier 'Player' has already been declared
at player.js:1
Uncaught SyntaxError: Identifier 'canvas' has already been declared
at tetris.js:1
i only get this error while working with laravel because the code works in a normal html file.
this is my javascript:
player.js
class Player
{
constructor()
{
this.pos = {x:0,y:0};
this.matrix = null;
this.score = 0;
}
}
tetris.jsconst canvas = document.getElementById('tetris');
const context = canvas.getContext('2d');
context.scale(20, 20);
context.fillStyle = '#000';
context.fillRect(0, 0, canvas.width, canvas.height);
context.strokeStyle = '#cbc7ca';
context.strokeRect(0,0, canvas.width, canvas.height);
function arenaSweep() {
let rowCount = 1
outer: for(let y = arena.length - 1; y > 0; --y) {
for(let x = 0; x < arena[y].length; ++x) {
if(arena[y][x] === 0){
continue outer;
}
}
const row = arena.splice(y, 1)[0].fill(0);
arena.unshift(row);
++y;
player.score += rowCount * 10;
rowCount *= 2;
}
}
function collide(arena, player){
const [m, o] = [player.matrix, player.pos];
for(let y = 0; y < m.length; ++y) {
for(let x = 0; x < m[y].length; ++x){
if(m[y][x] !== 0 &&
(arena[y + o.y] &&
arena[y + o.y][x + o.x]) !== 0)
return true;
}
}
return false;
}
function createMatrix(w, h){
const matrix = [];
while( h--) {
matrix.push(new Array(w).fill(0));
}
return matrix
}
function draw() {
context.fillStyle = '#000';
context.fillRect(0, 0, canvas.width, canvas.height);
drawMatrix(arena, {x:0, y:0});
drawMatrix(player.matrix, player.pos );
}
function createPiece(type) {
if( type === 'T'){
return [
[0,0,0],
[1,1,1],
[0,1,0],
];
}
else if(type === 'O'){
return [
[2,2],
[2,2]
];
}
else if( type === 'L'){
return [
[0,3,0],
[0,3,0],
[0,3,3],
];
}
else if( type === 'J'){
return [
[0,4,0],
[0,4,0],
[4,4,0],
];
}
else if( type === 'I'){
return [
[0,5,0,0],
[0,5,0,0],
[0,5,0,0],
[0,5,0,0],
];
}
else if( type === 'Z'){
return [
[6,6,0],
[0,6,6],
[0,0,0],
];
}
else if( type === 'S'){
return [
[0,7,7],
[7,7,0],
[0,0,0],
];
}
}
function drawMatrix(matrix, offset){
matrix.forEach((row, y) => {
row.forEach((value, x) => {
if(value !== 0) {
context.fillStyle = colors[value];
context.fillRect(x + offset.x,
y + offset.y,
1,1);
}
});
});
}
function merge(arena, player) {
player.matrix.forEach((row, y) => {
row.forEach((value, x) => {
if(value !== 0) {
arena[y + player.pos.y][x + player.pos.x] = value;
}
});
});
}
function playerDrop() {
player.pos.y++;
if(collide(arena, player)) {
player.pos.y--;
merge(arena,player);
playerReset();
arenaSweep();
updateScore();
}
dropCounter = 0;
}
function playerMove(dir) {
player.pos.x += dir;
if(collide(arena, player)) {
player.pos.x -= dir;
}
}
function playerReset() {
const pieces = 'ILJOSZ';
player.matrix = createPiece(pieces[pieces.length * Math.random() | 0]);
player.pos.y = 0;
player.pos.x = (arena[0].length / 2 | 0) -
(player.matrix[0].length / 2 | 0);
if(collide(arena,player)) {
arena.forEach(row => row.fill(0));
player.score = 0;
playerReset();
}
}
function playerRotate(dir){
const pos = player.pos.x;
let offset = 1;
rotate(player.matrix, dir);
while (collide(arena, player)) {
player.pos.x += offset;
offset = -(offset +(offset > 0 ? 1 : -1 ));
if(offset > player.matrix[0].length) {
rotate(player.matrix, -dir);
player.pos.x = pos;
return;
}
}
}
function rotate(matrix, dir){
for(let y = 0; y < matrix.length;++y) {
for(let x = 0; x < y; ++x) {
[
matrix[x][y],
matrix[y][x],
] = [
matrix[y][x],
matrix[x][y],
];
}
}
if(dir > 0){
matrix.forEach(row => row.reverse());
}else{
matrix.reverse();
}
}
let dropCounter = 0;
let dropInterval = 1000;
let lasttime = 0;
function update(time = 0) {
const deltaTime = time - lasttime;
lasttime = time;
dropCounter += deltaTime;
if(dropCounter > dropInterval){
playerDrop();
}
draw();
requestAnimationFrame(update);
}
function updateScore() {
document.getElementById('score').innerText = player.score;
}
const colors =[
null,
'purple',
'yellow',
'orange',
'blue',
'cyan',
'red',
'green',
];
const arena = createMatrix(12, 20);
const player = new Player;
document.addEventListener('keydown', event => {
if (event.keyCode === 37){
playerMove(-1);
}
else if(event.keyCode === 39){
playerMove(1);
}
else if(event.keyCode === 40){
playerDrop();
}
else if(event.keyCode === 90) {
playerRotate(-1);
}
else if(event.keyCode === 88) {
playerRotate(1);
}
})
playerReset();
updateScore();
update();
this is my blade template:
#section('content')
<div id="score">0</div>
<canvas id="tetris" width="240" height="400"></canvas>
<script type="application/javascript" src="{{asset('js/player.js')}}"></script>
<script type="application/javascript" src="{{asset('js/tetris.js')}}"></script>
#endsection`

Percularities with p5 pixel fill

I'm using the p5.js library.
I'm making a program that is meant to automatically fill closed spaces but I'm having a problem.
Sometimes the program fills half closed loops and I can't figure out why.
If anyone could help me identify the problem I will fix it myself.
Here is an example of that problem:
You have to zoom in a lot or it breaks (on a side note if you know how to scale up the pixels that would also be great)
let pixelVals;
let checkedPixels;
let filledPixels;
let iter = 0;
let drawFilled;
function setup() {
pixelVals = array(height, width, 4);
createCanvas(25, 25);
pixelDensity(1);
for(var i = 0; i < width; i++) {
for(var j = 0; j < height; j++) {
pixelVals[i][j][0] = 0;
pixelVals[i][j][1] = 0;
pixelVals[i][j][2] = 0;
pixelVals[i][j][3] = 255;
}
}
}
function draw() {
loadPixels();
for(var i = 0; i < width; i++) {
for(var j = 0; j < height; j++) {
pixelVals[i][j][1] = 0;
}
}
if(mouseIsPressed) {
if(mouseX < width && mouseX >= 0 && mouseY < height && mouseY >= 0) {
pixelVals[mouseX][mouseY][0] = 255;
}
}
checkEnclosed();
updatePixels();
}
function checkEnclosed() {
checkedPixels = array(height, width);
filledPixels = array(height, width);
for(var i = 0; i < width; i++) {
for(var j = 0; j < height; j++) {
checkedPixels[i][j] = false;
filledPixels[i][j] = false;
}
}
for(var i = 0; i < height; i++) {
for(var j = 0; j < width; j++) {
if(!checkedPixels[i][j] && pixelVals[i][j][0] != 255) {
drawFilled = true;
checkSurroundings(i, j);
if(drawFilled) {
setFilled();
} else {
setFilledFalse();
}
}
}
}
for(var i = 0; i < width; i++) {
for(var j = 0; j < height; j++) {
for(var k = 0; k < 4; k++) {
pixels[(i + j * width) * 4 + k] = pixelVals[i][j][k];
}
}
}
}
function checkSurroundings(x, y) {
pixelVals[x][y][1] = 255;
filledPixels[x][y] = true;
checkedPixels[x][y] = true;
if(x == width - 1 || x == 0 || y == height - 1 || y == 0) {
drawFilled = false;
} else {
if(x + 1 < width) {
if(pixelVals[x + 1][y][0] != 255) {
if(!checkedPixels[x + 1][y]) {
checkSurroundings(x + 1, y)
}
}
}
if(x - 1 >= 0) {
if(pixelVals[x - 1][y][0] != 255) {
if(!checkedPixels[x - 1][y]) {
checkSurroundings(x - 1, y)
}
}
}
if(y + 1 < height) {
if(pixelVals[x][y + 1][0] != 255) {
if(!checkedPixels[x][y + 1]) {
checkSurroundings(x, y + 1)
}
}
}
if(y - 1 >= 0) {
if(pixelVals[x][y - 1][0] != 255) {
if(!checkedPixels[x][y - 1]) {
checkSurroundings(x, y - 1)
}
}
}
}
}
function setFilled() {
for(var i = 0; i < width; i++) {
for(var j = 0; j < height; j++) {
if(filledPixels[i][j]) {
pixelVals[i][j][2] = 255;
}
}
}
}
function setFilledFalse() {
for(var i = 0; i < width; i++) {
for(var j = 0; j < height; j++) {
filledPixels[i][j] = false;
}
}
}
function array(length) {
var arr = new Array(length || 0), i = length;
if (arguments.length > 1) {
var args = Array.prototype.slice.call(arguments, 1);
while(i--) arr[length-1 - i] = array.apply(this, args);
}
return arr
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.2/p5.js"></script>
I'm new to JavaScript so ignore the messy code :).
let pixelVals;
let checkedPixels;
let filledPixels;
let iter = 0;
let drawFilled;
function setup() {
pixelVals = array(height, width, 4);
createCanvas(25, 25);
pixelDensity(1);
for(var i = 0; i < width; i++) {
for(var j = 0; j < height; j++) {
pixelVals[i][j][0] = 0;
pixelVals[i][j][1] = 0;
pixelVals[i][j][2] = 0;
pixelVals[i][j][3] = 255;
}
}
}
function draw() {
loadPixels();
for(var i = 0; i < width; i++) {
for(var j = 0; j < height; j++) {
pixelVals[i][j][1] = 0;
}
}
if(mouseIsPressed) {
if(mouseX < width && mouseX >= 0 && mouseY < height && mouseY >= 0) {
pixelVals[mouseX][mouseY][0] = 255;
}
}
checkEnclosed();
updatePixels();
}
function checkEnclosed() {
checkedPixels = array(height, width);
filledPixels = array(height, width);
for(var i = 0; i < width; i++) {
for(var j = 0; j < height; j++) {
checkedPixels[i][j] = false;
filledPixels[i][j] = false;
}
}
for(var i = 0; i < height; i++) {
for(var j = 0; j < width; j++) {
if(!checkedPixels[i][j] && pixelVals[i][j][0] != 255) {
drawFilled = true;
checkSurroundings(i, j);
if(drawFilled) {
setFilled();
} else {
setFilledFalse();
}
}
}
}
for(var i = 0; i < width; i++) {
for(var j = 0; j < height; j++) {
for(var k = 0; k < 4; k++) {
pixels[(i + j * width) * 4 + k] = pixelVals[i][j][k];
}
}
}
}
function checkSurroundings(x, y) {
pixelVals[x][y][1] = 255;
filledPixels[x][y] = true;
checkedPixels[x][y] = true;
if(x == width - 1 || x == 0 || y == height - 1 || y == 0) {
drawFilled = false;
} else {
if(x + 1 < width) {
if(pixelVals[x + 1][y][0] != 255) {
if(!checkedPixels[x + 1][y]) {
checkSurroundings(x + 1, y)
}
}
}
if(x - 1 >= 0) {
if(pixelVals[x - 1][y][0] != 255) {
if(!checkedPixels[x - 1][y]) {
checkSurroundings(x - 1, y)
}
}
}
if(y + 1 < height) {
if(pixelVals[x][y + 1][0] != 255) {
if(!checkedPixels[x][y + 1]) {
checkSurroundings(x, y + 1)
}
}
}
if(y - 1 >= 0) {
if(pixelVals[x][y - 1][0] != 255) {
if(!checkedPixels[x][y - 1]) {
checkSurroundings(x, y - 1)
}
}
}
}
}
function setFilled() {
for(var i = 0; i < width; i++) {
for(var j = 0; j < height; j++) {
if(filledPixels[i][j]) {
pixelVals[i][j][2] = 255;
}
}
}
}
function setFilledFalse() {
for(var i = 0; i < width; i++) {
for(var j = 0; j < height; j++) {
filledPixels[i][j] = false;
}
}
}
function array(length) {
var arr = new Array(length || 0), i = length;
if (arguments.length > 1) {
var args = Array.prototype.slice.call(arguments, 1);
while(i--) arr[length-1 - i] = array.apply(this, args);
}
return arr
}
Much appreciated,
Zac
This was my solution by changing the checkSurroundings function:
function checkSurroundings(x, y) {
pixelVals[x][y][1] = 255;
filledPixels[x][y] = true;
checkedPixels[x][y] = true;
if(x == width - 1 || x == 0 || y == height - 1 || y == 0) {
drawFilled = false;
}
if(x + 1 < width) {
if(pixelVals[x + 1][y][0] != 255) {
if(!checkedPixels[x + 1][y]) {
checkSurroundings(x + 1, y)
}
}
}
if(x - 1 >= 0) {
if(pixelVals[x - 1][y][0] != 255) {
if(!checkedPixels[x - 1][y]) {
checkSurroundings(x - 1, y)
}
}
}
if(y + 1 < height) {
if(pixelVals[x][y + 1][0] != 255) {
if(!checkedPixels[x][y + 1]) {
checkSurroundings(x, y + 1)
}
}
}
if(y - 1 >= 0) {
if(pixelVals[x][y - 1][0] != 255) {
if(!checkedPixels[x][y - 1]) {
checkSurroundings(x, y - 1)
}
}
}
}
let pixelVals;
let checkedPixels;
let filledPixels;
let iter = 0;
let drawFilled;
function setup() {
pixelVals = array(height, width, 4);
createCanvas(25, 25);
pixelDensity(1);
for(var i = 0; i < width; i++) {
for(var j = 0; j < height; j++) {
pixelVals[i][j][0] = 0;
pixelVals[i][j][1] = 0;
pixelVals[i][j][2] = 0;
pixelVals[i][j][3] = 255;
}
}
}
function draw() {
loadPixels();
for(var i = 0; i < width; i++) {
for(var j = 0; j < height; j++) {
pixelVals[i][j][1] = 0;
}
}
if(mouseIsPressed) {
if(mouseX < width && mouseX >= 0 && mouseY < height && mouseY >= 0) {
pixelVals[mouseX][mouseY][0] = 255;
}
}
checkEnclosed();
updatePixels();
}
function checkEnclosed() {
checkedPixels = array(height, width);
filledPixels = array(height, width);
for(var i = 0; i < width; i++) {
for(var j = 0; j < height; j++) {
checkedPixels[i][j] = false;
filledPixels[i][j] = false;
}
}
for(var i = 0; i < height; i++) {
for(var j = 0; j < width; j++) {
if(!checkedPixels[i][j] && pixelVals[i][j][0] != 255) {
drawFilled = true;
checkSurroundings(i, j);
if(drawFilled) {
setFilled();
} else {
setFilledFalse();
}
}
}
}
for(var i = 0; i < width; i++) {
for(var j = 0; j < height; j++) {
for(var k = 0; k < 4; k++) {
pixels[(i + j * width) * 4 + k] = pixelVals[i][j][k];
}
}
}
}
function checkSurroundings(x, y) {
pixelVals[x][y][1] = 255;
filledPixels[x][y] = true;
checkedPixels[x][y] = true;
if(x == width - 1 || x == 0 || y == height - 1 || y == 0) {
drawFilled = false;
}
if(x + 1 < width) {
if(pixelVals[x + 1][y][0] != 255) {
if(!checkedPixels[x + 1][y]) {
checkSurroundings(x + 1, y)
}
}
}
if(x - 1 >= 0) {
if(pixelVals[x - 1][y][0] != 255) {
if(!checkedPixels[x - 1][y]) {
checkSurroundings(x - 1, y)
}
}
}
if(y + 1 < height) {
if(pixelVals[x][y + 1][0] != 255) {
if(!checkedPixels[x][y + 1]) {
checkSurroundings(x, y + 1)
}
}
}
if(y - 1 >= 0) {
if(pixelVals[x][y - 1][0] != 255) {
if(!checkedPixels[x][y - 1]) {
checkSurroundings(x, y - 1)
}
}
}
}
function setFilled() {
for(var i = 0; i < width; i++) {
for(var j = 0; j < height; j++) {
if(filledPixels[i][j]) {
pixelVals[i][j][2] = 255;
}
}
}
}
function setFilledFalse() {
for(var i = 0; i < width; i++) {
for(var j = 0; j < height; j++) {
filledPixels[i][j] = false;
}
}
}
function array(length) {
var arr = new Array(length || 0), i = length;
if (arguments.length > 1) {
var args = Array.prototype.slice.call(arguments, 1);
while(i--) arr[length-1 - i] = array.apply(this, args);
}
return arr
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.2/p5.js"></script>

Trying to create tetris, but can't

For some reason my code refuses to let me assign an x and y position to each block. Each block is 30 pixels wide and tall and will be colored according to which piece it is a part of. Gravity and a clear function haven't been implemented and the move left and move right function are so different because it wasn't working right and then recreated it as it is seen now in the left function and it works less...
Please help!
Edit: My apologies, i dont normally post anything. The part i cant get past now is function block/add block/typeSet/assigning the type. it assigns a random one pretty well but then when that type (such as square) goes to assign x and y values it gives an error.
<!DOCTYPE html>
<html>
<head>
<title>Tetris in Canvas</title>
<style type="text/css">
canvas {
border: solid 1px black;
margin: -8px;
}
</style>
<script type="text/javascript">
var canvas = null;
var ctx = null;
var blockArray = [];
var board = [];
var blockNum = 0;
for (var s = 0; s < 14; s++) {
board[s] = [27];
for (var t = 0; t < 27; t++) {
board[s][t] = -1;
}
}
document.onkeydown = function(event) {
var keyCode;
if(event == null)
keyCode = window.event.keyCode;
else
keyCode = event.keyCode;
switch(keyCode) {
case 37:
left(blockArray.length);
break;
case 38:
up(blockArray.length);
break;
case 39:
right(blockArray.length);
break;
case 40:
down(blockArray.length);
break;
default:
break;
}
}
window.onload = function init() {
canvas = document.getElementById('Canvas1');
ctx = canvas.getContext("2d");
blank();
addBlock();
animate();
}
function up(i) {
blank();
animate();
}
function down(i) {
var u = 0;
var p = 0;
while(u<4) {
if (blockArray[i].y[u] + 1 > 26) {
u = 10;
}
else if ((board[blockArray[i].x[u]][blockArray[i].y[u] + 1]) == -1) {
u++;
}
else {
p = u;
for (var g = 0; ((g < 4) && (p = u)); g++) {
if ((blockArray[i].x[u] == blockArray[i].x[g]) && (blockArray[i].y[u] + 1 == blockArray[i].y[g])) {
u++;
}
}
if (p == u)
u = 10;
}
}
if (u < 10) {
for (var j=0; j<4; j++) {
blockArray[i].y[j] +=1;
}
}
else
addBlock();
animate();
}
function right(i) {
var u = 0;
var p = 0;
while(u<4) {
if (blockArray[i].x[u] + 1 > 13) {
u = 10;
}
else if ((board[blockArray[i].x[u] + 1][blockArray[i].y[u]]) == -1)
u++;
else {
p = u;
for (var g = 0; ((g < 4) && (p = u)); g++) {
if ((blockArray[i].x[u] + 1 == blockArray[i].x[g]) && (blockArray[i].y[u] == blockArray[i].y[g]))
u++;
}
if (p == u)
u = 10;
}
}
if (u < 10) {
for (var j=0; j<4; j++) {
blockArray[i].x[j] +=1;
}
}
else
addBlock();
animate();
}
function left(i) {
var u;
var p = 14;
for (var w = 0; w<4; w++) {
if (blockArray[i].x[w] < p) {
p = blockArray[i].x[w];
u = w;
}
}
if (p > 0) {
if ((board[blockArray[i].x[u] - 1][blockArray[i].y[u]]) == -1) {
for (var j=0; j<4; j++) {
blockArray[i].x[j] -=1;
}
}
}
animate();
}
function block(x, y, type) {
blockNum += 1;
this.id = blockNum;
this.x = [];
this.y = [];
this.landed = false;
this.type = Math.floor(Math.random() * (6)) + 1;
typeSet(this.type);
}
function addBlock() {
blockArray[blockArray.length] = new block();
}
function typeSet(type) {
i = blockArray.length;
switch (type) {
case 1:
square(i);
break;
case 2:
elR(i);
break;
case 3:
elL(i);
break;
case 4:
line(i);
break;
case 5:
zeR(i);
break;
case 6:
zeL(i);
break;
default:
break;
}
}
function animate() {
fillBoard();
colorBoard();
}
function fillBoard() {
for (var i = 0; i < 14; i++) {
for (var q = 0; q < 27; q++) {
board[i][q] = -1;
}
}
for (var i=0; i<blockArray.length; i++) {
for (var q=0; q<4; q++) {
board[blockArray[i].x[q]][blockArray[i].y[q]] = blockArray[i].type;
}
}
}
function colorBoard() {
blank();
ctx.strokeStyle = "white";
for(var q=0; q<14; q++) {
for(var r=0; r<27; r++) {
switch (board[q][r]) {
case 1:
ctx.fillStyle = "green";
color(q,r);
break;
case 2:
ctx.fillStyle = "orange";
color(q,r);
break;
case 3:
ctx.fillStyle = "cyan";
color(q,r);
break;
case 4:
ctx.fillStyle = "black";
color(q,r);
break;
case 5:
ctx.fillStyle = "yellow";
color(q,r);
break;
case 6:
ctx.fillStyle = "brown";
color(q,r);
break;
default:
break;
}
}
}
}
function color(q,r) {
ctx.fillRect(q*30,(r-4)*30,30,30);
ctx.strokeRect(q*30,(r-4)*30,30,30);
}
function square(i) {
blockArray[i].x[0] = 7;
blockArray[i].y[0] = 0;
blockArray[i].x[1] = 7;
blockArray[i].y[1] = 1;
blockArray[i].x[2] = 8;
blockArray[i].y[2] = 0;
blockArray[i].x[3] = 8;
blockArray[i].y[3] = 1;
}
function elR(i) {
blockArray[i].x[0] = 7;
blockArray[i].y[0] = 0;
blockArray[i].x[1] = 7;
blockArray[i].y[1] = 1;
blockArray[i].x[2] = 7;
blockArray[i].y[2] = 2;
blockArray[i].x[3] = 8;
blockArray[i].y[3] = 2;
}
function elL(i) {
blockArray[i].x[0] = 7;
blockArray[i].y[0] = 0;
blockArray[i].x[1] = 7;
blockArray[i].y[1] = 1;
blockArray[i].x[2] = 7;
blockArray[i].y[2] = 2;
blockArray[i].x[3] = 6;
blockArray[i].y[3] = 2;
}
function line(i) {
blockArray[i].x[0] = 7;
blockArray[i].y[0] = 0;
blockArray[i].x[1] = 7;
blockArray[i].y[1] = 1;
blockArray[i].x[2] = 7;
blockArray[i].y[2] = 2;
blockArray[i].x[3] = 7;
blockArray[i].y[3] = 3;
}
function zeR(i) {
blockArray[i].x[0] = 6;
blockArray[i].y[0] = 0;
blockArray[i].x[1] = 7;
blockArray[i].y[1] = 0;
blockArray[i].x[2] = 7;
blockArray[i].y[2] = 1;
blockArray[i].x[3] = 8;
blockArray[i].y[3] = 1;
}
function zeL(i) {
blockArray[i].x[0] = 8;
blockArray[i].y[0] = 0;
blockArray[i].x[1] = 7;
blockArray[i].y[1] = 0;
blockArray[i].x[2] = 7;
blockArray[i].y[2] = 1;
blockArray[i].x[3] = 6;
blockArray[i].y[3] = 1;
}
function blank() {
ctx.restore();
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.save();
}
function blank2() {
ctx.restore();
ctx.fillStyle = "purple";
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.save();
}
function rotateImgRight() {
for(d = 0; d < 180; d++) {
setTimeout(rotateImg, 50);
}
}
function rotateImgLeft() {
for(d = 0; d < 180; d++) {
setTimeout(rotateImg2, 50);
}
}
function rotateImg2() {
degrees = degrees - 0.5;
radian = (Math.PI / 180.0) * degrees;
blank();
ctx.translate(ctx.canvas.width/2, 700);
ctx.rotate(radian);
ctx.drawImage(srcImg, -srcImg.width/2,-srcImg.height/2);
slide = (degrees / 90) % 4;
}
function rotateImg(x,y) {
degrees = degrees + 0.5;
radian = (Math.PI / 180.0) * degrees;
ctx.translate(x,y);
ctx.rotate(radian);
ctx.drawImage(srcImg, -srcImg.width/2,-srcImg.height/2);
slide = (degrees / 90) % 4;
}
</script>
</head>
<body>
<div style="width: 100%; text-align:center">
<canvas id="Canvas1" width="421" height="690">Your browser does not support canvas.</canvas>
</div>
</body>
</html>
Your function addBlock looks like this:
function addBlock() {
blockArray[blockArray.length] = new block();
}
At any arbitrary point, your blockArray length could be anything. For now let's assume it's 25.
You're inserting a block to the 25th position in the array.
Let's have a look at the block function:
function block(x, y, type) {
blockNum += 1;
this.id = blockNum;
this.x = [];
this.y = [];
this.landed = false;
this.type = Math.floor(Math.random() * (6)) + 1;
typeSet(this.type);
}
What's this typeSet command? It doesn't look like it sets anything! Let's investigate:
function typeSet(type) {
i = blockArray.length;
switch (type) {
case 1:
square(i);
break;
// blah
}
}
AHA! I've found the problem, square() goes to the blockArray at position i, which doesn't even exist yet as block() hasn't finished executing, and assigns loads of x and y variables all over the place. When block() finishes executing, it overwrites all the values that typeSet() has just written.
You need to refactor your typeSet() method so that it takes in the actual block object and sets the x and y values on that rather than trying to access the element within the array (which doesn't even exist yet):
typeSet(this, this.type);
you can start by checking if the arrays actually contain the items you think they contain
for example, in your left method, instead of this:
for (var w = 0; w<4; w++) {
if (blockArray[i].x[w] < p) {
p = blockArray[i].x[w];
u = w;
}
}
do this:
for (var w = 0; w<4; w++) {
if ((blockArray[i]) && (blockArray[i].x[w])) {
if (blockArray[i].x[w] < p) {
p = blockArray[i].x[w];
u = w;
}
}
}
it seems as though the array is not fully populated and only done so at runtime, this can lead to undefined references.
PS: i have not fully read the code; only part of it, as it is a lot to work through.

Categories