Algorithm analysis of greed to eat snake (4)

zhaozj2021-02-17  69

Algorithm analysis of greedy snake

(4)

James @ www.chenshen.com

Wormpit class

Worm and Wormfood include Worm and Wormfood. The greedy snake will move in the picture to find food. If it eats food it will be a long. If it encounters a border or eats yourself.

Here are several important functions:

l

Private

Void PaintPITENTENTS (Graphics G)

Redraw all the elements on the screen

/ / Update the state of greed to eat snake

MyWorm.Update (g);

// The position of the head and the position of the food will eat food

IF (myfood.isat (myworm.getx (), myformation.gety ())) {

myworm.eat ();

Score = level;

Foodeaten ;

IF (Foodeaten> (Level << 1)) {

/ * Increase the game difficulty * /

ForceRedraw = true;

Foodeaten = 0;

Level ;

IF (TonePlayer! = NULL) {

Try {

TonePlayer.SetMediatime (0);

TonePlayer.Start ();

} catch (MediaException me) {}}

} else {

IF (audioplayer! = null) {

Try {

Manager.Playtone (69, 50, 100); // Play Audio

} catch (MediaException me) {}}}

g.setColor (WormPit.Rase_COLOUR);

// Fill the rectangle (the width of three words)

G.FillRect ((width - (score_char_width * 3)) - start_pos,

HEIGHT-START_POS,

(Score_char_width * 3),

Score_char_height;

g.setcolor (WormPit.Draw_colour);

/ / Display new score

g.drawstring ("" score,

Width - (score_char_width * 3) - start_pos,

Height - start_pos, graphics.top | graphics.Left);

/ / Re-generate food

myfood.Regenerate ();

INT x = myfood.getx ();

Int y = myfood.gety ();

While (MyWorm.Contains (x, y)) {

// If the food and the body of the snake are regenerated

myfood.Regenerate ();

X = myfood.getx (); y = myfood.gety ();}}

// Draw food

myfood.paint (g);

} catch (workxception se) {gameover = true;

l public void run ()

Main cycle:

While (! gamedestroyed) {// The game is not terminated, it is looped

Try {

Synchronized (MyWorm) {// Multi-threaded synchronization

// If the game is over

IF (GameOver) {

IF (WormScore.GethighScore (Level)

// Save the highest points

Wormscore.sethiGHScore (Level, Score, "ME");

IF ((Audioplayer! = null) && (Audioplayer.getState () == Player.Started) {

Try {

AudioPlayer.stop ();

Manager.Playtone (60, 400, 100);

} catch (exception ex) {}}}

// Rear painting

Repaint ();

Wait for the user to start again at the end of the game

Myworm.wait ();

} else if (gamepaused) {

// Rear painting

Repaint ();

// Wait for the user to start again when the game is suspended

Myworm.wait ();

} else {

// Game continues

myworm.moveonupdate ();

Repaint ();

// The waiting time here determines the game difficulty !!!

MyWorm.wait (Default_Wait- (Level * 40));

}

}

} catch (java.lang.interruptedException IE {

}

}

About the Author:

Shen Yachang, Senior Programmer, SCJP

Www.chenshen.com

Jinashen@benq.com

August 10, 2003

转载请注明原文地址:https://www.9cbs.com/read-29691.html

New Post(0)