<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>game 1</title>
<style type="text/css">
canvas{
border: 1px solid #eee;
}
</style>
</head>
<body>
<canvas id="canvas" width="400" height="300"></canvas>
<script type="text/javascript">
var log = console.log.bind()
var imageFromPath = function (path) {
var img = new Image()
img.src = path
return img
}
var Paddle = function () {
var image = imageFromPath('https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=2323943722,3696495464&fm=26&gp=0.jpg')
var o = {
img: image,
x: 200,
y: 150,
w: 120,
h: 60,
speed: 15,
}
o.moveLeft = function () {
o.x -= o.speed
}
o.moveRight = function () {
o.x += o.speed
}
o.collide = function (image) {
if (image.y + image.img.height > o.y && image.y < o.y + o.img.height) {
if (image.x > o.x && image.x < o.x + o.img.width) {
return true
}
}
return false
}
return o
}
var Ball = function () {
var image = imageFromPath('https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1504301500648&di=df06cc9f705e9355769e468413924d32&imgtype=jpg&src=http%3A%2F%2Fimg0.imgtn.bdimg.com%2Fit%2Fu%3D2346240780%2C32583404%26fm%3D214%26gp%3D0.jpg')
var o = {
img: image,
x: 200,
y: 150,
w: 60,
h: 30,
speedX: 10,
speedY: 10,
fired: false,
}
o.fire = function () {
o.fired = true
}
o.move = function () {
if (o.fired) {
if (o.x < 0 || o.x + o.w > 400) {
o.speedX *= -1
}
if (o.y < 0 || o.y + o.h > 300) {
o.speedY *= -1
}
o.x += o.speedX
o.y += o.speedY
}
}
return o
}
var Game = function () {
var g = {
actions: {},
keydowns: {},
}
var canvas = document.querySelector("#canvas")
var ctx = canvas.getContext("2d")
g.canvas = canvas
g.ctx = ctx
window.addEventListener("keydown",function (e) {
g.keydowns[e.key] = true
})
window.addEventListener("keyup",function (e) {
g.keydowns[e.key] = false
})
g.registerAction = function (key,cb) {
g.actions[key] = cb
}
g.clean = function () {
g.ctx.clearRect(0,0,g.canvas.width,g.canvas.height)
}
g.drawImage = function (image) {
g.ctx.drawImage(image.img,image.x,image.y,image.w,image.h)
}
setInterval(function () {
var actions = Object.keys(g.actions)
for (var i = 0; i < actions.length; i++) {
var key = actions[i]
if (g.keydowns[key]) {
g.actions[key]()
}
}
g.update()
g.clean()
g.draw()
},1000/30)
return g
}
var __main = function () {
var paddle = Paddle()
var game = Game()
var ball = Ball()
game.update = function () {
ball.move()
if (paddle.collide(ball)) {
ball.speedY *= -1
}
}
game.draw = function () {
game.drawImage(paddle)
game.drawImage(ball)
}
game.registerAction('a',function () {
paddle.moveLeft()
})
game.registerAction('d',function () {
paddle.moveRight()
})
game.registerAction('f',function () {
ball.fire()
})
}
__main()
</script>
</body>
</html>