📄 mazefog2.java
字号:
/* Java 1.1 AWT Applet - Maze Fog Game Written by: Keith Fenske, http://www.psc-consulting.ca/fenske/ Wednesday, 28 January 2004 Java class name: MazeFog2 Copyright (c) 2004 by Keith Fenske. Released under GNU Public License. This is a graphical Java 1.1 AWT (GUI) applet to play a maze game. The computer creates a random maze. The exit is marked by blue and white boxes. Your position is marked by a blue circle. Use the arrow keys or the mouse to move towards the exit. You may have to reposition your mouse if you bump into walls! You may run this program as a stand-alone application, or as an applet on the following web page: Maze Fog Game - by: Keith Fenske http://www.psc-consulting.ca/fenske/mazfog2a.htm There are no monsters or obstacles in the maze. Your view is limited by a "fog" that shows only nearby positions and positions that you have already visited. If you can't solve the maze, then click the "Show Me" button to see the path to the exit. GNU General Public License (GPL) -------------------------------- MazeFog2 is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY, without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see the http://www.gnu.org/licenses/ web page. ----------------------------------------------------------------------------- Programming Notes: Since every line is shared by two squares (except for lines on the outside edges of the board), assign all horizontal lines to the top edge of a square and all vertical lines to the left edge of a square. This makes the program data more consistent. There is one more column of vertical lines than there are columns of board squares, so add an invisible column of board squares on the right side to hold the extra "left" lines. Similarly, add an invisible row of board squares on the bottom to hold the extra "top" lines. ----------------------------------------------------------------------------- Java Applet Notes: The recommended way of writing applets is to use Java Swing, according to Sun Microsystems, the creators and sponsors of Java. Unfortunately, most web browsers don't support Swing unless you download a recent copy of the Java run-time environment from Sun. This leaves a Java programmer with two choices: (1) Write applets using only old features found in the AWT interface. The advantage, if you can see it this way, is that the programmer gets a detailed opportunity to interact with the graphical interface. (Joke.) (2) Force users to visit http://java.sun.com/downloads/ to download and install a newer version of Java. However, forcing anyone to download something before they can visit your web page is a poor idea. A worse idea is new browsers that don't have any Java support at all, unless the user first downloads Sun Java. Microsoft stopped distributing their version of Java in 2003 starting with Windows XP SP1a (February), then Windows 2000 SP4 (June). Until Microsoft and Sun resolve their various lawsuits -- or until Microsoft agrees to distribute an unaltered version of Sun Java -- there will be an increasing number of internet users that have *no* version of Java installed on their machines! The design considerations for this applet are as follows: (1) The applet should run on older browsers as-is, without needing any additional downloads and/or features. The minimum target is JDK1.1 which is Microsoft Internet Explorer 5.0 (Windows 98) and Netscape 4.7/4.8 (JDK 1.1.5 from 1997). (2) Unlike the previous Life3 and TicTacToe4 applets, this applet uses more than one class. A second class, a subclass of Canvas, is used to better draw and accept mouse input on the game board. To run this applet on a web page, MazeFog2 should be loaded from a JAR (Java archive) file. (3) The default background in the Sun Java applet viewer is white, but most web browsers use light grey. To get the background color that you want, you must setBackground() on components or fillRect() with the color of your choice. (4) A small main() method is included with a WindowAdapter subclass, so that this program can be run as an application. The default window size and position won't please everyone. (5) We play a sample sound when the user reaches the exit. Most newer web browsers are smart enough to load this sound file from the applet's JAR file, but not Netscape 4.7/4.8 (JDK1.1) which expects to find the sound as a separate file on the web server. That means putting the sound file in two places: once inside the JAR (for faster loading on most browsers) and once by itself on the web site. Note also that sound clips are loaded differently in applets and applications.*/import java.applet.*; // older Java applet supportimport java.awt.*; // older Java GUI supportimport java.awt.event.*; // older Java GUI event supportpublic class MazeFog2 extends Applet implements ActionListener, KeyListener{ /* constants */ static final int canvasBorder = 10; // empty pixels around game board static final String noMessage = " "; // message text when nothing to say static final int[] sizeList = {10, 13, 16, 20, 25, 32, 40, 50, 63, 80}; // defined sizes in pixels of board squares static final String winSoundString = "MAZFOG2E.AU"; // Play this sound clip when the user wins: // a renamed "danger.au" from the Java SDK, // which sounds like cow bells. Must match // the exact file name (lower- and uppercase) // in some applet viewers. static final Color BACKGROUND = new Color(255, 204, 204); // light pink static final Color ColorEXIT1 = new Color(204, 255, 255); // cyan static final Color ColorEXIT2 = new Color(102, 51, 204); // off blue static final Color ColorLINE = new Color(153, 102, 102); // darker pink static final Color ColorUSER = new Color(102, 102, 255); // light blue static final int DelayDRAW = 5; // milliseconds while drawing board static final int DelayFLASH = 100; // milliseconds while flashing display static final int GameACTIVE = 101; // waiting for user to move static final int GameFINISH = 102; // game is finished (no moves allowed) static final int LineEMPTY = 201; // no horizontal or vertical line static final int LineHIDDEN = 202; // line exists, but is currently hidden static final int LineVISIBLE = 203; // line is visible to the user /* class variables */ static AudioClip winSound = null; // non-null when sound clip has been loaded /* instance variables, including shared GUI components */ Button biggerButton; // "Bigger" button int boardBorderSize; // size in pixels of border between board // ... lines and board symbols Canvas boardCanvas; // where we draw the game board int[][] boardDistance; // distance from exit (in squares), or -1 if // ... not on a path int boardGridSize; // size in pixels of each board square, // ... including one set of lines int[][] boardLeft; // left (vertical) lines int boardLineWidth; // width in pixels of board lines int boardSymbolSize; // size in pixels of board symbols int[][] boardTop; // top (horizontal) lines int exitCol; // column number of exit (goal) square int exitRow; // row number of exit (goal) square int gameState; // state variable for current game Label messageText; // information or status message for user Button newgameButton; // "New Game" button int numCols; // number of columns in current game board int numRows; // number of rows in current game board int sizeIndex; // index of current entry in <sizeList> Button showmeButton; // "Show Me" button Button smallerButton; // "Smaller" button int startCol; // user's starting column number int startDistance; // user's starting distance from the exit int startRow; // user's starting row number int userCol; // current column number for user's position int userColOffset; // offset from <userCol> in pixels int userRow; // current row number for user's position int userRowOffset; // offset from <userRow> in pixels/* init() method Initialize this applet (equivalent to the main() method in an application). Please note the following about writing applets: (1) An Applet is an AWT Component just like a Button, Frame, or Panel. It has a width, a height, and you can draw on it (given a proper graphical context, as in the paint() method). (2) Applets shouldn't attempt to exit, such as by calling the System.exit() method, because this isn't allowed on a web page.*/ public void init() { /* Intialize our own data before creating the GUI interface. Some of these values are necessary; others are a precaution in case the GUI gets ahead of us before we build a proper maze. The initial value of all arrays is assumed to be null. */ exitCol = exitRow = 0; // just to be safe, set some initial value gameState = GameFINISH; // no moves allowed until we are ready numCols = numRows = 1; startCol = startDistance = startRow = 0; userCol = userColOffset = userRow = userRowOffset = 0; sizeIndex = 5; // initial size is near middle of list setBoardSizes(); // set sizes of board elements /* Load the winning sound now if an application wrapper hasn't already done so. getCodeBase() will throw a NullPointerException if we are not running as an applet. */ if (winSound == null) // if application hasn't already loaded sound try { winSound = getAudioClip(getCodeBase(), winSoundString); } catch (NullPointerException except) { winSound = null; } /* Create the GUI interface as a series of little panels inside bigger panels. The intermediate panel names (panel1, panel2, etc) are of no importance and hence are only numbered. */ /* Make a horizontal panel to hold four equally-spaced buttons. We put this first panel inside a second FlowLayout panel to prevent the buttons from stretching horizontally as the window size gets bigger. */ Panel panel1 = new Panel(new GridLayout(1, 4, 25, 0)); biggerButton = new Button("Bigger (B)"); biggerButton.addActionListener((ActionListener) this); panel1.add(biggerButton); smallerButton = new Button("Smaller (S)"); smallerButton.addActionListener((ActionListener) this); panel1.add(smallerButton); showmeButton = new Button("Show Me (M)"); showmeButton.addActionListener((ActionListener) this); panel1.add(showmeButton); newgameButton = new Button("New Game (N)"); newgameButton.addActionListener((ActionListener) this); panel1.add(newgameButton); Panel panel2 = new Panel(new FlowLayout(FlowLayout.CENTER, 0, 5)); panel2.setBackground(BACKGROUND); // for Netscape 4.7/4.8 (JDK1.1) panel2.add(panel1); /* Put a message field under the buttons. */ Panel panel3 = new Panel(new GridLayout(2, 1, 0, 0)); panel3.add(panel2); messageText = new Label("Maze Fog (Java applet). Copyright (c) 2004 by Keith Fenske. GNU Public License.", Label.CENTER); messageText.setFont(new Font("Default", Font.PLAIN, 14)); messageText.setBackground(BACKGROUND); panel3.add(messageText); /* Put the buttons and message field on top of a canvas for the game board, giving the game board the remaining window space. We set the applet to have a BorderLayout and put <boardCanvas> in the center, which allows the canvas to expand and contract with the applet's window size. Note that the MazeFog2Board class assumes that a MazeFog2 object is the parent container of <boardCanvas>. */ boardCanvas = new MazeFog2Board(); boardCanvas.addKeyListener((KeyListener) this); // listen to arrow keys boardCanvas.addMouseMotionListener((MouseMotionListener) boardCanvas); this.setLayout(new BorderLayout(0, 0)); this.add(panel3, BorderLayout.NORTH); this.add(boardCanvas, BorderLayout.CENTER); this.setBackground(BACKGROUND); this.validate(); // do the window layout /* Create the initial maze. Must come after GUI is ready, because we use the size of <boardCanvas>. */ makeBoard(false); // make maze, don't display as we create /* Now let the GUI interface run the game. A repaint() will occur after init() returns, which will display the game board with the appropriate parts hidden or visible. */ boardCanvas.requestFocus(); // set focus so we can listen for arrow keys gameState = GameACTIVE; // let the game begin } // end of init() method/* main() method Applets only need an init() method to start execution. This main() method is a wrapper that allows the same applet code to run as an application.*/ public static void main(String[] args) { MazeFog2 appletPanel; // the target applet's window Frame mainFrame; // this application's window /* Loading sound clips in an application requires a call to newAudioClip(), which is JDK1.2. Load the winning sound now so that the applet won't fail when calling getCodeBase(). As long as the URL syntax is good, <winSound> will have a non-null value ... even if the file doesn't exist or can't be loaded. */ try { winSound = newAudioClip(new java.net.URL("file:" + winSoundString)); } catch (java.net.MalformedURLException except) { winSound = null; } /* Create the frame that will hold the applet. */
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -