Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Java BRIDGES Project: Rainbow Snake Game Starter Code File: RamSnakeGame.java Introduction You will use the BRIDGES NonBlockingGame class to make the classic snake game. A

Java BRIDGES Project: Rainbow Snake Game

Starter Code File: RamSnakeGame.java

Introduction

You will use the BRIDGES NonBlockingGame class to make the classic snake game. A player moves a snake (line of sprites) along a 2D grid attempting to run over and eat a randomly placed apple, with the snake growing in size for each apple eaten.

If it runs into itself the game is over and the player has lost. The object of the game is to make the snake as big as possible to earn a high point score.

Major Tasks

Initialize a 2D array the size of your game grid.

Initialize the NamedColors of your background, snake, and object.

Complete the mplemention the initialize method to set up the game

Implement a method called changeDirection that allows the player to control the direction of the snakes head.

Implement the draw method to update game in progress

Getting Started

Create a new project/folder in your IDE of choice called Project2

Import the BRIDGES external library into your project if your IDE of choice does not automatically do so.

Create a new cmsc256 package. You can then import the starter file, or create a new Java file called RamSnakeGame.java that extends the.NonBlockingGame class and copy the starter code.

Imports

There are five imports in the RamSnakeGame class.

util.ArrayList, the standard Java class for creating variable-length lists.

base.NamedColor is an enumeration class containing all the colors we are allowed to use in our game.

base.NamedSymbol is an enumeration class containing all the symbols we are allowed to use in our game.

util.Random. Is a class used for generation random numbers

games.NonBlockingGame enables the use of the NonBlockingGame

class for reacting to keyboard input and displaying colors. The SnakeGame class extends NonBlockingGame, which causes the initialize and gameLoop methods to be called automatically.

Class variables

Look at the top of the class where the member variables are located and read over the comments to understand what each represents with respect to the game.

The snake starts out with a length of three, heading in the right direction. Therefore when starting the game some variables will look like this:

snake: [ [5, 5], [5, 4], [5, 3], [5, 2] ]

moves: [ [0, 1], [0, 1], [0, 1], [0, 1] ]

dir: right

The dir variable controls what direction the snake is moving, and determines what to add to the moves array which controls the snake's movement.

Constructor

Add statements inside the constructor to set the title and description of your game. The title should be RamSnake and the description must include your name, course number, and section.

Initialize the backgroundColor as a NamedColor of your choice.

Add a call to the start method.

main method

In the main method, add your Bridges User ID, and Bridges API Key to the instantiation of the RamSnakeGame object.

initialize method

The RamSnakeGame class extends the NonBlockingGame class, which means the initialized class will be called at the beginning of the program. We will also be using this to reset the game when you restart it.

Reset the frames and points by setting them to 0

Set the gameOver variable to false and the starting direction to right

Set the background and clear all symbols.

Initialize the snake and moves ArrayLists then add four parts to the snake ArrayList and four moves to the moves ArrayList (see the example in the Class Variables section of this page)

Initialize the apple location by instantiating the array with two values for the row and column location for the apple.

draw method

The draw method draws the snake and apple on the board.

First erase the part of the snake that has been moved to a new tile. This location is stored in the lastPos array.

Use a for loop to transverse the snake array and draw it as a rainbow of colors. Use the colorList Array(you can find it at the top of the class) and Mod(%). Feel free to edit the colorList Array to make the snake be any pattern of colors you want. Find all the colors in NamedColor

Finally draw the apple in. Use NamedSymbol.apple and draw it in at the location stored in Array apple.

changeDirection method

This method is called whenever we change the snake's direction

First set the String oppositeDirection to the opposite of the current direction the snake is going.

Compare the opposite direction and the new direction the snake is going. If the new direction is the same as the opposite direction, do not change its direction. If they are different, it means this is a valid move for the snake and set the String dir, which controls the snake's direction, to the new direction.

Add this move to the move List depending on the dir value by calling the provided addMove method and passing the adjustments needed for the row and column to change the direction.

More Details to Get You Started

Key Press Events - NonBlocking Games

keyUp()

keyDown()

keyLeft()

keyRight()

keyQ()

keySpace()

keyW()

keyS()

keyA()

keyD()

Key Press Events - Blocking Games

getKeyPress(); Returns a string.

"ArrowLeft"

"ArrowRight"

"ArrowUp"

"ArrowDown"

"w"

"s"

"a"

"d"

etc...

Variables, Colors, and Sprite Symbols

NamedSymbol.symbolname;

NamedColor.colorname;

drawObject(column, row, NamedSymbol, NamedColor);

setBGColor(column, row, NamedColor);

Important Functions

The gameLoop() function loops until the game is over.

quit() stops the game.

start() starts the game and calls the initialize() function once before it starts the gameLoop() function.

render() sends your updated game grid to the server once. This is a blocking game function.

