Assignment 5: The Snake Game


Question 2: Snake Control [2 marks



Download 291.77 Kb.
View original pdf
Page5/7
Date10.03.2024
Size291.77 Kb.
#63800
1   2   3   4   5   6   7
Assignment5-COMP1010-Fall2022
ComputerNetworks
Question 2: Snake Control [2 marks
Now use the keyboard to control the motion of the snake. Use the special
keyPressed()
function. When the user presses the L or D key the snake should turn clockwise, and when the user presses the A or J key the snake should turn counterclockwise. Accept both upper and lowercase letters. The keys do not directly control the snake’s direction. They control how the snake turns. That makes the game more fun (or more annoying, depending on your point of view. Use a simple
int
variable to keep track of the snake’s current direction (down, left, up, or right, using the values 0 to 3 only. The easiest way to translate this direction into the x and y values needed by the
moveSnake
function is to use two constant arrays
final int X_DIRECTIONS = {0,-1,0,+1}; X change for down, left, upright
final int Y_DIRECTIONS = {+1,0,-1,0}; Y change for down, left, upright
Note that the four directions are in clockwise order.
Question 3: Add Apples [2 marks
Add another pair of partially-full arrays to store the position of the apples, including a variable that keeps track of the current number of apples (which will change, starting in Question 4). Define a variable
startingApples=5
which controls how many apples should appear at the start of each level. This works exactly the same way that
startingLength
does, but for apples, not the snake. Unlike the snake, the apples appear at random locations. Define a function
int[] randomArray(int n, int max)
which will create and return an array of exactly
n
int
values, randomly chosen from the values 0 to
max
. For example,
randomArray(5,3)
might return the array
{0,3,1,3,2}
. Define a function
resetApples()
which will use
randomArray
to pick a random set of

Download 291.77 Kb.

Share with your friends:
1   2   3   4   5   6   7




The database is protected by copyright ©ininet.org 2024
send message

    Main page