Tarvitsisin apua Javascript koodauksessa

Olen tehnyt tässä lähiaikoina YouTuben tutoriaalien avulla kehittynyttä Tetristä, mutta se ei vain toimi millään. Käytän Microsoftin Microsoft Expression 4 Webiä koodaamiseen. Nettisivuun käytän HTML5 :ttä. HTML5 ei hyväksy data-mainia. Toivoisin, että joku voisi auttaa minua tässä.

styles.css(2.1) :

canvas {
border: 1px solid #000;
}

Block.js:

define(function() {

var DrawIDs = {
NONE: 0,
I: 1,
Z: 2,
J: 3,
L: 4,
S: 5,
O: 6,
T: 7
}

var Block = Class.extend({

init: function(id) {
this.setType(id || "none");
},

setType: function(id) {
this.ID = typeof id === "number" ? id : DrawIDs[id.toUpperCase()];
this.solid = this.ID !== DrawIDs.NONE;
}
});

for (var id in DrawIDs) {
Block[id] = DrawIDs[id];
}

return Block;

});

class.js:

/* Simple JavaScript Inheritance
* By John Resig http://ejohn.org/
* MIT Licensed.
*/
// Inspired by base2 and Prototype
(function(){
var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;

// The base Class implementation (does nothing)
this.Class = function(){};

// Create a new Class that inherits from this class
Class.extend = function(prop) {
var _super = this.prototype;

// Instantiate a base class (but only create the instance,
// don't run the init constructor)
initializing = true;
var prototype = new this();
initializing = false;

// Copy the properties over onto the new prototype
for (var name in prop) {
// Check if we're overwriting an existing function
prototype[name] = typeof prop[name] == "function" &&
typeof _super[name] == "function" && fnTest.test(prop[name]) ?
(function(name, fn){
return function() {
var tmp = this._super;

// Add a new ._super() method that is the same method
// but on the super-class
this._super = _super[name];

// The method only need to be bound temporarily, so we
// remove it when we're done executing
var ret = fn.apply(this, arguments);
this._super = tmp;

return ret;
};
})(name, prop[name]) :
prop[name];
}

// The dummy class constructor
function Class() {
// All construction is actually done in the init method
if ( !initializing && this.init )
this.init.apply(this, arguments);
}

// Populate our constructed prototype object
Class.prototype = prototype;

// Enforce the constructor to be what we expect
Class.prototype.constructor = Class;

// And make this class extendable
Class.extend = arguments.callee;

return Class;
};
})();
Ilmoita


engine.js:

var canvas, content, input;
(function() {

canvas = (function() {

var c = {},

frame = document.getElementsByTagName("canvas")[0],
_fctx = frame.getContext("2d")

view = document.createElement("canvas")
ctx = view.getContext("2d")

_fw, _fh, _vw, _vh, _scale = 1;

c.frame = frame;
c.view = view;
c.ctx = ctx;

c.flip = function() {
_fctx.clearRect(0, 0, _fw, _fh,);
_fctx drawImage(this.view, 0, 0, _fw _fh);

this.ctx.clearRect(0,0, _vw, _vh);
}

Object.defineProperty(c, "width", {
set: function(w) {
this.view.width = w;
this.scale = _scale;
},
get: function()
return _vw;
}
});
Object.defineProperty(c, "height", {
set: function(h) {
this.view.height = h;
this.scale = _scale;
},
get: function()
return _vh;
}
});
Object.defineProperty(c, "scale", {
set: function(s) {
_scale =s;
_vw = this.view.width;
_vh = this.view.height;
_fw = this.frame.width = _vw * s;
_fh = this.frame.height = _vh * s;

_fctx["imageSmoothingEnabled"] = false;
["o", "ms", "moz", "webkit",].forEach(function (v) {
_fctx[v "imageSmoothingEnabled"] = false;
});
},
get: function()
return _scale;0
}
});

c.scale = _scale;

return c;
})();

