nodez.java

来自「java learn PPT java learn PPT java learn」· Java 代码 · 共 367 行

JAVA
367
字号
     import java.applet.*;
     import java.awt.*;
     import java.awt.event.*;
     import java.awt.image.*;
     import java.awt.geom.*;
     import java.util.*;

     import magic.actor2d.*;
     import magic.awtex.*;
     import magic.debug.*;
     import magic.gamelet.*;
     import magic.graphics.*;
     import magic.scene.*;
     import magic.net.*;

     public class Nodez extends Gamelet
     {
          // 显示帧速的标签
          private Label2D framerateLabel;

          // 允许声音效果切换
          private RadioButton2D audioButton;

          // 正确放置的节点数目
          private int numCorrect;

          // 画面中所包含的节点数
          private int totalNodes;

          // 显示numCorrect和totalNodes之间的比例
          private Label2D status;

          // 当前玩的级别
          private int currentLevel;

          // 显示当前级别的标签 
          private Label2D levelLabel;

          // 有必要标记最后一分钟开始
          private boolean firstTime = true;

          // 播放声音的静态标志
          public static final int LEVEL_LOADED    = 0;
          public static final int TOGGLE_FLAG_ON  = 1;
          public static final int NODE_SELECTED1  = TOGGLE_FLAG_ON;
          public static final int TOGGLE_FLAG_OFF = 2;
          public static final int NODE_SELECTED2  = TOGGLE_FLAG_OFF;
          public static final int GAME_OVER       = 3;

          // 要加载的音频文件名
          private final String[] AUDIO_FILES = 
                  { "shuffle.au", "pop.au", "bong.au", "salvation.au" };
         
          // 多播聊天连接
          private MulticastConnection chat;

          // 接收到的消息链表
          private java.util.List messageList;
          private final int MAX_MESSAGES = 5;

          // 显示当前要发出的消息的标签           
          private Label2D messageLabel;

          // 将要发出的消息
          private StringBuffer message;          
          private final int MESSAGE_LEN = 20;

          // 用来在发出的消息周围画一个矩形框
          private Rectangle2D messageOutline;

          public void init()
          {               
               // 初始化Gamelet
               super.init();

          }   // init

          // 只要得到有效的Graphics2D容器就执行初始化来绘制"加载"画面
          private void finalInit(Graphics2D g2d)
          {
               // 创建画面并加载第一级
               NodezScene ns = new NodezScene(getBounds(), this);
               currentLevel = 1;
               
               NodezLoader loader = new NodezLoader(getBounds(), ns.getNodeGroup(), g2d);
               loader.start();

               // 加载声音
               loadAudio();

               // 设置声音选择按钮
               ButtonImageGroup big = new ButtonImageGroup(2, "audio.gif");
               big.init(this);
               audioButton = new RadioButton2D(null, big, null, new Vector2D.Double(6, getSize().getHeight()-40));          
               addMouseListener(audioButton);
               audioButton.setSelected(false);

               // 设置帧速显示标签
               Font font;
               font = new Font("Helvetica", Font.PLAIN, 18);
               framerateLabel = new Label2D(font, "", Color.RED);
               framerateLabel.setPos(10, getSize().getHeight() - 50);

               // 帧速同步为60 fps
               setFramerate(1000/60);

               // 设置可见组件
               levelLabel = new Label2D(font, "Level X", Color.GREEN);
               levelLabel.setPos(400, 30);
               
               font = new Font("Helvetica", Font.PLAIN, 30);
               status = new Label2D(font, "XX/YY", Color.GREEN.brighter());
               status.setPos(400, 70);
               
               // 注册SPACE 键来key 切换帧速报告
               addKeyListener(new KeyAdapter() 
                    {
                         public void keyTyped(KeyEvent e)  
                         {
                              char ch = e.getKeyChar();

                              // 允许空格键
                              if(ch == KeyEvent.VK_BACK_SPACE)
                              {
                                   if(message.length() > 0)
                                   {
                                        message.deleteCharAt(message.length()-1);
                                   }
                                   return;
                              }

                              // 如果是回车键则发送当前的消息
                              else if(ch == KeyEvent.VK_ENTER)
                              {                               
                                   // 确保连上聊天服务器而且消息有效
                                   if(chat != null && ! "".equals(message.toString().trim()))
                                   {
                                        chat.send(message.toString().trim());
                                        message = new StringBuffer();
                                   }
                                   return;
                              }

                              // 否则, 在字符串末尾添加一个字符
                              else if((Character.isJavaIdentifierPart(ch) || Character.isWhitespace(ch)) && 
                                      message.length() < MESSAGE_LEN)
                              {
                                   message.append(ch);
                              }
                         }
                    } );

               // 注册鼠标点击/节点选取事件
               addMouseListener(new MouseAdapter()
                    {
                         public void mousePressed(MouseEvent e) 
                         {
                              ((NodezScene) scene).processMouseClick(e.getPoint(), e.getButton());
                         }
                    } );

               // 创建发送和接收消息的组件
               message      = new StringBuffer();
               messageLabel = new Label2D(new Font("Helvetica", Font.PLAIN, 14), "", Color.GREEN);
               messageLabel.setPos(100, getSize().getHeight() - 20);
               messageOutline = new Rectangle2D.Double(95, getSize().getHeight() - 35, 400, 25);
               messageList    = Collections.synchronizedList(new LinkedList());

               ns.loadLevel(currentLevel);

               totalNodes = ns.getNumNodes();
               numCorrect = 0;
               scene = ns;
               
               levelLabel.setText("Level " + currentLevel);   

               // 连接到多播组
               try
               {
                    chat = new MulticastConnection("225.0.16.21", MulticastConnection.DEFAULT_PORT);
                    addMessage("System Message: successfully connected to server!");
               }
               catch(Exception e)
               {
                    addMessage("System Error: Could not connect to Chat Server!");
                    System.out.println(e);
                    chat = null;
               }

               while(! loader.isFinished());
               loader.stop();

               // 这一关被加载, 播放提示声音!
               playSound(LEVEL_LOADED, false);
          }

          // 在所接收消息链表中添加一个消息
          private void addMessage(String msg)
          {
               // 如果链表已经满了则删除第一个消息
               if(messageList.size() >= MAX_MESSAGES)
               {
                    messageList.remove(0);
               }
     
               // 添加接收到的消息
               messageList.add(msg);
          }

          // 在窗体上绘制消息链表
          static final Font msgFont = new Font("Helvetica", Font.PLAIN, 14);
          public void drawMessages(Graphics2D g2d, int x, int y)
          {
               if(messageList.size() == 0) return;

               g2d.setFont(msgFont);
               g2d.setPaint(Color.GREEN);
               for(ListIterator i = messageList.listIterator(); i.hasNext(); )
               {     
                    g2d.drawString(i.next().toString(), x, y);
                    y += 16;
               }
          }

          public void start()
          {
               super.start();

               // 创建一个线程监听多播组并将接收到的消息发送到窗体上
               new Thread(new Runnable()
                    {
                         public synchronized void run()
                         {
                              MulticastConnection mc = null;
                              try
                              {
                                   mc = new MulticastConnection("224.0.0.21",
                                                  MulticastConnection.DEFAULT_PORT);
                              }
                              catch(Exception e)
                              {
                                   mc = null;
                              }
                              
                              while(mc != null)
                              {
                                   addMessage(mc.recv());
            
                                   try
                                   {
                                         Thread.sleep(10);
                                   }
                                   catch(InterruptedException e)
                                   {
                                   }
                              }
                         }

                    } ).start();
          }
         
          // 更新画面和其他的可见组件      
          public void update(Graphics g)
          {
               // 如果调试输出是激活的则忽略更新
               if(Debugger.isDisplayingOutput())
               {
                    paint(g);
                    return;
               }

               // 如果firstTime标志为true,则执行last-minute初始化               
               if(firstTime)
               {
                    finalInit((Graphics2D) g);
                    firstTime = false;
               }

               // 更新画面
               scene.update();

               // 如果题目已经解决,则等待画面已经设置再处理
               if(((NodezScene) scene).gameOver() && ((NodezScene) scene).isSettled())
               {
                    ++ currentLevel;
                    if(currentLevel > NodezLevel.MAX_LEVELS)
                    {
                         currentLevel = 1;
                    }
                    ((NodezScene) scene).loadLevel(currentLevel);

                    totalNodes = ((NodezScene) scene).getNumNodes();

                    levelLabel.setText("Level " + currentLevel);   
               }
 
               // 更新声音标记     
               audioEnabled = !audioButton.isSelected();

               numCorrect = ((NodezScene) scene).getNumCorrect();

               // 更新消息
               messageLabel.setText(message.toString() + "_");

               paint(g);
          }

          public void paint(Graphics g)
          {
               if(firstTime) return;
              
               // 如果调试输出窗口处于激活状态则挂起绘制过程
               if(Debugger.isDisplayingOutput())
               {
                    Graphics2D g2d = (Graphics2D) g;      
                    g2d.setPaint(Color.BLACK);
                    g2d.fill(getBounds());
                    g2d.setPaint(Color.RED);
                    g2d.drawString("Gamelet suspended; close the debug window to continue", 100, 100);
                    return;
               }

               super.paint(g);
          }

          protected void paintScene(Graphics2D g2d)
          {
               super.paintScene(g2d);

               // 显示帧速
               framerateLabel.setText("fps: " + (int) reportedFramerate);
               framerateLabel.paint(g2d);

               // 显示状态,正确的数目等等
               levelLabel.paint(g2d);

               status.setText(numCorrect + "/" + totalNodes);
               status.paint(g2d);

               // 绘制当前要发出的消息
               g2d.setPaint(Color.WHITE);
               g2d.setStroke(new BasicStroke(1.0f));
               g2d.draw(messageOutline);
               messageLabel.paint(g2d);

               // 绘制接收到的消息
               drawMessages(g2d, 10, 16);

               // 绘制声音按钮
               audioButton.paint(g2d);

               g2d.setPaint(Color.RED);
               g2d.drawRect(0,0, (int)getSize().getWidth()-2, (int)getSize().getHeight()-2);

          }

          // 加载声音
          private void loadAudio()
          {
               audioClips = new AudioClip[4];
               for(int i = 0; i < 4; i++)
               {
                    audioClips[i] = getAudioClip(getCodeBase(), AUDIO_FILES[i]);
               }
               audioEnabled = true;
          }
     }     // Nodez

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?