My first game (CodePen) via /r/learnprogramming


My first game (CodePen)

Hello, I've been learning programming for a few months now and this is my first attempt at a simple game.

http://ift.tt/2sWsWfK

CONTROLS:

SPACE -> starts/pauses game

R -> Restart

ARROW KEYS -> movement

You can see the code in JavaScript by going into upper-right corner 'Change View' and select 'Editor View'.

I bet there are much better ways to do this stuff.

I've got some questions about the game:

Normally, how do you create a simple 'game loop' in JavaScript ? I use Interval(function(){draw;},1000/24); basically calling the function that draws the snake 24 times per second, but I'm sure there are better ways to do this. I'm open to all kinds of suggestions.

The other thing is about how I spawn the 'apples'. I basically use Math.random() to find random coords [x,y] and see if it collides with any part of the snake, if those coords are invalid and collide I generate a new pair of coords until I find an empty space.

Now the problem with this system is how ineficient it is, since Math.random() could potentially generate the same invalid coords more than once before finding a viable spot.

Finally, I hate how you can go 'under' or 'beyond the edge' of the screen. If you manage to change direction just as you hit one of the edges of the canvas you won't appear on the oposite side of the screen but keep going on the limit, your position will be the maximum possible and the snake won't be visible since there'll be not enough space to draw it.

It would be best if as you cross the edge of the left side of the canvas you started to appear on the right side, in a way that you could be half in one side and half in the opposite side. Right now, you'll either be in the left side or in the right.

Sorry in advance if this is not the correct subreddit for this kind of post.

Submitted July 13, 2017 at 11:01PM by Luckyno
via reddit http://ift.tt/2tOZ33R

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s