content = (function() {

var c = {},

_files = {}
_filecount = 0,
_loadcount = 0;

c.get = function(name) {
return _files[name];
}

c.progress = function() {
return _loadcount/_filecount;
}

c.load = function(name, src) {

src = src || name;

_filecount ;

switch (src.split(".").pop()) {

case "png":
case "gif":
case "jpg":
var img = new Image();
img.onload = function() {
_loadcount ;
}
img.src = src;
_files[name] = img;
break;

case "ogg":
case "mp3":
case "wav":
break;

case "json":
case "tmx":
break;
}
}

return c;

}();

input = (function() {

var i = {},

_bindings = {},
_pressed = {},
_down = {},
_released = [],

mouse = { x: 0, y: 0 };

i.mouse = mouse;

var Buttons = {
LEFT: -1,
MIDDLE: -2,
RIGHT: -3
}

var Keys = {
SPACE: 32,
LEFT_ARROW: 37,
UP_ARROW: 38,
RIGHT_ARROW: 39,
DOWN_ARROW: 40
}

for (var ch = 65; ch <= 90; ch ) {
Keys[String.fromCharCode(ch)] = c
Ilmoita
engine.js: jatkuuu...
}

i.Buttons = Buttons;
i.Keys = Keys;

i.bindKey = function(action, keys) {
if (typeof keys === "number") {
_bindings[keys] = action;
return;
}
for (var i = 0; i < keys.length; i ) {
_bindings[keys[i]] = action;
}
}

function _getCode(e) {
var t = e.type;
if (t === "keydown" || t === "keyup") {
return e.keyCode;
} else if (t === "mousedown" || t === "mouseup") {
switch (e.button) {
case 0:
return Buttons.LEFT;
case 1:
return Buttons.MIDDLE;
case 2:
return Buttons.RIGHT;
}
}
}

function ondown(e) {
var action = _bindings[_getCode(e)];
if (!action) return;
_pressed[action] = !_down[action];
_down[action] = true;
e.preventDefault();
}

function onup(e) {
var action = _bindings[_getCode];
if (!action) return;
_released.push(action)
e.preventDefault();
}

function oncontext(e) {
if (_bindings[Buttons.RIGHT]) {
e.preventDefault();
}
}

function onmove (e) {
var el = e.target,
ox = 0,
oy = 0,

do {
ox = el.offsetLeft;
oy = el.offsetTop;
} while (el = el.parentOffset);

mouse.x = e.clientX - ox;
mouse.y = e.clientY - oy;

e.preventDefault();
}

i.clearPressed = function() {
for (var i = 0; i < _released.length; i ) {
_down[_released[i]] = false;
}
_pressed = {};
_released = [];
}

i.pressed = function(action) {
return _pressed[action];
}

i.down = function(action) {
return _down[action];
}

i.released = function(action) {
return _released.indexOf(action) >= 0;
}

canvas.frame.onmousedown = ondown;
canvas.frame.onmouseup =onup;
canvas.frame.onmousemove = onmove;
canvas.frame.oncontextmenu = oncontext;

document.onkeydown = ondown;
document.onkeyup = onup;
document.onmouseup = onup;

return i;

})();

})();
Ilmoita
Game.js:

define(function() {

var _vendors = ["o", "ms", "moz", "webkit"];
for (var i = _vendors.length; i--&& !window.requestAnimationFrame;) {
var v = _vendors[i];

window.requestAnimationFrame = window[v "RequestAnimationFrame"];
window.cancelAnimationFrame = window[v "CancelAnimationFrame"] ||
window[v "CancelRequestAnimationFrame"];
}

var Game = Class.extend({

tick: function() {
console.warn("should overrided by childclass!");
},

stop: function() {
if (this._reqframe){
window.cancelAnimationFrame(this._reqframe);
}
this._reqframe = null;
this._running = false;
},

run: function() {
if (this._running) return;
this._running = true;

var self = this;
function loop()
self._reqframe = window.requestAnimationFrame(loop);

self.tick();

input.clearPressed();
canvas.flip();
}
this._reqframe = window.requestAnimationFrame(loop);
}
});

return Game;
});

Gameboard.js:

