예제 #1
0
func (p *paddle) draw(canvasEl *dom.HTMLCanvasElement) {
	newYPos := p.yPos + p.yMovement
	if newYPos > 5 && newYPos < (canvasEl.Height-p.height-5) {
		p.yPos = newYPos
	}

	ctx := canvasEl.GetContext2d()
	ctx.FillStyle = "#0000ff"
	ctx.FillRect(p.xPos, p.yPos, p.width, p.height)
}
예제 #2
0
func (b *ball) draw(canvasEl *dom.HTMLCanvasElement) {
	b.xPos += int(math.Floor(b.xMovement + 0.5))
	b.yPos += int(math.Floor(b.yMovement + 0.5))

	ctx := canvasEl.GetContext2d()
	ctx.FillStyle = "red"
	ctx.BeginPath()
	ctx.Arc(b.xPos, b.yPos, b.radius, 0, 6, false)
	ctx.Fill()
	ctx.ClosePath()
}
예제 #3
0
func newCanvas(canvasEl *dom.HTMLCanvasElement) *canvas {
	c := &canvas{canvasEl: canvasEl, event: make(chan string)}

	canvasEl.AddEventListener("keydown", false, func(event dom.Event) {
		c.handleKeyDown(event.(*dom.KeyboardEvent))
	})

	canvasEl.AddEventListener("keyup", false, func(event dom.Event) {
		c.handleKeyUp(event.(*dom.KeyboardEvent))
	})

	go func() {
		ticker := time.NewTicker(time.Duration(1000/animationFramesPerSecond) * time.Millisecond)
		for {
			<-ticker.C

			c.draw()

			if c.checkLost() {
				c.bll = nil
				c.event <- "L"
			} else {
				c.checkTopBottomCollision()
				c.checkPaddleCollision()
				if c.checkOverNet() {
					rad := math.Atan2(c.bll.yMovement, c.bll.xMovement)
					deg := rad * radianToDegree
					if deg < 0 {
						deg = 360 + deg
					}
					speed := math.Floor(c.bll.xMovement/math.Cos(rad) + 0.5)
					if speed < 2 {
						speed = 2
					}
					c.event <- fmt.Sprintf("N,%d,%d,%d", c.bll.yPos, int(deg), int(speed))
					c.bll = nil
				}
			}
		}
	}()

	return c
}