Files
learngo/x-tba/slices/21-bouncing-ball-project
2019-03-14 18:57:51 +03:00
..
2019-03-14 18:57:51 +03:00
2019-03-14 18:57:51 +03:00
2019-03-14 18:57:51 +03:00
2019-03-14 18:57:51 +03:00

Bouncing Ball Challenge Tips

Use the following tips only when you get stuck. This document isn't in a particular order, please do not follow it like so.

Ball position and velocity

You can use velocity to change the ball's speed and position. In my example, the speed is constant, so I always use unit value: 1.

On each loop step: Add velocities to ball's position. This will make the ball move.

CREATE THE BOARD

I use [][]bool for the board but you can use anything you like. For example, you can directly use [][]rune or []rune. Experiment with them and decide which one is the best for you.

CLEAR THE SCREEN

  • Before the loop, clear the screen once by using my screen package.

  • After each loop step, move the cursor to the top-left position by using the screen package. So that you can draw the animation frame all over again in the same position.

  • It's here.

  • Its documentation is here.

  • You can find more information about it in the Retro Clock project section.

DRAW THE BOARD

Instead of drawing the board and the ball to the screen everytime, you will fill a buffer, and when you complete, you can draw the board and the ball once by printing the buffer.

I use a []rune buffer because rune can store an emoji character, and I use a slice of runes because I want to draw empty cells and a ball in the end.

  • Make a large enough rune slice named buf using the make function.

    • HINT: width * height will give you a large enough buffer.

    • TIP: You could also use string concatenation to draw into a string buffer but it would be inefficient.

    • You will find more information about bytes and runes in the strings section.

// TIP for converting the buffer
var buffer []rune

// For printing, you can convert a rune slice to a string like so:
str := string(buffer)

SLOW DOWN THE SPEED

Call the time.Sleep function to slow down the speed of the loop a little bit, so you can see the ball :)

time.Sleep(time.Second / 20)