define(["src/Numfont"], function(Numfont) {

var Gameboard = Class.extend({

init: function() {
this.back = content.get("back");
this.blocks = content.get("blocks");
var num = content.get("numbers");

this.font = {
gray : new Numfont(num, 0, 9),
cyan : new Numfont(num, 9, 9),
red : new Numfont(num, 18, 9),
blue : new Numfont(num, 27, 9),
orange: new Numfont(num, 36, 9),
green : new Numfont(num, 45, 9),
yellow: new Numfont(num, 54, 9),
purple: new Numfont(num, 63, 9)
};
},

draw: function(ctx,stat) {
var tet = stat.tetraminos;

ctx.drawImage(this.back, 0, 0);

this.font.gray.draw(ctx, stat.lvl, 113, 16, 5);
this.font.gray.draw(ctx, stat.lines, 113, 34, 5);
this.font.gray.draw(ctx, stat.score, 78, 52, 10);

this.font.orange.draw(ctx, tet.L, 432, 52, 5);
this.font.cyan.draw( ctx, tet.I, 432, 76, 5);
this.font.purple.draw(ctx, tet.T, 432, 100, 5);
this.font.green.draw( ctx, tet.S, 432, 124, 5);
this.font.red.draw( ctx, tet.Z, 432, 148, 5);
this.font.yellow.draw(ctx, tet.O, 432, 172, 5);
this.font.blue.draw( ctx, tet.J, 432, 196, 5);

this.font.gray.draw( ctx, tet.tot, 425, 220, 6);
},

drawBlock: function(ctx, block, x, y) {
var id = block.ID,
size = 13;

x = 180 x*12;
y = 4 y*12;

ctx.drawImage(this.blocks, id*12, 0, size, size, x, y, size, size);
}
});

return GameBoard;

});
Ilmoita
main.js:

requirejs.config({

baseUrl: "js",

paths: {
src: "./src"
}
});

require(["src/Game", "src/Tetris"], function(Game, Tetris) {

var App = Game.extend({

init: function() {
canvas.width = 480;
canvas.height = 272;
canvas.scale = 1;

content.load("back", "res/back.png);
content.load("blocks", "res/blocks.png);
content.load("numbers", "res/numbers.png);

input.bindKey("space", input.Keys.SPACE);
input.bindKey("left", [input.Keys.LEFT_ARROW, input.Keys.A]);
input.bindKey("up", [input.Keys.UP_ARROW, input.Keys.W]);
input.bindKey("right", [input.Keys.RIGHT_ARROW, input.Keys.D]);
input.bindKey("down", [input.Keys.DOWN_ARROW, input.Keys.S]);

this.hasLoad = false;
},

tick: function() {

if (this.hasLoad)

this.tetris.update(input);
this.tetris.draw(canvas.ctx);

} else {

this hasLoad = cotent.progress() === 1;

if (this.hasLoad) {
this.tetris = new Tetris(10, 22);
}
}
}
});

(function() {
var game = new App();
game.run();

window.onblur = game.stop.bind(game);
window.onfocus = game.run.bind(game);
})();
});

Numfont.js:

define(function() {

var Numfont = Class.extend({

init: function(img, y, h) {
this.img = img;
this.y = y;
this.height = h;
this.width = img.width / 10;
},

draw: function(ctx, num, x, y, padding) {

num = "" num;

if (padding) {
num = num.length >= padding ? num : new Array(padding - num.length 1).join("0") num;
}

var n;
for (var i = 0, len = num.length; i < len; i ) {
n = parseInt(num[i]);
ctx.drawImage(this.img, this.width*n, this.y, this.width, this.height,
x, y, this.width, this.height);
x = this.width;
}
}
});

return Numfont;

});
Ilmoita
Randomizer.js:

define(function() {

var Randomizer = Class.extend({

init: function() {
this._IDs = "LITSZOJ".split("");
this._S_ID = this._IDs.indexOf("S");
this._Z_ID = this._IDs.indexOf("Z");
this.size = this._IDs.length;
this.initialize();
},

initialize: function() {
this.idx = 0;
this.bag = new Array(this.size);

for (var i = 0; i < this.size; i ) {
this.bag[i] = i;
}

do {
this.shuffle();
} while (this.bag[0] === this._S_ID || this.bag[0] === this._Z_ID)
},

shuffle: function(array) {
var array = array || this.bag,
counter = array.length,
temp,
index;

while (counter > 0) {
index = Math.round(Math.random() * --counter) {
temp = array[counter];
array[counter] = array[index];
array[index] = temp;
}

return array;
},

nextInt: function() {
var i = this.bag[this.idx];
this.idx ;
if (this.idx >= this.size)
this.idx = 0;
this.shuffle();
}
return i;
},

nextID: function() {
return this._IDs[this.nextInt()];
}
});

return Randomizer;
});
Ilmoita
StatManager.js:

define(function() {

var StatManager = Class.extend({

init: function() {
this.reset(0);
},

reset: function(startlvl) {

this.tetraminos = {
L: 0,
I: 0,
T: 0,
S: 0,
Z: 0,
O: 0,
J: 0,

tot: 0
}

this._firstlvl = false;

this.startlvl = startlvl || 0;
this.lvl = this.startlvl;

this.score = 0;
this.lines = 0;
},

incTetramino: function(id) {
this.tetraminos[id] = 1;
this.tetraminos.tot = 1;
},

addScore: function(cleared) {
var p = [0, 40, 100, 300, 1200][cleared];
this.score = (this.lvl 1) * p;
},

checkLvlUp: function() {
if (this._firstlvl) {
if (this.lines >= (this.lvl 1) * 10) {
this.lvl ;
}
} else {
if (this.lines >= (this.startlvl 1) * 10 || 100) {
this._firstlvl = true;
this.lvl ;
}
}
}
});

return StatManager;

});
Ilmoita
Tetramino.js:

define(function() {

var ShapeDef = {
L: "001"
"111"
"000",

I: "0000 1111 0000 0000",
T: "010 111 000",
S: "011 110 000",
Z: "110 011 000",
O: "011 011 000",
J: "100 111 000"
};

var IDs = [];
for (var sd in ShapeDef) {
ShapeDef[sd] = ShapeDef[sd].replace(/\s /g, "");
IDs.push(sd);
}

var Tetramino = Class.extend({

init: function(id, x, y) {
this._shapes = [];
this.rotation = 0;
this.ID = id.toUpperCase();

this.x = x || 0;
this.y = y || 0;

var shape = ShapeDef[this.ID];

var s = [],
n = Math.sqrt(shape.length);

for (var i = 0; i< n; i ) {
s[i] = [];
for (var j = 0; j < n; j ){
s[i][j] = parseInt(shape[j i*n]);
}
}
this._shapes.push(s);

var r = 3, t;
while (this.ID !== "O" && r-- !== 0) {
t = [];
for (var i = 0; i < n; i ) {
t[i] = [];
for (var j = 0; j < n; j ) {
t[i][j] = s[n - j - 1][i];
}
}
s = t.slice(0);
this._shapes.push(s);
}
},

setTo: function(control, id) {
id = id != null ? id : this.ID;
var shape = this._shapes[this.rotation];

for (var i = 0; i < shape.length; i ) {
for (var j = 0; j < shape.length; j ) {
if (shape[j][i]) {
control[this.x i][this.y j].setType(id);
}
}
}
},

check: function(control, dx, dy, dr) {
dx = dx || 0;
dy = dy || 0;
dr = dr ? this.getRotation(dr) : this.rotation;

var x = this.x dx,
y = this.y dy,
w = control.length,
h = control[0].length,
shape = this._shapes[dr];

for (var i = 0; i < shape.length; i ) {
for (var j = 0; j < shape.length; j ) {
if (shape[j][i]) {

if (!(0 <= x i && x i < w && 0 <= y j && y j < h) ||
control[x i][y j].solid
) {
return false;
}
}
}
}

return true;
},

getRotation: function(dr) {
var r = this.rotation,
l = this._shapes.length;
if (dr > 0) {
return (r 1) % 1;
} else {
return r - 1 >= 0 ? r - 1 : l - 1;
}
},

toString: function() {
var str = "";

for (var i = 0; i < this._shapes.length; i ) {
str = "\n";
var s = this._shapes[i];
for (var j = 0; j < s.length; j ) {
for (var k = 0; k < s[j].length; k ) {
str = s[j][k] ? "#" : ".";
}
str = "\n"
}
Ilmoita
Tetramino.js (jatkuuu...):

}

return str;
}
});

for (var i = 0; i < IDs.length; i ) {
Tetramino[IDs[i]] = IDs[i];
}

return Tetramino;
});

Tetris.js:

define([
"src/Gameboard",
"src/StatManager",
"src/Tetramino",
"src/Block",
"src/Randomizer"
], function(Gameboard, StatManager, Tetramino, Block, Randomizer) {

var Tetris = Class.extend({

init: function(cols, rows) {

this.cols = cols;
this.rows = rows;

this.gameBoard = new GameBoard();
this.stat = new StatManager();
this.random = new Randomizer();

this.blockControl = [];

this.reset();
},

reset: function() {

this.frames = 1;

this.blockControl = [];
for (var i = 0; i < this.cols; i ) {
this.blockControl[i] = [];
for (var j = 0; j < this.rows; j ) {
this.blockControl[i][j] = new Block(Block.NONE);
}
}

this.random.initialize();
this.setToNextTetramino();
},

update : function(inpt) {
this.currentTetramino.setTo(this.blockControl, Block.NONE);

if (inpt.pressed("up")) {
this.moveRotate();
}
if (inpt.pressed("down")) {
this.moveDown();
}
if (inpt.pressed("left")) {
this.moveLeft();
}
if (inpt.pressed("right")) {
this.moveRight();
}
if (inpt.pressed("space")) {
this.hardDrop();
}

if (this.frames % 20 === 0) {
this.moveDown();
}

this.currentTetramino.setTo(this.blockControl);
},

draw: function(ctx) {
this.gameBoard.draw(ctx, this.stat);

for (var i = 0; i < this.cols; i ) {
for (var j = 0; j< this.rows; j ) {
var b = this.blockControl[i][j];
if (b.solid) {
this.gameBoard.drawBlock(ctx, b, i, j);
}
}
}
},

setNextTetramino: function(){

this.currentTetramino = new Tetramino(this.random.nextID());
this.currentTetramino.x = 3;
this.currentTetramino.y = 0;

this.stat.incTetramino(this.currentTetramino.ID);
},

moveLeft: function() {
var bc = this.blockControl,
ct = this.currentTetramino;

if (ct.check(bc, -1, 0)) {
ct.x -= 1;
}
},

moveRight: function() {
var bc = this.blockControl,
ct = this.currentTetramino;

if (ct.check(bc, 1, 0)) {
ct.x = 1;
}
},

moveRotate: function(dr) {
dr = dr || 1;
var bc = this.blockControl,
ct = this.currentTetramino;

if (ct.check(bc, 0, 0, dr)) {
ct.rotation = ct.getRotation(dr);
}
},

moveDown: function() {
var bc = this.blockControl,
ct = this.currentTetramino;

if (ct.check(bc, 0, 1)) {
Ilmoita
Mitä tarkoitat "ei hyväksy" ?

Jos attribuutti on data-* niin selaimet ei välitä niistä mitään ja se on normaalia toimintaa.

Ja mikä siinä nyt ei tarkalleen ottaen toimi? Tuossahan on jo jonkin verran koodia että mitkä näistä olet testannut toimivaksi? Ohjelmia ei yleensä tehdä niin, että kirjoitetaan koodia satoja rivejä ja sitten mietitä miten toimisi, vaan ensiksi kirjoitetaan testi, ja sitten pieni pätkä koodia joka testataan että toimiiko.
1 VASTAUS:
Siis laitoin noi lähes turhaan tohon. Siinä ei toimi HTML5 osuus.
+Lisää kommentti
Tetris.js(jatkuuu...):

ct.y = 1;
} else {
ct.setTo(bc);
this.checkRows();
this.setNextTetramino();
}
},

hardDrop: function() {
var bc = this.blockControl,
ct = this.currentTetramino,
move = true;

while (move) {
if (ct.check(bc, 0, 1)) {
ct.y = 1;
this.stat.score = 2;
} else {
move = false;
ct.setTo(bc);
this.checkRows();
this.setNextTetramino();
}
}
},

checkRows: function() {
var full, removed = 0;

for (var i = this.rows-1; i >= 0; i--) {
full = true;
for (var j = 0; j < this.cols; j ) {
if (!this.blockControl[j][i].solid) {
full = false;
break;
}
}

if (full) {
this.removeRow(i);
removed ;
this.stat.lines ;
i ;
}
}

if (removed > 0) {
this.stat.addScore(removed);
this.stat.checkLvlUp();
}
},

removeRow: function(row) {
var bc = this.blockControl;
for (var i = row; i > 0 i--) {
for (var j = 0; j < this.cols; j ) {
bc[j][i].setType(bc[j][i - 1].ID);
}
}
}
});

return Tetris;

}):
Ilmoita
Tässä on se data-main, jota JS ei hyväksy.

Lisäksi minulla on kolme png:llä tallennettua kuvaa jotka olen sijoittanut nettisivulle.

Minulla on myös yksi netistä otettu tiedosto, jonka nimi on require.js.

Se on niin suuri, että en laittanut sitä tähän. Tämän ei pitäisi olla kiinni siitä.





STC: Simple Tetris Clone














Ps. nämä koodit ovat pitkiä... hyvä jos joku jaksaa kelata lopuun asti. Toivon silti, että joku osaisi auttaa!
Kiitos jo etukäteen.
3 VASTAUSTA:
Onko tämä polku oikein "js/src/main.js" ?

Näkyy olevan muut muotoa js/foo.js
Pitää vielä kokeilla, mutta sen pitäisi toimia sillä ne ovat kansiossa js jonka sisällä on kansio src. Pitää testata saattaa toimia. Kiitos neuvosta M-Kar!
Sellainen perstuntuma myös, että järjestyksellä missä linkkaat niitä .js tiedostoja voi olla myös merkitystä.
+Lisää kommentti
Laita koodi jonnekin, missä on koodinväritin ja tasalevyinen fontti.
Ilmoita

Tästä on poistettu viesti sääntöjen vastaisena.

Ilmoita

Vastaa alkuperäiseen viestiin

Tarvitsisin apua Javascript koodauksessa

Olen tehnyt tässä lähiaikoina YouTuben tutoriaalien avulla kehittynyttä Tetristä, mutta se ei vain toimi millään. Käytän Microsoftin Microsoft Expression 4 Webiä koodaamiseen. Nettisivuun käytän HTML5 :ttä. HTML5 ei hyväksy data-mainia. Toivoisin, että joku voisi auttaa minua tässä.

styles.css(2.1) :

canvas {
border: 1px solid #000;
}

Block.js:

define(function() {

var DrawIDs = {
NONE: 0,
I: 1,
Z: 2,
J: 3,
L: 4,
S: 5,
O: 6,
T: 7
}

var Block = Class.extend({

init: function(id) {
this.setType(id || "none");
},

setType: function(id) {
this.ID = typeof id === "number" ? id : DrawIDs[id.toUpperCase()];
this.solid = this.ID !== DrawIDs.NONE;
}
});

for (var id in DrawIDs) {
Block[id] = DrawIDs[id];
}

return Block;

});

class.js:

/* Simple JavaScript Inheritance
* By John Resig http://ejohn.org/
* MIT Licensed.
*/
// Inspired by base2 and Prototype
(function(){
var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;

// The base Class implementation (does nothing)
this.Class = function(){};

// Create a new Class that inherits from this class
Class.extend = function(prop) {
var _super = this.prototype;

// Instantiate a base class (but only create the instance,
// don't run the init constructor)
initializing = true;
var prototype = new this();
initializing = false;

// Copy the properties over onto the new prototype
for (var name in prop) {
// Check if we're overwriting an existing function
prototype[name] = typeof prop[name] == "function" &&
typeof _super[name] == "function" && fnTest.test(prop[name]) ?
(function(name, fn){
return function() {
var tmp = this._super;

// Add a new ._super() method that is the same method
// but on the super-class
this._super = _super[name];

// The method only need to be bound temporarily, so we
// remove it when we're done executing
var ret = fn.apply(this, arguments);
this._super = tmp;

return ret;
};
})(name, prop[name]) :
prop[name];
}

// The dummy class constructor
function Class() {
// All construction is actually done in the init method
if ( !initializing && this.init )
this.init.apply(this, arguments);
}

// Populate our constructed prototype object
Class.prototype = prototype;

// Enforce the constructor to be what we expect
Class.prototype.constructor = Class;

// And make this class extendable
Class.extend = arguments.callee;

return Class;
};
})();

5000 merkkiä jäljellä

Peruuta