Forum - Java
- gioco snake: il serpente non muore!!
Pagine: [ 1 2 ]
|
beppe_ita (Normal User)
Newbie
Messaggi: 6
Iscritto: 22/10/2012
Salve a tutti sono nuovo!! siccome necessito del gioco Snake per un mio progetto ho cercato in internet del codice già scritto e alla fine ne ho trovato uno che più o meno capisco completamente!! l'unico problema è che non si riesce a far terminare la partita perchè il serpente quando sbatte contro la propria coda, invece di morire, la attraversa!! quindi in pratica il gioco è infinito! ho provato a sistemarlo da solo ma davvero non capisco cosa ci sia di sbagliato e per questo spero che qualcuno di voi mi possa aiutare! questo è il codice:
Codice sorgente - presumibilmente Java
import java.awt.* ;
import java.awt.event.* ;
import javax.swing.* ;
import java.util.* ;
/**
*
*/
private static final long serialVersionUID = 1L;
int x = 500, y = 250, gu = 2, directionx = 1, directiony = 0, speed = 50, difference = 0, oldx, oldy, score = 0 ;
int [ ] lbx = new int [ 300] ;
int [ ] lby = new int [ 300] ;
boolean food = false , runl = false , runr = true , runu = true , rund = true , bonusflag = true ;
public void initializeValues( ) {
gu = 3 ;
lbx[ 0] = 100 ;
lby[ 0] = 150 ;
directionx = 10 ;
directiony = 0 ;
difference = 0 ;
score = 0 ;
food = false ;
runl = false ;
runr = true ;
runu = true ;
rund = true ;
bonusflag = true ;
}
Snake( ) {
super ( "Snake" ) ;
setSize( 500, 330) ;
//Create Menue bar with functions
creatbar( ) ;
//initialize all variables
initializeValues( ) ;
// Start of UI design
// t will view the score
t.setEnabled ( false ) ;
t.
setBackground ( Color .
BLACK ) ; // snake have to eat bonousfood to growup
bonusfood.setEnabled ( false ) ;
// will make first snake
createFirstSnake( ) ;
p1.setLayout ( null ) ;
p1.setBounds ( 0, 0, x, y) ;
p1.
setBackground ( Color .
blue ) ; p2.setBounds ( 0, y, x, 30) ;
p2.
setBackground ( Color .
RED ) ;
p2.add ( t) ; // will contain score board
// end of UI design
getContentPane( ) .setLayout ( null ) ;
getContentPane( ) .add ( p1) ;
getContentPane( ) .add ( p2) ;
setVisible( true ) ;
setDefaultCloseOperation( EXIT_ON_CLOSE) ;
addKeyListener( this ) ;
// start thread
myt.start ( ) ; // go to run() method
}
public void createFirstSnake( ) {
// Initially the snake has small length 3
for ( int i = 0 ; i < 3 ; i++ ) {
lb[ i] .setEnabled ( false ) ;
p1.add ( lb[ i] ) ;
lb[ i] .setBounds ( lbx[ i] , lby[ i] , 10, 10) ;
lbx[ i + 1] = lbx[ i] - 10 ;
lby[ i + 1] = lby[ i] ;
}
}
public void creatbar( ) {
game
= new JMenu ( "Game" ) ;
newgame.addActionListener (
reset( ) ;
}
} ) ;
}
} ) ;
game.add ( newgame) ;
game.addSeparator ( ) ;
game.add ( exit) ;
mymbar.add ( game) ;
level
= new JMenu ( "Level" ) ;
mymbar.add ( level) ;
help
= new JMenu ( "Help" ) ;
JOptionPane .
showMessageDialog ( p2,
"Chiara Moccia è il mio amore" ) ; }
} ) ;
help.add ( creator) ;
help.add ( instruction) ;
mymbar.add ( help) ;
setJMenuBar( mymbar) ;
}
@SuppressWarnings( "deprecation" )
void reset( ) {
initializeValues( ) ;
p1.removeAll ( ) ;
myt.stop ( ) ;
createFirstSnake( ) ;
t.setText ( "Score==>" + score) ;
myt.start ( ) ;
}
void growup( ) {
lb[ gu] .setEnabled ( false ) ;
p1.add ( lb[ gu] ) ;
int a = 10 + ( 10 * r.nextInt ( 48) ) ;
int b = 10 + ( 10 * r.nextInt ( 23) ) ;
lbx[ gu] = a;
lby[ gu] = b;
lb[ gu] .setBounds ( a, b, 10, 10) ;
gu++;
}
// this method contains the logic to move the snake. player will define the derection
// this method just forward the snake to the right derection which deriction is pressed
// by the player.
void moveForward( ) {
for ( int i = 0 ; i < gu; i++ ) {
lbp[ i] = lb[ i] .getLocation ( ) ;
}
lbx[ 0] += directionx;
lby[ 0] += directiony;
lb[ 0] .setBounds ( lbx[ 0] , lby[ 0] , 10, 10) ;
for ( int i = 1 ; i < gu; i++ ) {
lb[ i] .setLocation ( lbp[ i - 1] ) ;
}
if ( lbx[ 0] == x) {
lbx[ 0] = 10 ;
} else if ( lbx[ 0] == 0) {
lbx[ 0] = x - 10 ;
} else if ( lby[ 0] == y) {
lby[ 0] = 10 ;
} else if ( lby[ 0] == 0) {
lby[ 0] = y - 10 ;
}
if ( lbx[ 0] == lbx[ gu - 1] && lby[ 0] == lby[ gu - 1] ) {
food = false ;
score += 5 ;
t.setText ( "Score==>" + score) ;
if ( score % 50 == 0 && bonusflag == true ) {
p1.add ( bonusfood) ;
bonusfood.setBounds ( ( 10 * r.nextInt ( 50) ) , ( 10 * r.nextInt ( 25) ) , 15, 15) ;
bfp = bonusfood.getLocation ( ) ;
bonusflag = false ;
}
}
if ( bonusflag == false ) {
if ( bfp.x <= lbx[ 0] && bfp.y <= lby[ 0] && bfp.x + 10 >= lbx[ 0] && bfp.y + 10 >= lby[ 0] ) {
p1.remove ( bonusfood) ;
score += 100 ;
t.setText ( "Score ==>" + score) ;
bonusflag = true ;
}
}
if ( food == false ) {
growup( ) ;
food = true ;
} else {
lb[ gu - 1] .setBounds ( lbx[ gu - 1] , lby[ gu - 1] , 10, 10) ;
}
for ( int i = 1 ; i < gu; i++ ) {
if ( lbp[ 0 ] == lbp[ i] ) {
t.setText ( "GAME OVER " + score) ;
try {
myt.join ( ) ;
}
break ;
}
}
p1.repaint ( ) ;
setVisible( true ) ;
}
// snake move to left when player pressed left arrow
if ( runl == true && e.getKeyCode ( ) == 37) {
directionx = - 10 ; // means snake move right to left by 10pixels
directiony = 0 ;
runr = false ; // run right(runr) means snake cant move from left to right
runu = true ; // run up (runu) means snake can move from down to up
rund = true ; // run down (run down) means snake can move from up to down
}
// snake move to up when player pressed up arrow
if ( runu == true && e.getKeyCode ( ) == 38) {
directionx = 0 ;
directiony = - 10 ; // means snake move from down to up by 10 pixel
rund = false ; // run down (run down) means snake can move from up to down
runr = true ; // run right(runr) means snake can move from left to right
runl = true ; // run left (runl) means snake can move from right to left
}
// snake move to right when player pressed right arrow
if ( runr == true && e.getKeyCode ( ) == 39) {
directionx = + 10 ; // means snake move from left to right by 10 pixel
directiony = 0 ;
runl = false ;
runu = true ;
rund = true ;
}
// snake move to down when player pressed down arrow
if ( rund == true && e.getKeyCode ( ) == 40) {
directionx = 0 ;
directiony = + 10 ; // means snake move from left to right by 10 pixel
runu = false ;
runr = true ;
runl = true ;
}
}
}
}
public void run( ) {
for ( ;; ) {
// Move the snake move forword. In the start of the game snake move left to right,
// if player press up, down, right or left arrow snake change its direction according to
// pressed arrow
moveForward( ) ;
try {
}
}
}
}
invece questo è il main:
Codice sorgente - presumibilmente Java
public class Main {
public static void main
( String [ ] args
) { new Snake( ) ;
} }
LittleHacker (Member )
Guru
Messaggi: 1033
Iscritto: 28/04/2009
L'errore mi sembra che stia qui:
Codice sorgente - presumibilmente Java
for ( int i = 1 ; i < gu; i++ ) {
if ( lbp[ 0 ] == lbp[ i] ) {
t.setText ( "GAME OVER " + score) ;
try {
myt.join ( ) ;
}
break ;
}
}
Ma quando la attraversa ti dice game over oppure nulla, continua?
sembra tanto che gu, è la variabile che tiene conto del numero di code(se non sbaglio)!
Faccio delle prove e ti faccio sapere!
beppe_ita (Normal User)
Newbie
Messaggi: 6
Iscritto: 22/10/2012
si l'errore è in quel pezzo di codice in particolare sembra che
Codice sorgente - presumibilmente Java
non si verifichi mai!! lbp dovrebbe essere un Pointer in cui sono salvate le posizioni di ogni componente del serpente! ovvero lbp[0] è la testa e verifica se concide con un qualsiasi pezzo del corpo! tuttavia quando si scontra non segnala Game Over e il serpente si attraversa!!
LittleHacker (Member )
Guru
Messaggi: 1033
Iscritto: 28/04/2009
Postato originariamente da beppe_ita :
si l'errore è in quel pezzo di codice in particolare sembra che
Codice sorgente - presumibilmente Java
non si verifichi mai!! lbp dovrebbe essere un Pointer in cui sono salvate le posizioni di ogni componente del serpente! ovvero lbp[0] è la testa e verifica se concide con un qualsiasi pezzo del corpo! tuttavia quando si scontra non segnala Game Over e il serpente si attraversa!!
Adesso sto scaricando Eclipse(perchè non l'ho scaricato prima? Boh
) Appena ho qualche risultato ti faccio sapere!
LittleHacker (Member )
Guru
Messaggi: 1033
Iscritto: 28/04/2009
Ma il sito da dove lo hai scaricato, ti ha assicurato che funzionasse perchè qui sembra che ci sia un problema più grande del semplice if, sembra che non riesca a prendere i point giusti!
beppe_ita (Normal User)
Newbie
Messaggi: 6
Iscritto: 22/10/2012
Il programmatore assicurava che funziona ma nei commenti ammette che c'è questo bug!
Se provi a ad eseguirlo vedi che funziona tutto, tranne questa cosa quindi magari non è un errore globale! Comunque grazie per la tua disponibilità
LittleHacker (Member )
Guru
Messaggi: 1033
Iscritto: 28/04/2009
Trovato un'altro funzionante, un po' diverso:
Snake.java:
Codice sorgente - presumibilmente Java
import java.awt.* ;
import java.awt.event.* ;
import java.util.ArrayList ;
import java.util.Random ;
import javax.swing.JOptionPane ;
import javax.swing.UIManager ;
public class Snake
extends Core
implements KeyListener { // main method
public static void main
( String [ ] args
) { try {
Object [ ] opts
= { "Easy" ,
"Normal" ,
"Hard" ,
"Insane" ,
"Exit" } ; int dif
= JOptionPane .
showOptionDialog ( null ,
"Select a difficulty" ,
null , opts, opts) ;
if ( dif == 0) {
sleep = 110 ;
grid = true ;
new Snake( ) .run ( ) ;
} else if ( dif == 1) {
sleep = 99 ;
grid = true ;
new Snake( ) .run ( ) ;
} else if ( dif == 2) {
sleep = 69 ;
grid = false ;
new Snake( ) .run ( ) ;
} else if ( dif == 3) {
sleep = 29 ;
grid = false ;
new Snake( ) .run ( ) ;
} else {
}
if ( replay) {
main( null ) ;
}
}
ArrayList< Rectangle> snake;
boolean up, down, left, right, eaten, dirChanged;
static boolean grid;
int score;
// init method
public void init( ) {
super .init ( ) ;
w.addKeyListener ( this ) ;
removeCursor( ) ;
snake = new ArrayList< Rectangle> ( ) ;
eaten = true ;
score = 0 ;
}
// updates the game
public void update( ) {
// food
food( ) ;
dirChanged = false ;
// Collision between snake and itself
for ( int i = 0 ; i < snake.size ( ) ; i++ ) {
for ( int j = i + 1 ; j < snake.size ( ) ; j++ ) {
if ( snake.get ( i) .getLocation ( ) .x == snake.get ( j) .getLocation ( ) .x
&& snake.get ( i) .getLocation ( ) .y == snake.get ( j)
.getLocation ( ) .y ) {
stop( ) ;
JOptionPane .
showMessageDialog ( null ,
"Game Over" + "\n You scored " + score,
w.setVisible ( false ) ;
replay = true ;
}
}
}
// movement for snake
for ( int i = snake.size ( ) - 1 ; i >= 0 ; i-- ) {
if ( up) {
try {
snake.get ( i) .setLocation ( snake.get ( i - 1) .x ,
snake.get ( i - 1) .y ) ;
if ( snake.get ( i) .getLocation ( ) .y > 0) {
snake.get ( i) .setLocation ( snake.get ( i) .x ,
snake.get ( i) .y - 20) ;
} else {
snake.get ( i) .setLocation ( snake.get ( i) .x ,
w.getHeight ( ) - 20) ;
}
}
} else if ( down) {
try {
snake.get ( i) .setLocation ( snake.get ( i - 1) .x ,
snake.get ( i - 1) .y ) ;
if ( snake.get ( i) .getLocation ( ) .y < w.getHeight ( ) - 20) {
snake.get ( i) .setLocation ( snake.get ( i) .x ,
snake.get ( i) .y + 20) ;
} else {
snake.get ( i) .setLocation ( snake.get ( i) .x , 0) ;
}
}
} else if ( left) {
try {
snake.get ( i) .setLocation ( snake.get ( i - 1) .x ,
snake.get ( i - 1) .y ) ;
if ( snake.get ( i) .getLocation ( ) .x > 0) {
snake.get ( i) .setLocation ( snake.get ( i) .x - 20,
snake.get ( i) .y ) ;
} else {
snake.get ( i) .setLocation ( w.getWidth ( ) - 20,
snake.get ( i) .y ) ;
}
}
} else if ( right) {
try {
snake.get ( i) .setLocation ( snake.get ( i - 1) .x ,
snake.get ( i - 1) .y ) ;
if ( snake.get ( i) .getLocation ( ) .x < w.getWidth ( ) - 20) {
snake.get ( i) .setLocation ( snake.get ( i) .x + 20,
snake.get ( i) .y ) ;
} else {
snake.get ( i) .setLocation ( 0, snake.get ( i) .y ) ;
}
}
}
}
}
// food method
public void food( ) {
if ( eaten && up || eaten && down || eaten && left || eaten && right) {
int x
= new Random ( ) .
nextInt ( 30
) * 20 ; int y
= new Random ( ) .
nextInt ( 25
) * 20 ; boolean spawn = true ;
for ( int i = 0 ; i < snake.size ( ) ; i++ ) {
if ( snake.get ( i) .x == x && snake.get ( i) .y == y) {
spawn = false ;
}
}
if ( spawn) {
eaten = false ;
}
} else if ( food != null && ! eaten) {
if ( snake.get ( 0) .x == food.x && snake.get ( 0) .y == food.y ) {
score++;
eaten = true ;
}
}
}
// draw method
g.fillRect ( 0, 0, w.getWidth ( ) , w.getHeight ( ) ) ;
if ( grid) {
for ( int x = 0 ; x < w.getWidth ( ) / 20 ; x++ ) {
for ( int y = 0 ; y < w.getHeight ( ) / 20 ; y++ ) {
g.drawRect ( x * 20, y * 20, 20, 20) ;
}
}
}
if ( ! eaten) {
g.fill ( food) ;
}
for ( int i = snake.size ( ) - 1 ; i >= 0 ; i-- ) {
g.fill ( snake.get ( i) ) ;
}
g.
setFont ( new Font ( "Dialog" ,
Font .
PLAIN , 16
) ) ; g.drawString ( "Score: " + score, 2, 17) ;
g.drawString ( "Escape to quit" , 482, 17) ;
if ( ! up && ! down && ! left && ! right) {
g.drawString ( "Up, down, left or right to start game" , 162, 17) ;
}
}
// Key listeners
if ( e.
getKeyCode ( ) == KeyEvent .
VK_ESCAPE ) { stop( ) ;
} else if ( e.
getKeyCode ( ) == KeyEvent .
VK_UP && ! down
&& ! dirChanged
) { dirChanged = true ;
up = true ;
down = false ;
left = false ;
right = false ;
} else if ( e.
getKeyCode ( ) == KeyEvent .
VK_DOWN && ! up
&& ! dirChanged
) { dirChanged = true ;
up = false ;
down = true ;
left = false ;
right = false ;
} else if ( e.
getKeyCode ( ) == KeyEvent .
VK_LEFT && ! right
&& ! dirChanged
) { dirChanged = true ;
up = false ;
down = false ;
left = true ;
right = false ;
} else if ( e.
getKeyCode ( ) == KeyEvent .
VK_RIGHT && ! left
&& ! dirChanged
) { dirChanged = true ;
up = false ;
down = false ;
left = false ;
right = true ;
}
}
}
}
}
Core.java:
Codice sorgente - presumibilmente Java
import java.awt.* ;
import java.awt.image.BufferStrategy ;
import java.awt.image.BufferedImage ;
import javax.swing.* ;
public abstract class Core {
boolean running;
static boolean replay;
//stop method
public void stop( ) {
running = false ;
}
//call init and gameloop
public void run( ) {
try {
init( ) ;
gameLoop( ) ;
} finally {
if ( ! replay) {
}
}
}
//set to full screen
public void init( ) {
w.setUndecorated ( true ) ;
w.setIgnoreRepaint ( true ) ;
w.setResizable ( false ) ;
w.setSize ( 600, 500) ;
w.setLocationRelativeTo ( null ) ;
w.
setFont ( new Font ( "Arial" ,
Font .
PLAIN , 24
) ) ; w.
setBackground ( Color .
BLACK ) ; w.
setForeground ( Color .
WHITE ) ; w.setVisible ( true ) ;
w.createBufferStrategy ( 2) ;
replay = false ;
running = true ;
}
static long sleep;
//main game loop
public void gameLoop( ) {
while ( running) {
draw( g) ;
g.dispose ( ) ;
this .update ( ) ;
if ( w != null ) {
BufferStrategy s = w.getBufferStrategy ( ) ;
if ( ! s.contentsLost ( ) ) {
s.show ( ) ;
}
}
try {
}
}
//update game
public abstract void update( ) ;
//draws to the screen
//sets blank cursor
public void removeCursor( ) {
Cursor blankCursor
= Toolkit .
getDefaultToolkit ( ) .
createCustomCursor ( cursorImg,
new Point ( 0 ,
0 ) ,
"blank cursor" ) ; w.setCursor ( blankCursor) ;
}
}
L'altro non so proprio come sistemarlo
Edit:
Ops
perdonami, ero di fretta e non ho controllato il codice postato, però ero sicuro di aver copiato il codice core! Scusa
Ultima modifica effettuata da LittleHacker il 23/10/2012 alle 23:25
beppe_ita (Normal User)
Newbie
Messaggi: 6
Iscritto: 22/10/2012
Grazie milleeeee!!! c'è sono un piccolo problemino col tuo codice
e cioè che hai postato 2 volte il codice del Main e manca il Core
gigisoft (Member )
Guru
Messaggi: 696
Iscritto: 11/10/2008
gioco snake: il serpente non muore!!