package cmsc256; import bridges.games.NonBlockingGame; import bridges.base.NamedColor; import bridges.base.NamedSymbol; import java.util.Random; import java.util.ArrayList; public class RamSnakeGame extends NonBlockingGame{ static int[] boardSize; // controls board size (rows, cols) private static NamedColor[] colorList; // colors for snake private static final int ASSIGNMENT_NUMBER = 2; private NamedColor backgroundColor; // background color private ArrayList snake; //location of all snake parts private ArrayList moves; //moves that each part of the snake will take private int[] apple; //location of apple private String dir; //direction snake is moving private int frame; //num of frames private int points; //points you have private boolean gameOver; private int[] lastPos = {0, 0}; private int[] temp; private Random randomGenerator = new Random(); //constructor public RamSnakeGame(int assid, String login, String apiKey, int r, int c){ // set up bridges super(assid, login, apiKey, r, c); // set title (add you name to the title) and provide a description with instructions // initialize background color // start the game engine } public static void main(String args[]) { //enter your username and api key here RamSnakeGame mg = new RamSnakeGame(ASSIGNMENT_NUMBER, "USERNAME", "API_KEY", boardSize[0], boardSize[1]); } public void initialize() { //set frames and points variables to 0 //set gameOver to false //and make the starting direction be "right" // using nested for loops for each tile, // set the background color and set the symbol to None //reset snake and moves Lists with an empty list //add some parts to snake //add moves for each snake part // set starting position for the apple } private void draw() { // Change the last location of the snake to the color of the board. // Use the lastPos array // Use a loop to tranverse the Snake arraylist and // draw the snake on all the tiles //draw in the apple using an apple symbol } private void changeDirection(String newDirection) { // check what direction the snake is going and // set the String oppositeDirection to the opposite of that direction String oppositeDirection; // check to see if newDirection is equal to oppositeDirection. // Since the snake can't turn around and go back on itself, // we can only change the direction if is not turning completely around // If they are not equal, then the change in direction is allowed and // you can update its direction. // based on the dir that was just set, add a move to the moves List } private void handleInput() { //test to see if each key is pressed, and call function change direction; if(keyLeft()) changeDirection("left"); else if(keyRight()) changeDirection("right"); else if(keyUp()) changeDirection("up"); else if(keyDown()) changeDirection("down"); else //call function but dont change direction changeDirection(dir); } private boolean moveSnake() { //returns true if snake moves into a spot which would mean game over //set last pos to pos of last part of snake lastPos[0] = snake.get(snake.size() - 1)[0]; lastPos[1] = snake.get(snake.size() - 1)[1]; //look at new pos of snake int newCol = snake.get(0)[0] + moves.get(0)[0]; int newRow = snake.get(0)[1] + moves.get(0)[1]; //see if it is a valid move if(newRow < 0 || newRow > boardSize[1] - 1) return true; if(newCol < 0 || newCol > boardSize[0] - 1) return true; for(int i = 0; i <=snake.size() - 1; i++) { if(snake.get(i)[0] == newCol && snake.get(i)[1] == newRow) return true; } //test to see if you are moving to space with apple in it if(newCol == apple[0] && newRow == apple[1]) { //increase points and move apple points++; grow(); //remove apple symbol drawSymbol(apple[0], apple[1], NamedSymbol.none, NamedColor.red); //move apple to new spot apple[0] = randomGenerator.nextInt(boardSize[0]); apple[1] = randomGenerator.nextInt(boardSize[1]); //make sure new apple is not on a space with a snake on it while(inSnake(apple)) { apple[0] = randomGenerator.nextInt(boardSize[0]); apple[1] = randomGenerator.nextInt(boardSize[1]); } } //move each part of the snake to a new position for(int i = 0; i < snake.size(); i++) { snake.get(i)[0] += moves.get(i)[0]; snake.get(i)[1] += moves.get(i)[1]; } return false; } public void gameLoop() { //moves every 4 frames and if the game is not over if(frame % 4 == 0 && !gameOver) { //handles input to move snake handleInput(); //moves snake returns true if game is over if(moveSnake()) { //end game and print out points gameOver = true; System.out.println("Game Over you got " + points + " points"); } //update snake and apple on screen draw(); } //if game is over and space key is pressed the restart the game if(gameOver && keySpace()) initialize(); //incrmement frames frame++; } //add move to moves private void addMove(int y, int x) { //creates new array of x and y move temp = new int[2]; temp[0] = y; temp[1] = x; //adds it to moves moves.add(0, temp); //removes the last move that is replaced by new one moves.remove(moves.size() - 1); } private void grow() { //grow snake temp = new int[2]; //calculate where the new snake part should go temp[0] = snake.get(snake.size() - 1)[0] - (snake.get(snake.size() - 2)[0] - snake.get(snake.size() - 1)[0]); temp[1] = snake.get(snake.size() - 1)[1] - (snake.get(snake.size() - 2)[1] - snake.get(snake.size() - 1)[1]); //add new part to snake snake.add(temp); //creates new move to correspond with new part of the snake temp = new int[2]; temp[0] = moves.get(moves.size() - 1)[0]; temp[1] = moves.get(moves.size() - 1)[1]; moves.add(temp); } //checks to see if location is part of the snake private boolean inSnake(int[] x) { //looks at all snake parts and checks to see of a location is ewuall to that parts loc. for(int[] i : snake){ if(i[0] == x[0] && i[1] == x[0]) return true; } return false; } }

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Advances In Spatial And Temporal Databases 10th International Symposium Sstd 2007 Boston Ma Usa July 2007 Proceedings Lncs 4605

Authors: Dimitris Papadias ,Donghui Zhang ,George Kollios

2007th Edition

3540735399, 978-3540735397

More Books

Students also viewed these Databases questions