From 88ecbf63625e3ce4c4fcfb9f19b0594ea88d007c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dawid=20Wysoki=C5=84ski?= Date: Sat, 2 Dec 2023 07:48:46 +0000 Subject: [PATCH] feat: random direction of the ball at the beginning of the match/after a restart (#4) Reviewed-on: https://gitea.dwysokinski.me/classic-games/tennis-game/pulls/4 --- internal/ball.go | 25 +++++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/internal/ball.go b/internal/ball.go index f9b18c3..e4a2ffb 100644 --- a/internal/ball.go +++ b/internal/ball.go @@ -3,6 +3,8 @@ package internal import ( "image" "image/color" + "math/rand" + "time" "github.com/hajimehoshi/ebiten/v2" "github.com/hajimehoshi/ebiten/v2/vector" @@ -20,23 +22,25 @@ type ball struct { const ( ballBaseRadius = 5 - ballBaseSpeedX = 1 - ballBaseSpeedY = 1 + ballBaseSpeedX = 1.5 + ballBaseSpeedY = 1.5 ) func newBall(screenWidth, screenHeight int) *ball { fScreenWidth := float32(screenWidth) fScreenHeight := float32(screenHeight) + r := ballBaseRadius * fScreenHeight / BaseHeight x := fScreenWidth/2.0 - r y := fScreenHeight/2.0 - r + return &ball{ x: x, y: y, initX: x, initY: y, - speedX: ballBaseSpeedX * fScreenWidth / BaseWidth, - speedY: ballBaseSpeedY * fScreenHeight / BaseHeight, + speedX: randSpeedDirection() * ballBaseSpeedX * fScreenWidth / BaseWidth, + speedY: randSpeedDirection() * ballBaseSpeedY * fScreenHeight / BaseHeight, r: r, } } @@ -99,6 +103,8 @@ func (b *ball) nextSpeed(bounds image.Rectangle, obstacles ...image.Rectangle) ( func (b *ball) reset() { b.x = b.initX b.y = b.initY + b.speedX *= randSpeedDirection() + b.speedY *= randSpeedDirection() } func (b *ball) resize(x, y float32) { @@ -114,3 +120,14 @@ func (b *ball) resize(x, y float32) { func (b *ball) bounds() image.Rectangle { return image.Rect(int(b.x-b.r), int(b.y-b.r), int(b.x+b.r), int(b.y+b.r)) } + +func randSpeedDirection() float32 { + //nolint:gosec + r := rand.New(rand.NewSource(time.Now().Unix())) + + if r.Intn(101) >= 50 { + return -1 + } + + return 1 +}