面向对象学习
面向对象:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>寻找徐峥</title>
<style>
* {
padding: 0;
margin: 0;
}
</style>
</head>
<body>
<script>
class SearchXuZheng {
constructor(parent, w, h) {
this.parent = parent || document.body;
this.WIDTH = w || 600;
this.HEIGHT = h || 600;
this.lv = 1;
this.list = [];
this.divCon = this.createDiv();
this.createGame();
}
clearGame() {
for (let i = 0; i < this.list.length; i++) {
this.list[i].remove();
this.list[i] = null;
}
this.list.length = 0;
}
clickHandler(e) {
if (e.target.constructor === HTMLDivElement) return;
if (~e.target.src.indexOf('1')) {
this.self.lv++;
}
this.self.clearGame();
this.self.createGame();
}
createGame() {
for (let i = 0; i < Math.pow((1 + this.lv), 2); i++) {
var img = new Image();
img.src = './img/2.png';
Object.assign(img.style, {
width: this.WIDTH / (this.lv + 1) + 'px',
height: this.HEIGHT / (this.lv + 1) + 'px'
})
this.divCon.appendChild(img);
this.list.push(img);
}
this.list[Math.floor(Math.random() * this.list.length)].src = './img/1.png';
}
createDiv() {
if (this.divCon) return;
var div = document.createElement('div');
Object.assign(div.style, {
width: this.WIDTH + 'px',
height: this.HEIGHT + 'px',
margin: 'auto',
border: '1px solid black',
fontSize: '0'
})
div.self = this;
div.addEventListener('click', this.clickHandler);
this.parent.appendChild(div);
return div;
}
}
var game = new SearchXuZheng();
</script>
</body>
</html>