Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am very new to the front end programming and I sometimes do not get the meaning of the shortcuts of the javascript and jquery. I have some code template to work on and I do not understand clearly that how it is working which are as below.
Will you please help me to get through article to understand these definations which are in the js file.
Thank you in advance.
I have something like this. I just want to know that how it works! I am not getting the clear idea.
1
for (var e = document.getElementsByTagName("div"), t = 0; t < e.length; t++)
"fish" == e[t].getAttribute("class") && fishArray.push(e[t])
2.
"vertical" == layersMovement ? (balloonDiv.style.left = o + "px", robbyContainerDiv.style.left = n + "px") : "not moving 1" == layersMovement ||
"not moving 2" == layersMovement ? (robbyContainerDiv.style.left = n + pageVerticalPosition - (pageDiv.offsetHeight - containerDiv.offsetHeight - distanceBetweenRobbyAndBalloon) + "px",
balloonDiv.style.left = o + "px") : (balloonDiv.style.left = layerHorizontalArray[layerHorizontalArray.length - 1].offsetLeft + layerHorizontalArray[layerHorizontalArray.length - 1].offsetWidth - .5 * (containerDiv.offsetWidth + balloonDiv.offsetWidth) + "px",
robbyContainerDiv.style.left = "50%")
Transforming it to cleaner code will help you understand:
for (var e = document.getElementsByTagName("div"), t = 0; t < e.length; t++) "fish" == e[t].getAttribute("class") && fishArray.push(e[t])
cleanning the code:
var e = document.getElementsByTagName("div");
==> Defining e to hold all div elements
for (var t = 0; t < e.length; t++)
==> Loop for each div element in e. The first section of for statement can be used to initialize variables. For example: for (var a = 0, b = 2, c = 3; a < b; a++) This is why the original code defined e inside the for statement.
"fish" == e[t].getAttribute("class") && fishArray.push(e[t])
==> a && b evaluates a and in case the evaluation result is true, b is performed. It is a shortcut for if (a) { b; }. In this statement, if the class attribute of the current div equals to 'fish', push the reference of the div to fishArray array.
In other words, the code can be written cleaner like this:
var e = document.getElementsByTagName("div");
for (var t = 0; t < e.length; t++) {
var currentDiv = e[t];
if ("fish" == currentDiv.getAttribute("class")) {
fishArray.push(e[t]);
}
}
The second code:
"vertical" == layersMovement ? (balloonDiv.style.left = o + "px", robbyContainerDiv.style.left = n + "px") : "not moving 1" == layersMovement || "not moving 2" == layersMovement ? (robbyContainerDiv.style.left = n + pageVerticalPosition - (pageDiv.offsetHeight - containerDiv.offsetHeight - distanceBetweenRobbyAndBalloon) + "px", balloonDiv.style.left = o + "px") : (balloonDiv.style.left = layerHorizontalArray[layerHorizontalArray.length - 1].offsetLeft + layerHorizontalArray[layerHorizontalArray.length - 1].offsetWidth - .5 * (containerDiv.offsetWidth + balloonDiv.offsetWidth) + "px",
robbyContainerDiv.style.left = "50%")
Explanation:
The second code contains nested conditions.
The following: a ? b : c is equals to: if (a) { b; } else { c; }.
I can write a, b, c; in order to execute a, then b and then c ( a; b; c; ).
With those two rules, take that block of code and rewrite it so you could understand it.
BTW, I believe you are looking on minified code.
Hope that helps!
Related
Is there any way to deobfuscate some javascript code that produced with webpack 4 and is also splitChunked?
It's a little more than 1MB js code and I only need to understand a small portion of the code, which is this function :
function l(e) {
t.d(8, function(e) {
for (var n = e.length, r = t.b(n), f = a(), c = 0; c < n; c++) {
var i = e.charCodeAt(c);
if (i > 127)
break;
f[r + c] = i
}
if (c !== n) {
0 !== c && (e = e.slice(c)),
r = t.c(r, n, n = c + 3 * e.length);
var d = a().subarray(r + c, r + n);
c += o(e, d).written
}
return u = c,
r
}(e), u);
var n, r, f = (null !== i && i.buffer === t.e.buffer || (i = new Int32Array(t.e.buffer)),
i), c = (n = f[2],
r = f[3],
d.decode(a().subarray(n, n + r))).slice();
return t.a(f[2], 1 * f[3]),
c
}
I used chrome debugger and set some breakpoints and I was able to grasp what it's doing but I need to do the exact same thing in my project So I need a more readable code to do that.
As far as I know, there is no easy way to do so, but I want to share some tips with you:
Replace all ',' with ', '\n'
Review and correct the possible code breaks
Use a for loop to iterate between static value arrays and replace all the usages.
Change the encoding in case of language dependent breaks
Replace all ; with ; \n and correct possible code breaks
Know it is easier to rename functions and write comments for them.
https://jsfiddle.net/2L4t9saq/180/ is my fiddle
most of the code is just useless, ill just post the stuff that matters
var baseConverter = function(r, e, n) {
var o = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if (e <= 0 || e > o.length || n <= 0 || n > o.length) return console.log("Base unallowed"), null;
var l, t = 0;
if (10 != e) {
var a = r.length;
for (l = 0; l < a; l++) {
var u, f = -1;
for (u = 0; u < o.length; u++)
if (r[l] == o[u]) {
f = 1;
break
}
if (u >= e) return console.log("Symbol unallowed in baseform"), null;
if (-1 == f) return console.log("Symbol not found"), null;
var s = a - l - 1;
t += 0 == s ? u : u * Math.pow(e, s)
}
} else t = parseInt(r);
if (10 != n) {
for (var g = []; t > 0;) {
var i = t % n;
if (i < 0 || i >= o.length) return console.log("Out of bounds error"), null;
g.push(o[i]), t = parseInt(t / n)
}
return g.reverse().toString().replace(/,/g, "")
}
return t.toString()
}
var b36torgba = function(input) {
for (var i = 1; i < (input.length / 8) + 1; i++) {
var arr = input
var r = arr.charAt[0 + (i - 1) * 8] + "" + arr.charAt[1 + (i - 1) * 8]
var g = arr.charAt[2 + (i - 1) * 8] + "" + arr.charAt[3 + (i - 1) * 8]
console.log(g.charAt[2])
var b = arr.charAt[4 + (i - 1) * 8] + "" + arr.charAt[5 + (i - 1) * 8]
console.log(b)
var a = arr.charAt[6 + (i - 1) * 8] + "" + arr.charAt[7 + (i - 1) * 8]
console.log(a)
var rrgba = baseConverter(r, 36, 10)
var grgba = baseConverter(r, 36, 10)
var brgba = baseConverter(r, 36, 10)
var argba = baseConverter(r, 36, 10)
var bigMessOfAVariable = "rgba(" + rrgba + "," + grgba + "," + brgba + "," + argba + "),"
return bigMessOfAVariable;
}
}
you can ignore the top function, all it is is a base converter script, that takes in three inputs, an input, the base its in, and the base it should be converted to: eg baseConverter(73,36,10) will output 255.
now, the problem is with my b36torgba function.
it will take in a string, which is guaranteed to have a length that is either 0, 8, or a multiple of 8, this is just standardization to make sure everything runs smoothly, without having 700 indexOf[] functions.
it takes in the input, and divides it by 8, this tells the function how many bytes it has to go through, and how many it will spit out, so a string "[7300002S7300002S]" should (divided by 8) output 2, therefore the script runs 2 iterations.
currently, it should be taking in the string, and assigning each group of 2 characters (again standard) to a specific variable, this will allow it to all be put in the end and outputted as the same string but in base 10 rgba (hence 73 being use, 73 in base 36 is 255), but before it can do any of that, it breaks when it tries to find the characters in a string, saying this syntax error:
Uncaught TypeError: Cannot read property '0' of undefined
at b36torgba ((index):40)
at window.onload ((index):55)
why does it break as soon as it tries to feed the string into my charAt()'s?
ps: i do understand that the code in its current state, if it worked, it'd only output the rgba value of the last 8 characters
Easy mistake. You're using charAt (which is a function) by doing charAt[index] (using square brackets), rather than charAt(index) (using round brackets). Fixing that up should solve your issue.
Also - you're calling the function by doing b36torgba(["7300002S7300002S"]) in your JSFiddle, and trying to do string manipulation on it. Since ["7300002S7300002S"] is an array, not a string, .charAt() won't work on it. Try calling the function by doing b36torgba("7300002S7300002S") instead.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm trying to execute the following JavaScript on the backend by recreating the logic with C# code. I'm trying to obtain the "sucuri_cloudproxy_js" cookie in order to access webcontent, but in order to obtain this cookie, you must execute this JavaScript. What is the most efficient way to execute javascript in C#? Thank you!
var s = {},
u, c, U, r, i, l = 0,
a, e = eval,
w = String.fromCharCode,
sucuri_cloudproxy_js = '',
S = 'dj0nd0U3Jy5jaGFyQXQoMikrU3RyaW5nLmZyb21DaGFyQ29kZSg5OSkgKyAiIiArIjZzdSIuc2xpY2UoMCwxKSArICI5c3UiLnNsaWNlKDAsMSkgKyAnNScgKyAgIjUiICsgImZzZWMiLnN1YnN0cigwLDEpICsgIjNzdWN1ciIuY2hhckF0KDApKyAnJyArIAoiMyIgKyAiIiArImQiLnNsaWNlKDAsMSkgKyAgJycgKyIwc3UiLnNsaWNlKDAsMSkgKyAgJycgKydlJyArICAiYyIgKyAiIiArImJzdWN1ciIuY2hhckF0KDApK1N0cmluZy5mcm9tQ2hhckNvZGUoMHgzMikgKyAgJycgKycnKydlJyArICAiOCIuc2xpY2UoMCwxKSArICAnJyArJ2ZLNycuY2hhckF0KDIpKydANCcuc2xpY2UoMSwyKSsiIiArImQiICsgICcnICsgCiJiIiArICI5IiArICAnJyArJycrU3RyaW5nLmZyb21DaGFyQ29kZSg1NCkgKyAiYiIgKyAgJycgKyAKIjYiICsgJzAnICsgICIiICsiNyIgKyAnb01kJy5jaGFyQXQoMikrImFzZWMiLnN1YnN0cigwLDEpICsgU3RyaW5nLmZyb21DaGFyQ29kZSg0OSkgKyAgJycgKycnKyc4JyArICAiZHNlYyIuc3Vic3RyKDAsMSkgKyAnJztkb2N1bWVudC5jb29raWU9J3NzdWMnLmNoYXJBdCgwKSsgJ3VzdWMnLmNoYXJBdCgwKSsgJ2MnKyd1JysncicrJ2knKydfJysnYycuY2hhckF0KDApKydsc3UnLmNoYXJBdCgwKSArJ3N1Y3VybycuY2hhckF0KDUpICsgJ3UnKydzdWN1cmQnLmNoYXJBdCg1KSArICdwc3VjdXInLmNoYXJBdCgwKSsgJ3InKydvJysneHN1Y3VyJy5jaGFyQXQoMCkrICd5Jy5jaGFyQXQoMCkrJ18nKycnKyd1c3VjdXInLmNoYXJBdCgwKSsgJ3N1Jy5jaGFyQXQoMSkrJ2knKycnKydkJysnX3MnLmNoYXJBdCgwKSsnM3N1Y3UnLmNoYXJBdCgwKSAgKycwJysnZCcrJzEnLmNoYXJBdCgwKSsnOXN1Y3UnLmNoYXJBdCgwKSAgKydzdTknLmNoYXJBdCgyKSsnc3VjdXIzJy5jaGFyQXQoNSkgKyAnYXN1Y3VyaScuY2hhckF0KDApICsgJ2YnKyI9IiArIHY7IGxvY2F0aW9uLnJlbG9hZCgpOw==';
L = S.length;
U = 0;
r = '';
var A = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
for (u = 0; u < 64; u++) {
s[A.charAt(u)] = u;
}
for (i = 0; i < L; i++) {
c = s[S.charAt(i)];
U = (U << 6) + c;
l += 6;
while (l >= 8) {
((a = (U >>> (l -= 8)) & 0xff) || (i < (L - 2))) && (r += w(a));
}
}
e(r);
This looks like some sort of base 64 decoding algorithm. There are built in base64 decoders in C# you could try. Alternatively, if 'S' never changes, you could just execute this in javascript and put the result in to your C# program.
executing this in javascript console:
var s = {},
u, c, U, r, i, l = 0,
a, e = eval,
w = String.fromCharCode,
sucuri_cloudproxy_js = '',
S = 'dj0nd0U3Jy5jaGFyQXQoMikrU3RyaW5nLmZyb21DaGFyQ29kZSg5OSkgKyAiIiArIjZzdSIuc2xpY2UoMCwxKSArICI5c3UiLnNsaWNlKDAsMSkgKyAnNScgKyAgIjUiICsgImZzZWMiLnN1YnN0cigwLDEpICsgIjNzdWN1ciIuY2hhckF0KDApKyAnJyArIAoiMyIgKyAiIiArImQiLnNsaWNlKDAsMSkgKyAgJycgKyIwc3UiLnNsaWNlKDAsMSkgKyAgJycgKydlJyArICAiYyIgKyAiIiArImJzdWN1ciIuY2hhckF0KDApK1N0cmluZy5mcm9tQ2hhckNvZGUoMHgzMikgKyAgJycgKycnKydlJyArICAiOCIuc2xpY2UoMCwxKSArICAnJyArJ2ZLNycuY2hhckF0KDIpKydANCcuc2xpY2UoMSwyKSsiIiArImQiICsgICcnICsgCiJiIiArICI5IiArICAnJyArJycrU3RyaW5nLmZyb21DaGFyQ29kZSg1NCkgKyAiYiIgKyAgJycgKyAKIjYiICsgJzAnICsgICIiICsiNyIgKyAnb01kJy5jaGFyQXQoMikrImFzZWMiLnN1YnN0cigwLDEpICsgU3RyaW5nLmZyb21DaGFyQ29kZSg0OSkgKyAgJycgKycnKyc4JyArICAiZHNlYyIuc3Vic3RyKDAsMSkgKyAnJztkb2N1bWVudC5jb29raWU9J3NzdWMnLmNoYXJBdCgwKSsgJ3VzdWMnLmNoYXJBdCgwKSsgJ2MnKyd1JysncicrJ2knKydfJysnYycuY2hhckF0KDApKydsc3UnLmNoYXJBdCgwKSArJ3N1Y3VybycuY2hhckF0KDUpICsgJ3UnKydzdWN1cmQnLmNoYXJBdCg1KSArICdwc3VjdXInLmNoYXJBdCgwKSsgJ3InKydvJysneHN1Y3VyJy5jaGFyQXQoMCkrICd5Jy5jaGFyQXQoMCkrJ18nKycnKyd1c3VjdXInLmNoYXJBdCgwKSsgJ3N1Jy5jaGFyQXQoMSkrJ2knKycnKydkJysnX3MnLmNoYXJBdCgwKSsnM3N1Y3UnLmNoYXJBdCgwKSAgKycwJysnZCcrJzEnLmNoYXJBdCgwKSsnOXN1Y3UnLmNoYXJBdCgwKSAgKydzdTknLmNoYXJBdCgyKSsnc3VjdXIzJy5jaGFyQXQoNSkgKyAnYXN1Y3VyaScuY2hhckF0KDApICsgJ2YnKyI9IiArIHY7IGxvY2F0aW9uLnJlbG9hZCgpOw==';
L = S.length;
U = 0;
r = '';
var A = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
for (u = 0; u < 64; u++) {
s[A.charAt(u)] = u;
}
for (i = 0; i < L; i++) {
c = s[S.charAt(i)];
U = (U << 6) + c;
l += 6;
while (l >= 8) {
((a = (U >>> (l -= 8)) & 0xff) || (i < (L - 2))) && (r += w(a));
}
}
r;
gives this:
v='wE7'.charAt(2)+String.fromCharCode(99) + "" +"6su".slice(0,1) + "9su".slice(0,1) + '5' + "5" + "fsec".substr(0,1) + "3sucur".charAt(0)+ '' +
"3" + "" +"d".slice(0,1) + '' +"0su".slice(0,1) + '' +'e' + "c" + "" +"bsucur".charAt(0)+String.fromCharCode(0x32) + '' +''+'e' + "8".slice(0,1) + '' +'fK7'.charAt(2)+'#4'.slice(1,2)+"" +"d" + '' +
"b" + "9" + '' +''+String.fromCharCode(54) + "b" + '' +
"6" + '0' + "" +"7" + 'oMd'.charAt(2)+"asec".substr(0,1) + String.fromCharCode(49) + '' +''+'8' + "dsec".substr(0,1) + '';document.cookie='ssuc'.charAt(0)+ 'usuc'.charAt(0)+ 'c'+'u'+'r'+'i'+'_'+'c'.charAt(0)+'lsu'.charAt(0) +'sucuro'.charAt(5) + 'u'+'sucurd'.charAt(5) + 'psucur'.charAt(0)+ 'r'+'o'+'xsucur'.charAt(0)+ 'y'.charAt(0)+'_'+''+'usucur'.charAt(0)+ 'su'.charAt(1)+'i'+''+'d'+'_s'.charAt(0)+'3sucu'.charAt(0) +'0'+'d'+'1'.charAt(0)+'9sucu'.charAt(0) +'su9'.charAt(2)+'sucur3'.charAt(5) + 'asucuri'.charAt(0) + 'f'+"=" + v; location.reload();
take off the location.reload and execute that and it results in a string:
"sucuri_cloudproxy_uuid_30d1993af=7c6955f33d0ecb2e874db96b607da18d"
all of that was originally passed through the eval function, so in the end, I'm guessing you want the 7c...18d, or maybe something to do with the uuid variable.
if S changes, then you'll need to reverse engineer this whole thing, or find a way to leverage a server side tool to execute javascript. You could use something like phantomjs perhaps.
Adding to the answer from Mark Evaul, the cookie content should be available in your controller code by referencing:
Request.Cookies["sucuri_cloudproxy_js"].Value
You can run the replacement algorithm on the value to decode the value of the cookie.
function getAnswer(){
var answer, c = 334;
while (c < 999){
var a = Math.round(((1000 - c) / 2) - 0.5), b = Math.round((1000 - c) / 2);
while (a > 0 && b < c){
if (Math.pow(a, 2) + Math.pow(b, 2) != Math.pow(c, 2)){
a -= 1;
b += 1;
}else{
answer = a * b * c;
}
}
c += 1;
}
document.getElementById("a").innerHTML = answer;
}
Hi! I am a beginner programmer in javascript, and I have been trying to solve problem 9 in Project Euler. That problem goes like this:
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
I don't know why no answer appears, and my script crashes/program stops running, whenever I run this script. Please explain and tell me what's wrong with my script.
When you have found the answer, you don't stop with the iteration. Even worse, you don't change the values of a and b any more, so they never reach the end of the iteration, and you're stuck in an infinite loop.
You'll need to break out of the loop when you've found the answer. Or even break out of both your nested loops, using a label:
function getAnswer() {
var answer,
c = 334;
find: while (c < 999) {
var a = Math.round(((1000 - c) / 2) - 0.5),
b = Math.round((1000 - c) / 2);
while (a > 0 && b < c) {
if (Math.pow(a, 2) + Math.pow(b, 2) == Math.pow(c, 2)) {
answer = a * b * c;
break find;
}
a -= 1;
b += 1;
}
c += 1;
}
document.getElementById("a").innerHTML = answer;
}
Notice that it would be easier if your function just returned the answer, instead of populating #a with it. You'd call it like
document.getElementById("a").innerHTML = getAnswer();
and can just return a * b * c; to break out of the whole function.
Hy,
I am trying to implement an Connect Four Game in javascript / jQuery. First off this is no homework or any other duty. I'm just trying to push my abilities.
My "playground" is a simple html table which has 7 rows and 6 columns.
But now I have reached my ken. I'm stuck with the main functionality of checking whether there are 4 same td's around. I am adding a class to determine which color it should represent in the game.
First I thought I could handle this with .nextAll() and .prevAll() but this does not work for me because there is no detection between.
Because I was searching for siblings, when adding a new Item and just looked up the length of siblings which were found and if they matched 4 in the end I supposed this was right, but no its not :D Is there maybe any kind of directNext() which provides all next with a css selector until something different comes up ?
I will put all of my code into this jsfiddle: http://jsfiddle.net/LcUVf/5/
Maybe somebody has ever tried the same or someone comes up with a good idea I'm not asking anybody to do or finish my code. I just want to get hints for implementing such an algorithm or examples how it could be solved !
Thanks in anyway !
DOM traversal is not particularly efficient so, when you can avoid it, I'd recommend doing so. It'd make sense for you to build this as a 2D array to store and update the state of the game. The table would only be a visual representation of the array.
I know that, normally, you would build the array with rows as the first dimension and columns as the second dimension but, for the purposes of being able to add pieces to each column's "stack," I would make the first dimension the columns and the second dimension the rows.
To do the check, take a look at this fiddle I made:
http://jsfiddle.net/Koviko/4dTyw/
There are 4 directions to check: North-South, East-West, Northeast-Southwest, and Southeast-Northwest. This can be represented as objects with the delta defined for X and Y:
directions = [
{ x: 0, y: 1 }, // North-South
{ x: 1, y: 0 }, // East-West
{ x: 1, y: 1 }, // Northeast-Southwest
{ x: 1, y: -1 } // Southeast-Northwest
];
Then, loop through that object and loop through your "table" starting at the farthest bounds that this piece can possibly contribute to a win. So, since you need 4 pieces in a row, the currently placed piece can contribute in a win for up to 3 pieces in any direction.
minX = Math.min(Math.max(placedX - (3 * directions[i].x), 0), pieces.length - 1);
minY = Math.min(Math.max(placedY - (3 * directions[i].y), 0), pieces[0].length - 1);
maxX = Math.max(Math.min(placedX + (3 * directions[i].x), pieces.length - 1), 0);
maxY = Math.max(Math.min(placedY + (3 * directions[i].y), pieces[0].length - 1), 0);
To avoid any issues with less-than and greater-than (which I ran into), calculate the number of steps before looping through your pieces instead of using the calculated bounds as your conditions.
steps = Math.max(Math.abs(maxX - minX), Math.abs(maxY - minY));
Finally, loop through the items keeping a count of consecutive pieces that match the piece that was placed last.
function isVictory(pieces, placedX, placedY) {
var i, j, x, y, maxX, maxY, steps, count = 0,
directions = [
{ x: 0, y: 1 }, // North-South
{ x: 1, y: 0 }, // East-West
{ x: 1, y: 1 }, // Northeast-Southwest
{ x: 1, y: -1 } // Southeast-Northwest
];
// Check all directions
outerloop:
for (i = 0; i < directions.length; i++, count = 0) {
// Set up bounds to go 3 pieces forward and backward
x = Math.min(Math.max(placedX - (3 * directions[i].x), 0), pieces.length - 1);
y = Math.min(Math.max(placedY - (3 * directions[i].y), 0), pieces[0].length - 1);
maxX = Math.max(Math.min(placedX + (3 * directions[i].x), pieces.length - 1), 0);
maxY = Math.max(Math.min(placedY + (3 * directions[i].y), pieces[0].length - 1), 0);
steps = Math.max(Math.abs(maxX - x), Math.abs(maxY - y));
for (j = 0; j < steps; j++, x += directions[i].x, y += directions[i].y) {
if (pieces[x][y] == pieces[placedX][placedY]) {
// Increase count
if (++count >= 4) {
break outerloop;
}
} else {
// Reset count
count = 0;
}
}
}
return count >= 4;
}
I released a fully working version of the game on Github.
It implements an optimised variation on the algorythm Sirko mentioned.
To avoid any unnecessary redunancy, the algorythm directly checks the DOM rather than a JS table. As that algorythm requires a minimum amount of checks, the performance overhead for accessing the DOM is neglectable.
The current player and a flag for keeping track of whether the game has ended are basicly the only statuses stored in the JS itself.
I even used the DOM to store strings. It has no external dependencies and is supported by all versions of IE from IE6 upwards as well as modern browsers.
Code is optimised for filesize and performance. The latest version also includes animation, even though the total JS code of the game is still only 1.216 bytes after minification.
The Code :
Here's the full, un-minified JS code :
(function (doc, win, onclick, gid, classname, content, showMessage) {
var
a, b, c, colorLabel, cid, players, current, finished, newgameLabel, wonLabel, laststart = 1,
cellAt = function (i, j) {
return doc[gid](cid + i + j);
},
isCurrentColor = function (i, j) {
return cellAt(i, j)[classname] === players[current];
},
start = function () {
current = laststart = (laststart + 1) % 2;
finished = 0;
colorLabel[content] = colorLabel[classname] = players[current = (current + 1) % 2];
for (a = 1; a < 7; a++)
for (b = 1; b < 8; b++)
cellAt(a, b)[classname] = '';
},
makeMove = function (i, j, s) {
s > 0 && (cellAt(s, j)[classname] = '');
cellAt(s + 1, j)[classname] = players[current];
s === i - 1 ? function (i, j) {
return function (i, j) {
for (a = j - 1; 0 < a && isCurrentColor(i, a); a--) {
}
for (b = j + 1; 8 > b && isCurrentColor(i, b); b++) {
}
return 4 < b - a;
}(i, j) || function (i, j) {
for (c = i + 1; 7 > c && isCurrentColor(c, j); c++) {
}
return 3 < c - i;
}(i, j) || function (i, j) {
for (a = i - 1, b = j - 1; 0 < a && !(1 > b) && isCurrentColor(a, b); a--)
b--;
for (c = i + 1, b = j + 1; 7 > c && !(7 < b) && isCurrentColor(c, b); c++)
b++;
return 4 < c - a
}(i, j) || function (i, j) {
for (a = i - 1, b = j + 1; 0 < a && !(7 < b) && isCurrentColor(a, b); a--)
b++;
for (c = i + 1, b = j - 1; 7 > c && !(1 > b) && isCurrentColor(c, b); c++)
b--;
return 4 < c - a;
}(i, j);
}(i, j)
? finished = 1 && win[showMessage](doc[gid](wonLabel)[content].replace("%s", players[current].toLowerCase())) && start()
: colorLabel[content] = colorLabel[classname] = players[current = (current + 1) % 2]
: setTimeout(function () {
makeMove(i, j, s + 1)
}, 20);
};
return function (n, w, c, h, p1, p2) {
cid = c;
newgameLabel = n;
wonLabel = w;
colorLabel = doc[gid](c);
players = [doc[gid](p1)[content], doc[gid](p2)[content]];
for (a = 1; a < 7; a++)
for (b = 1; b < 8; b++)
cellAt(a, b)[onclick] = function (b, a) {
return function () {
if (!finished)
for (a = 6; a > 0; a--)
if (!cellAt(a, b)[classname]) {
makeMove(a, b, 0);
break;
}
};
}(b);
;
doc[gid](h)[onclick] = function () {
win[showMessage](doc[gid](newgameLabel)[content]) && start()
};
start();
};
})(document, window, "onclick", "getElementById", "className", "innerHTML", "confirm")("newgame", "won", "color", "restart", "p1", "p2");
A screenshot :
In general a 2dimensional array would be better suited for checking for a line of 4. You could then do something like the following:
function check( lastPiece, playground, player ) {
// check length in each direction
var l = 1,
i = 1;
// top to bottom
while( (playground[ lastPiece.x ][ lastPiece.y - i ] === player) && ((lastPiece.y - i) >= 0) ) { l += 1; i += 1; };
i = 1;
while( (playground[ lastPiece.x ][ lastPiece.y + i ] === player) && ((lastPiece.y + i) <= MAX_Y) ) { l += 1; i += 1; };
if ( l >= 4 ) { return true; }
// left to right
l = 1;
while( (playground[ lastPiece.x - i][ lastPiece.y ] === player) && ((lastPiece.x - i) >= 0) ) { l += 1; i += 1; };
i = 1;
while( (playground[ lastPiece.x + i][ lastPiece.y ] === player) && ((lastPiece.x + i) <= MAX_X) ) { l += 1; i += 1; };
if ( l >= 4 ) { return true; }
// same for top left to bottom right and bottom left to top right
// . . .
// if we got no hit until here, there is no row of 4
return false;
}
EDIT: added checks for borders of the playground