Skip to content

Instantly share code, notes, and snippets.

@zjiekai
Last active August 29, 2015 14:10
Show Gist options
  • Save zjiekai/5d6a298efe01c4d78677 to your computer and use it in GitHub Desktop.
Save zjiekai/5d6a298efe01c4d78677 to your computer and use it in GitHub Desktop.
Moving Blocks to Upper-right
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
<div class="container">
</div>
<script src="//code.jquery.com/jquery-2.0.3.min.js"></script>
<script src="index.js"></script>
</body>
</html>
// Utils
if (!String.prototype.format) {
String.prototype.format = function() {
var args = arguments;
return this.replace(/{(\d+)}/g, function(match, number) {
return typeof args[number] != 'undefined'
? args[number]
: match
;
});
};
}
// Main
var blotWidth = 15,
blotHeight = 15,
W = 25, H = 25;
var ele;
for (var i = 0; i < H; ++i) {
for (var j = 0; j < W; ++j) {
ele = '<div class="blot" id="b{0}"></div> '.format(i*W+j);
$("div.container").append(ele);
}
}
$(".blot").css('width', blotWidth+'px');
$(".blot").css('height', blotHeight+'px');
$("div.container").css('width', W*blotWidth+'px');
$("div.container").css('height', H*blotHeight+'px');
function IDString(x, y) {
var i = H-y-1, j = x;
return 'b'+(i*W+j);
}
function xyFromID(s) {
var t = parseInt(s.substring(1)),
j = t%W, i = (t-j)/W;
var x = j, y = H-i-1;
return [x, y];
}
function Empty(x, y) {
return !$('#'+IDString(x, y)).hasClass('blot-on');
}
function Fill(x, y) {
$('#'+IDString(x, y)).addClass('blot-on');
}
function Unfill(x, y) {
$('#'+IDString(x, y)).removeClass('blot-on');
}
function DoBlot(x, y) {
if (Empty(x+1, y) && Empty(x, y+1)) {
Fill(x+1, y);
Fill(x, y+1);
Unfill(x, y);
}
}
Fill(0, 0);
$('.blot').on('click', function() {
var t = xyFromID(this.id);
var x = t[0], y = t[1];
console.log(t);
if (!Empty(x, y)) {DoBlot(x, y);}
});
/*
border-box
http://www.paulirish.com/2012/box-sizing-border-box-ftw/
*/
html {
box-sizing: border-box;
}
*, *:before, *:after {
box-sizing: inherit;
}
body {
background: #aaa;
font: 14px 'Microsoft YaHei', 微软雅黑, Arial, Lucida Grande, Tahoma, sans-serif;
color: #000;
text-shadow: 0px 1px 0px #d1d1d1;
}
div.container {
position: absolute;
top: 50%;
left: 50%;
margin-top: -200px;
margin-left: -200px;
width: 250px;
height: 400px;
font-size: 0px; /* remove inline-block space */
}
/*
inline-block
http://ued.taobao.org/blog/2012/08/inline-block/
*/
.blot {
background-color: #222;
width: 10px;
height: 10px;
border: #aaa;
border-style: solid;
border-width: 1px;
display: inline-block;
}
.blot-on {
background-color: #d00 !important;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment