Snake Game Movement Algorithm
Jun 16, 2014I am working on replicating this project: [URL] ....
What is wrong with the moveSnake method and the for loop within it?
I am working on replicating this project: [URL] ....
What is wrong with the moveSnake method and the for loop within it?
gridworld snake game all over the internet, but all of those are the "snakebug extends Bug" version, mine is different. im behind everyone else in apcs so i rarely have any idea what im doing(gridworld especially). our teacher gave us most of the code, which i coped down (hopefully correctly) and he told us that we still needed to fill in the "removeTail" method which i did. basically the snake moves by placing a segment in front then removing the last segment.
When i click run the snakerunner file, i can make the snake segment rotate by pressing the arrow keys, but it doesn't move. when i click the "run" on the gridworld window, the single snake segment just disappears. so the move method is triggering the "removetail" method but it isn't placing the next segment. im starting to think that i copied something wrong from the board, because he showed us the entire move method. i have attached my gridworld files, what is wrong with my snake.java that makes the move method delete a segment but not add one
I'm trying to create a simple snake game, but I can't get my timer and keyListener to work...
//Timer
Timer tm = new Timer(5, this);
int x = 50, y = 250, vel = 2;
// The snake
g.setColor(Color.black);
g.fillRect(x, y, snakeSize, snakeSize);
[Code] .....
I tried to make a runnable snake game. When i try to run my code i get this:
Exception in thread "main" java.lang.NullPointerException
at Game.Move(Game.java:85)
at Game.run(Game.java:244)
at Game.main(Game.java:38)
The game runs, but the snake doesn't move, and apples are spawned everywhere.
Here are Move, run and main code:
public static void main(String[] args) {
JFrame frame = new JFrame("Snake");
Game game = new Game();
frame.add(game);
frame.setSize(406, 430);
frame.setVisible(true);
frame.setResizable(false);
[Code] .....
I am busy programming a clone of the popular phone game they had on Nokia cellphones a long time ago called Snake II but since I know very little about programming I will be using ASCII graphics instead of a 2D graphics engine.
My idea for implementation is having a main class called game which should refresh a grid of ascii characters every, say 0.2 seconds. Then I have another class called Dot. Each Dot object has x and y coordinates, and a direction in the x and y planes (dirx = -1 means left, dirx = 1 means right, diry = 1 means up, diry = -1 means down, and obviously the snake cant move the diagonals)
The Game class prints a "*" symbol where the Dot is, and what I'm trying to do is get the screen to refresh (I think I need to use the sleep() function for this to slow the game down to a reasonable pace), and go in the direction it is supposed to go.
(I haven't programmed this in yet but the snake will be an array of Dot, and at each refresh Dot at position 0 will pass it's coordinates and direction to Dot at position 1, Dot1 to Dot2, Dot2 to Dot3, etc.
Here's my code so far:
A first class called Game.
Java Code: //Not done yet but this is the start to my game of Snake. Basically the class Game generates a Grid of ASCII characters
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
final int WIDTH = 79;
[Code] .....
My problem now is that I am taking input from the Scanner class. What it does is wait for my input, then it goes on to executing the rest of the code in other words refresh the ASCII grid. This is a problem because I need the snake to keep moving at constant pace while listening to the keyboard.
How can I get my while loop to keep going (i will add a sleep() function later) while listening to the keyboard without stopping?
I'm relatively new to Java, I'm trying to create a text based game, like those old ones where you type "north" or "east" to move as such, and "look" to inspect the area. My only problem thus far has been trying to figure out just how I should... "structure?" the movement. As in, what's the best overall way to approach this? I've tried making a new method for every area and just passing a variable called "location," but along with passing the inventory and stat arrays, it's just become messy. Or is this a good way to do it? I have a separate method for when the player enters something, but then how will it know which description to give when the player types "look?"
View Replies View RelatedI'm working on this space invaders game and I've been stuck trying to get the alien spaceships to move down in one group. The way we have to design the game is we have to implement at least these 3 classes. These classes are GameData,GamePanel, and Animator. GameData is all the action figures/models in the game. GamePanel draws all game action figures/ models on the screen. Animator updates periodicaly action figures positions,sizes, colors etc. I can get the aliens to move right but once they hit the end of the canvas I cannot figure out how to get them to move as a group down and then begin moving left. I tried to add alien objects to the GameFigures list and then have the update method in the Alien class be responsible for moving the alien ships, but I couldn't figure out how to make it work. So then I made an alienFigures list in the GameData class and I still cannot figure out what to do. Here is the GameData class
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
[code]....
I made a kind of maze game that includes the class keylistener and orients a object, i can't find where the program tracks this object (where its x and y coordinates are). So now my object can move freely through all walls and i want it to bounce back or at least something to happen when the object reaches a wall.
I want to find a way to limit my objects movement and because i cant find where the coordinates or variable for this object is i cannot limit its movement
I have been trying to create an algorithm for the computer in my Tic-Tac-Toe game? So I searched for some good ones, and found about this confusing but effective algorithm, at least if you get it working, called Minimax. I tried implementing it into my game. Let's say it was easier said than done. Sometimes I think it's working, but sometimes it doesn't work at all. How do I get my algorithm working? What the variables BEST_SCORE_COMPUTER and BEST_SCORE_PLAYER in my code should have as starting values.
Java Code:
import java.util.Scanner;
public class TicTacToe{
private static char BOARD[] = {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '}; // This is the main board itself.
private static int ROWS[][] = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {0, 3, 6}, {1, 4, 7}, {2, 5, 8}, {0, 4, 8}, {2, 4, 6}}; // These are all the rows one can win by filling.
private static int SCORE, BEST_MOVE_COMPUTER, BEST_SCORE_COMPUTER = -1, BEST_SCORE_PLAYER = 1; // These variables speak for themselves.
private static byte TURN = 1; // 1 means player's turn, and 2 means computer's turn.
[Code] .....
I have a checker game already and I am trying to make an AI opponent even if not so Intelligent as long as it can move chips on its own until the game is over.
View Replies View RelatedI'm trying to make a checkers game in Java and I managed to make my grid with it's button on it. Each button which has a pawn on it has it's own actionListener which was all done in the loop as I made the grid as shown in my code below. Now I have a huge problem. I don't know how to handle the move, check if move is legal, jump and double jump. Here is the code I wrote so far. I wrote it in such a way that all the buttons which have a pawn on them can perform the same action but then I'm completely stuck.
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class CheckerBoard extends JPanel{
public static final int WIDTH = 530;
public static final int HEIGHT = 530;
private JButton[][] grids;
[Code] .....
I am making an android racing game. I have a method that draws the track to the screen, the map is bigger than the screen so i clip the bitmap and draw it to the screen hence to draw the track I have to get the visible track points and then draw them. I have noticed that when I enable drawing the track the game lags quite a bit but when i disable it is smooth as expected the code is below :
public void drawTrack(Canvas canvas) {
if (this.trackPoints != null && this.trackPoints.size() > 0) {
// get points, convert back to screen coords and add them to array,
// then
// use that arraylist<point> below
getCurrentVisibleTrack();
counter++;
if (this.visibleTrackPoints.size() > 0) {
[Code] .....
I am having a problem with my java program. My goal is to request the user to enter how many times they want to roll a pair of dices. Each dice have numbers 1-6. When rolling the dices, I randomly pick a number from each dice and total the number. My goal is to calculate the number of times snake-eyes was rolled which is a total of 2 and total number of times a total of 7 was rolled. Here is my code. I am calling the rollDice method to perform the random pick and calculations. The error I am getting is at the bottom of the code.
package dice;
import java.util.Scanner;
import java.util.Random;
public class Dice
{
public static void main(String[] args)
{
int numRolls; // number of rolls
[code]...
How many times would you like to roll the two dice? 1000 Exception in thread "main" java.lang.NullPointerException at dice.Dice.main(Dice.java:40)
Java Result: 1 BUILD SUCCESSFUL (total time: 4 seconds)
I have been working on this mouse movement code that detects which direction the mouse moves in hope to use it in a game. The only problem is that I can not figure out how to make it move to the other side of the screen so I could continue turning to the right or left without having to stop. How would I actually get the x and y coordinants of the mouse to change?
PHP Code: if(x == xscreen){
//set x to 0
}else if(x == 0){
//set x to xscreen
}else if(y == yscreen){
//set y to 0
}else if(y == 0){
//set y to yscreen
} mh_sh_highlight_all('php');
First, I have a figure that moves around the screen. It uses keylisteners and just subtracts or adds pixels. However, I notice the movement is not smooth at all. It is very rigid and laggy movement. How can I make it smoother movement?
Second, you get three lives in the game. The lives are subtracting correctly, but I want the game to say "GAME OVER" on a dialog box. How would I get this to happen? My JFrame and my life int are in separate classes. I know I should use an if statement, saying if lives are at or less than zero, open the box, but how do I open the box?
Third, I want to display the time on the screen. I have a swing timer, but how do I put it on the screen? DrawString is not working for me.
Fourth, I want to set an icon for the game, the code is running, but not doing anything.
Java Code: frame.setIconImage(Toolkit.getDefaultToolkit().getImage("/Users/MW/Downloads/petericon.jpg")); mh_sh_highlight_all('java');
I am new to DreamInCode! I was creating a game using OpenGL (and slick for textures).
Using Vector3f, I make coordinates to where my camera is camera'ing (and rotation).
It was working... until I modified something. I only added shaders. When I took the shaders off I think I might of accidentally deleted something. Nonetheless the code looks perfect to me.
On the method "input()" everything runs. No errors are thrown anywhere. I have syso'd the hell outa my code. It shows no signs of breaks. I can, however, move elements I put into my program. I am 100% sure that no other class is breaking my game (soon to be).
What you should look out for: I am not really sure about the glLoadIdentity()'s and glMatrixMode(). I am, knowing a good part of, thinking it could be gluViewPort....
My problem: Can't move my camera even tho it was working before.
package com.Hydroque.OpenGlTest;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.util.glu.GLU.gluPerspective;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
[Code] ....
I just started to learn Java. In my program, I created a GRect(paddle) and I would like to move it on the x axis whenever the mouse is moved.
import acm.graphics.*;
import acm.program.*;
import acm.util.*;
import java.awt.*;
import java.awt.event.*;
public class BreakoutClass extends GraphicsProgram {
/** Width and height of application window in pixels */
private static final int WIDTH = 400;
private static final int HEIGHT = 600;
[code]....
In this case, whenever the paddle reaches the right edge of the screen, it doesn't move off the windows, but it stops moving (even if you move the mouse).
I'm working on making a game in JAVA. To be brief, the game is on a 6x6 matrix called "blocks[][]". The game has two players and the objective is to capture the enemies pieces by moving your piece onto there's. The players do this by moving one piece per turn either forward/backward (Vertically) or right/left (horizontal) movements. Essentially checkers without jumps.I'm not very far into the development process here. So far I have the game board created and the pieces load by clicking the "Start" button (handled by the refresh function). However I'm having a few problems... Namely moving the pieces effectively at the moment.
Right now there's a lot to do:
(1) - Implement a turn system,
(2) - Only allow a player to click their pieces (I've a validation function already in place to only permit valid moves [horizontal/vertical only]),
(3) - getting the pieces to actually "move" what I mean by this is a player selects the piece they want to move, then they select the spot they want to move to and the icon I have placed on the button is supposed to be added to the new square and the icon for its previous position is to be made null.
Please see the "actionPerformed" section to see exactly what I'm trying to do and hopefully as well see what I'm missing as to why it is not working at the moment... Also see under the Refresh function where I commented out the for loops to add the pieces. I did this because it was resulting in an ArrayOutofBounds error so I just wrote each spot out manually where I wanted them to start.
/* Ghosts *
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.border.*;
import java.io.*;
[code].....
how I would go about having a moving sprite on a page, such as a virtual pet kind of thing. I've tried searching for it through the years and I've tried it with what I know on my own, but things just act up every time. Either:
A.) The sprite moves (respondent to key strokes, of course), but leaves a trail of its image behind itself.
B.) The background image writes, but for some reason the second image does not write, or is lost behind the background.
I'm sure these are simple issues for most of you, but I've tried going about this for a while now with no luck. What I'm trying to do I'm trying to write a virtual pet game, and I would eventually love to make it move around randomly like an A.I. that's pathfinding, but I've got ideas about that, just I need to know how to make it move period first, everything else I think I could figure out on my own.
I need the following key controlled ellipse to leave a trail behind that vanishes after 10 frames. Also, I need to create a random moving ellipse not related to the preexisting one. How to separate the two ellipses ...
Current code:
boolean left, right, backward, forward;
boolean SPEED;
PVector pos = new PVector(680, 400);
void setup() {
size (680,400);
fill (0 ,0,0);
frameRate(100);
noCursor();
[Code] .....
I've been creating a digital clock using Java, and have made the mouse cursor invisible after a set period of time (40-seconds) and had the thought to make it visible again if mouse was moved.
Here's the code that makes it invisible:
ActionListener mouseTimeout = new ActionListener() {
public void actionPerformed(ActionEvent e) {
setCursor(blankCursor);
}
};
/* Make mouse cursor disappear after 40 seconds */
Timer mTimeout = new Timer(40000, mouseTimeout);
mTimeout.start();
And here is what I have so far for making it visible again:
MouseMotionListener mouse = new MouseMotionListener() {
@Override
public void mouseDragged(MouseEvent e)
{
}
@Override
public void mouseMoved(MouseEvent e)
{
}
};
I have tried using "setCursor(DEFAULT_CURSOR)" but NetBeans says that it "cannot find symbol" .....
My OrderCalculator class is throwing an exception. The input from my HourPanel that is supposed to add to my OrderCalc is cooperating.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.DecimalFormat;
public class OrderCalculator extends JFrame
{
private JobPanel jobs;
private HourPanel rate;
[Code] .....
How to catch the event when table view's column are re-positioned. Basically when the column is re-positioned from 1 position to 5 position , i want to do update the db.
View Replies View RelatedOpoly works this way: The board is a circular track of variable length (the user determines the length when the game app runs). There is only one player, who begins the game at position 0.
Thus, if the board length is 20, then the board locations start at position 0 and end at position 19. The player starts with a reward of 100, and the goal of the game is to reach or exceed reward value 1000. When this reward value is reached or exceeded, the game is over. When the game ends, your program should report the number of turns the player has taken, and the final reward amount attained.
In Opoly the game piece advances via a spinner - a device that takes on one of the values 1, 2, 3, 4, 5 at random, with each of the five spin values equally likely.
Although the board is circular, you should draw the state of the board as a single "line", using an 'o' to represent the current player position, and * represent all other positions. Thus if the board size is 10, then this board drawing:
**o******
means that the player is at location 2 on the board.
Here are the other Opoly game rules:
If your board piece lands on a board cell that is evenly divisible by 7, your reward doubles.
If you land on the final board cell, you must go back 3 spaces. Thus if the board size is 20, the last position is position 19, and if you land there, you should go back to position 16. (If the position of the last cell is evenly divisible by 7, no extra points are added, but if the new piece location, 3 places back, IS evenly divisible by 7, then extra points ARE added).
If you make it all the way around the board, you get 100 points. Note that if you land exactly on location 0, you first receive 100 extra points (for making it all the around), and then your score is doubled, since 0 is evenly divisible by 7,
Every tenth move (that is, every tenth spin of the spinner, move numbers 10,20,30,... etc.), reduces the reward by 50 points. This penalty is applied up front, as soon as the 10th or 20th or 30th move is made, even if other actions at that instant also apply. Notice that with this rule it's possible for the reward amount to become negative.
Here is the driver class for the game:
import java.util.*;
public class OpolyDriver{
public static void main(String[] args){
System.out.println("Enter an int > 3 - the size of the board");
Scanner s = new Scanner(System.in);
int boardSize = s.nextInt();
[Code] ....
heres the methods:
REQUIRED CODE STRUCTURE: Your Opoly class must include the following methods (in addition to the Opoly constructor) and must implement the method calls as specified:
playGame - The top-level method that controls the game. No return value, no parameters. Must call drawBoard, displayReport, spinAndMove, isGameOver.
spinAndMove - spins the spinner and then advances the piece according to the rules of the game. No return value, no parameters. Must call spin and move.
spin - generates an integer value from 1 to 5 at random- all equally likely. Returns an integer, no parameters.
move - advances the piece according to the rules of the game. No return value, takes an integer parameter that is a value from 1 to 5.
isGameOver - checks if game termination condition has been met. Returns true if game is over, false otherwise. No parameters.
drawBoard - draws the board using *'s and an o to mark the current board position. Following each board display you should also report the current reward. No return value, no parameters.
displayReport - reports the end of the game, and gives the number of rounds of play, and the final reward. No return value, no parameters.
Im trying to make a tic tac toe game that you play against the computer using a random number generator and two dimensional arrays for the game board. Im not trying to make a GUI, the assignment is to have the board in the console, which I have done. I have run into a few problems with trying to get the computer player to correctly generate 2 integers and have those two integers be a place on the game board. Here is my code so far.
import java.util.Random;
import java.util.Scanner;
public class TicTacToe {
private static Scanner keyboard = new Scanner(System.in);
private static char[][] board = new char[3][3];
public static int row, col;
[Code] ....
I am trying to make a program that compares the 3 different search algorithms(sequential/binary/hashing). I have already made the sequential search algorithm, binary and hashing part of the code.My program OPENS a data file, and then OPENS a key data file. and then searches through them using both. How to go about the binary and hashing search algorithm (in the driver program).
*I have included a zip file with:
-base program
-driver program
-data file
-key data file