開発環境
- OS X El Capitan - Apple (OS)
- Emacs (Text Editor)
- JavaScript (プログラミング言語)
- jQuery (Library)
- Safari(Web browser)
Javascript for Kids (Nick Morgan 著、Angus Croll 寄稿、Miran Lipovaca イラスト、No Starch Press)のPart 2(Advanced JavaScript)、Chapter 12(Object-Oriented Programming)、PROGRAMMING CHALLENGES(No. 3417)を取り組んでみる。
PROGRAMMING CHALLENGES(No. 3417)
コード(Emacs)
<!doctype html>
<html>
<head>
<title>Find the buried treasure! </title>
</head>
<body>
<div id="div0" style="height:450px">
</div>
<div id="div1">
<button id="start0">start</button><button id="restart0">restart</button>
</div>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js"></script>
<script src="car.js"></script>
</body>
</html>
/*jslint browser : true, continue : true,
devel : true, indent : 4, maxerr : 50,
newcap : true, nomen : false, plusplus : false,
regexp : false, sloppy : true, vars : false,
white : false
*/
/*global $*/
var Car,
tesla,
nissan,
timer,
$div = $('#div0'),
$start = $('#start0'),
$restart = $('#restart0'),
div_left = $div.position().left,
div_top = $div.position().top;
Car = function (x, y) {
this.x = x;
this.y = y;
this.draw();
};
Car.prototype.draw = function () {
var car_html = '<img src="http://nostarch.com/images/car.png">';
this.car_element = $(car_html);
this.car_element.css({
position: 'absolute',
left: this.x,
top: this.y
});
$div.append(this.car_element);
};
Car.prototype.moveRight = function (distance) {
this.x += distance;
this.car_element.css({
left: this.x,
top: this.y
});
};
tesla = new Car(div_left + 20, div_top + 150);
nissan = new Car(div_left + 20, div_top + 300);
$('#div1').css({
position: 'absolute',
top: div_top + 350
});
$start.click(function () {
timer = setInterval(function () {
var tesla_speed = Math.floor(Math.random() * 6),
nissan_speed = Math.floor(Math.random() * 6);
tesla.moveRight(tesla_speed);
nissan.moveRight(nissan_speed);
}, 30);
});
$restart.click(function () {
clearInterval(timer);
$div.html('');
tesla = new Car(div_left + 20, div_top + 20);
nissan = new Car(div_left + 20, div_top + 150);
});
0 コメント:
コメントを投稿