public void paint(Graphics g) int cell = 8; int offsetX = (128 - W*cell)/2; int offsetY = (160 - H*cell)/2; // background g.setColor(0x000000); g.fillRect(0,0,128,160); // draw food g.setColor(0xFF0000); g.fillRect(offsetX+foodX*cell, offsetY+foodY*cell, cell-1, cell-1); // draw snake g.setColor(0x00FF00); for(int i=0; i<length; i++) g.fillRect(offsetX+snakeX[i]*cell, offsetY+snakeY[i]*cell, cell-1, cell-1); // score g.setColor(0xFFFFFF); g.drawString("Score: "+score, 5, 5, Graphics.TOP
public SnakeCanvas(MIDlet m) super(true); midlet = m; setFullScreenMode(true); initGame();
public void run() { while(running) { long start = System.currentTimeMillis(); if(gameState == 0) updateGame(); repaint(); long delay = 150 - (System.currentTimeMillis()-start); if(delay < 5) delay = 5; try Thread.sleep(delay); catch(Exception e) {} } } 128x160 snake xenzia java game
private void spawnFood() // simple random do foodX = (int)(Math.random() * W); foodY = (int)(Math.random() * H); while(collidesWithSnake(foodX, foodY));
private boolean collidesWithSnake(int x, int y) for(int i=0; i<length; i++) if(snakeX[i]==x && snakeY[i]==y) return true; return false; public void paint(Graphics g) int cell = 8;
g.setColor(0x00FF00); // green body for(int i=0; i<length; i++) g.fillRect(offsetX + x[i]*CELL_SIZE, offsetY + y[i]*CELL_SIZE, CELL_SIZE-1, CELL_SIZE-1);
} import javax.microedition.lcdui.*; import javax.microedition.lcdui.game.GameCanvas; public class SnakeCanvas extends GameCanvas implements Runnable { private MIDlet midlet; private Thread thread; private boolean running; private int gameState; // 0=run,1=pause,2=gameover int offsetX = (128 - W*cell)/2
int action = getGameAction(keyCode); switch(action) case UP: if(direction != DOWN) nextDir = UP; break; case DOWN: if(direction != UP) nextDir = DOWN; break; case LEFT: if(direction != RIGHT) nextDir = LEFT; break; case RIGHT: if(direction != LEFT) nextDir = RIGHT; break; case FIRE: if(gameState == RUNNING) gameState = PAUSED; else if(gameState == PAUSED) gameState = RUNNING; break;
private void updateGame() newX>=W