Пример #1
1
 public MapBuilder(String name, File toLoad, File toSave, String tileDir) {
   super(name);
   currTileImg = null;
   currTileLoc = "";
   try {
     System.out.println(tileDir);
     currTileImg = new ImageIcon(getTile(tileDir, 0, 0, DISPLAY_SCALE));
     currTileLoc = "0_0";
   } catch (IOException e) {
     System.out.println("Generating current tile failed.");
     System.out.println(e);
     System.exit(0);
   }
   currTileDisplay = new JLabel(new ImageIcon(scaleImage(currTileImg.getImage(), 2)));
   this.input = toLoad;
   output = toSave;
   this.tileDir = tileDir;
   if (toLoad != null) {
     try {
       backEnd = loadMap(toLoad);
     } catch (FileNotFoundException e) {
       System.err.println("Could not find input file.");
       System.exit(0);
     }
   } else {
     backEnd = emptyMap(DEFAULT_WIDTH, DEFAULT_HEIGHT);
   }
   mapWidth = backEnd.getWidth();
   mapHeight = backEnd.getHeight();
 }
Пример #2
1
  private void winning() {
    String[] options = {"Try again", "Go back to Start", "Quit"};
    InformationFrame.stopClock();
    int n =
        JOptionPane.showOptionDialog(
            rootPane,
            "You won!"
                + "\n╔══╗░░░░╔╦╗░░╔═════╗"
                + "\n║╚═╬════╬╣╠═╗║░▀░▀░║"
                + "\n╠═╗║╔╗╔╗║║║╩╣║╚═══╝║"
                + "\n╚══╩╝╚╝╚╩╩╩═╝╚═════╝",
            "Smileys  c:  ☺  ☻  ت ヅ  ツ  ッ  シ Ü  ϡ  ﭢ" + "\nWhat would you like to do now?",
            JOptionPane.YES_NO_CANCEL_OPTION,
            JOptionPane.QUESTION_MESSAGE,
            null,
            options,
            options[2]);

    if (n == 2) {
      // System.out.println("n = " + n);
      System.exit(0);
    } else if (n == 1) {
      InformationFrame.dispose();
      main(null);
      this.dispose();
    } else if (n == 0) {
      String difficulty = MainManager.getMainGrid().getDifficulty();
      MainPanel.removeAll();
      constructMinesweeper(difficulty.toLowerCase());
    }
  }
Пример #3
1
 public void actionPerformed(ActionEvent ae) {
   // 响应用户点击
   if (ae.getActionCommand().equals("new_game")) {
     // 如果选择 “开始新游戏” 则跳转到游戏开始
     ae_panel = new GamePanel(false);
     Thread ae_thread = new Thread(ae_panel);
     ae_thread.start();
     // 先删除旧面板 -- 开始界面
     this.remove(start_panel);
     this.add(ae_panel);
     this.addKeyListener(ae_panel);
     this.setVisible(true); // 如果没有这句点击后不会出现新的游戏面板
   } else if (ae.getActionCommand().equals("qs_game")) {
     // 退出时保存游戏进度
     Recorder.set_enemies(ae_panel.enemies);
     Recorder.save_game_data();
     // 0 表示正常退出
     System.exit(0);
   } else if (ae.getActionCommand().equals("restart_old_game")) {
     // 恢复游戏数据 -- 如果曾经保存
     Recorder.recovery_position();
     ae_panel = new GamePanel(true);
     Thread ae_thread = new Thread(ae_panel);
     ae_thread.start();
     // 先删除旧面板 -- 开始界面
     this.remove(start_panel);
     this.add(ae_panel);
     this.addKeyListener(ae_panel);
     this.setVisible(true);
   } else if (ae.getActionCommand().equals("save_now")) {
     Recorder.set_enemies(ae_panel.enemies);
     Recorder.recovery_position();
   }
 }
  // initialize data hash table servers
  // read server addresses from file and initialize the servers
  private void initServers() {

    try {
      java.net.URL path = ClassLoader.getSystemResource(clientSettingFile);
      FileReader fr = new FileReader(path.getFile());
      BufferedReader br = new BufferedReader(fr);
      try {
        String[] portMap = br.readLine().split(",");
        mServerCount = portMap.length;
        mPortMap = new int[mServerCount];
        for (int i = 0; i < mServerCount; i++) {
          mPortMap[i] = Integer.parseInt(portMap[i]);
        }
      } catch (IOException e) {
        e.printStackTrace();
        System.exit(-1);
      }
    } catch (FileNotFoundException e2) {
      e2.printStackTrace();
      System.exit(-1);
    }

    mDhtServerArray = new IDistributedHashTable[mServerCount];
    for (int i = 0; i < mServerCount; i++) {
      try {
        mDhtServerArray[i] =
            (IDistributedHashTable)
                Naming.lookup("rmi://localhost:" + mPortMap[i] + "/DistributedHashTable");
        appendOutput("server: " + (i + 1) + " is connected");
      } catch (Exception e) {
        appendOutput("initServers: " + (i + 1) + " " + e.getMessage());
      }
    }
  }
Пример #5
0
 private static ArrayList<String> getArrayOfValues(String key) {
   ArrayList<String> stringArrayList = new ArrayList<>();
   try (BufferedReader br = new BufferedReader(new FileReader(CONFIG_FILE_LOCATION))) {
     for (String line; (line = br.readLine()) != null; ) {
       if (line.length() > 0) {
         if (line.charAt(0) != '#' && line.contains(key)) {
           String[] values = line.split("=");
           if (values.length == 2) {
             stringArrayList.add(values[1]);
           } else {
             infoBox("Value for ''" + key + "'' not defined\nProgram will exit!", "Error");
             System.exit(-2);
           }
         }
       }
     }
   } catch (IOException e) {
     infoBox(
         "Error reading config file. Save config file to C:\\config.conf and run program again.",
         "Error");
     e.printStackTrace();
     System.exit(1);
   }
   return stringArrayList;
 }
Пример #6
0
  /**
   * Creates a new entity enumeration icon chooser.
   *
   * @param enumeration the enumeration to display in this combo box
   */
  public EnumerationIconChooser(Class<E> enumeration) {
    super();

    this.enumeration = enumeration;

    try {
      this.icons = (ImageIcon[]) enumeration.getMethod("getIcons").invoke(null);
      for (int i = 0; i < icons.length; i++) {
        addItem(icons[i]);
      }
    } catch (NoSuchMethodException ex) {
      System.err.println(
          "The method 'getIcons()' is missing in enumeration " + enumeration.getName());
      ex.printStackTrace();
      System.exit(1);
    } catch (IllegalAccessException ex) {
      System.err.println(
          "Cannot access method 'getIcons()' in enumeration "
              + enumeration.getName()
              + ": ex.getMessage()");
      ex.printStackTrace();
      System.exit(1);
    } catch (InvocationTargetException ex) {
      ex.getCause().printStackTrace();
      System.exit(1);
    }
  }
Пример #7
0
  public static void main(String[] args) throws IOException {
    if (args.length != 1) {
      System.err.printf("Usage: DesignerApplication propertyFile\n");
      System.exit(-1);
    }

    Properties properties = parseProperties(args[0]);
    String repositoryFile = properties.getProperty("octopus.repository.file");
    if (repositoryFile == null || repositoryFile.length() == 0) {
      System.err.printf(
          "The property file %s is missing the octopus.repository.file property", args[0]);
      System.exit(-1);
    }

    OctopusRepository repository = new OctopusDb4oRepository(repositoryFile);
    LookAndFeelFactory.installDefaultLookAndFeelAndExtension();
    final DesignerFrame designerFrame = new DesignerFrame(repository);
    try {
      designerFrame.loadInitialDataFromRepository();

      SwingUtilities.invokeLater(
          new Runnable() {
            @Override
            public void run() {
              designerFrame.setVisible(true);
            }
          });
    } catch (RepositoryException e) {
      ErrorDialog.showErrorDialog(null, e, "Problem loading initial data from repository");
    }
  }
  public void userInput() {
    int input;
    int counter = 0;
    while (counter < 9) {
      while (counter % 2 == 0) {
        input =
            Integer.parseInt(
                JOptionPane.showInputDialog(null, "Please input the location for X: "));
        input = input - 1;

        if (verifyInput(input)) {
          if (isEmpty(input)) {
            board[input / 3][input % 3] = 'X';
            if (checkWinner()) {
              JOptionPane.showMessageDialog(null, "The Winner is X!");
              System.exit(0);
            }
            counter++;
            printBoard();
          }
        } else if (!verifyInput(input)) {
          JOptionPane.showMessageDialog(null, "The location you entered is incorrect");
        } else {
          JOptionPane.showMessageDialog(
              null, "The location you entered is already taken by " + board[input / 3][input % 3]);
        }
      }

      while (counter % 2 != 0) {
        input =
            Integer.parseInt(
                JOptionPane.showInputDialog(null, "Please input the location for O: "));
        input = input - 1;
        if (verifyInput(input)) {
          if (isEmpty(input)) {
            board[input / 3][input % 3] = 'O';
            intboard[input / 3][input % 3] = input;
            if (checkWinner()) {
              JOptionPane.showMessageDialog(null, "The Winner is O!");
              System.exit(0);
            }
            counter++;
            printBoard();
          } else {
            JOptionPane.showMessageDialog(
                null,
                "The location you entered is already taken by " + board[input / 3][input % 3]);
          }
        } else if (!verifyInput(input)) {
          JOptionPane.showMessageDialog(null, "The location you entered is incorrect");
        }
      }

      if (counter == 9) {
        JOptionPane.showMessageDialog(null, "The game is a tie!");
        System.exit(0);
      }
    }
  }
Пример #9
0
  public static void main(String args[]) {
    boolean debug = true;

    // Parse command-line arguments
    try {
      for (int i = 0; i < args.length; i++) {
        if (args[i].equals("-help")) {
          System.out.println("Usage: java Mesh <filename>");
          System.out.println("   or: java Mesh <shape> [uSize vSize]");
          System.out.println(" where <shape> is one of:");
          System.out.println(" -ellipsoid  -torus");
          System.exit(0);
        } else if (args[i].equals("-nodebug")) {
          debug = false;
        } else if (args[i].charAt(0) == '-') {
          // Primitive
          String primName = args[i].substring(1);

          int uSize = 24, vSize = 24;

          // Check for u/v
          if (args.length >= i + 3) {
            uSize = (new Integer(args[i + 1])).intValue();
            vSize = (new Integer(args[i + 2])).intValue();
            i += 2;
          }

          // Create primitive
          if (primName.equals("ellipsoid")) {
            shape = new Ellipsoid(uSize, vSize);
          } else if (primName.equals("torus")) {
            shape = new Torus(uSize, vSize);
          } else {
            throw new Exception("Unknown primitive: " + primName);
          }
        } else {
          // Filename
          shape = new PolyMesh(args[i]);
        }
      }
      if (shape == null) throw new Exception("No shape specified.");
    } catch (Exception e) {
      e.printStackTrace();
      System.out.println("Error: " + e.getMessage());
      System.exit(1);
    }

    // Create main window
    try {
      Mesh m = new Mesh(debug);
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(1);
    }
  }
Пример #10
0
    public void actionPerformed(ActionEvent arg) {

      if (arg.getSource() == exitMenuItem) {
        System.exit(0);
      }
      if (arg.getSource() == aboutMenuItem) {
        System.exit(0);
      }
      if (arg.getSource() == helpMenuItem) {
        System.exit(0);
      }
    }
Пример #11
0
 public void actionPerformed(ActionEvent e) {
   JFileChooser chooser = new JFileChooser();
   chooser.setDialogTitle("Load");
   int choice = 0;
   do {
     int result = chooser.showOpenDialog(null);
     if (result == JFileChooser.APPROVE_OPTION) {
       file = chooser.getSelectedFile();
       try {
         if (file != null) {
           fileName = file.getCanonicalPath();
           reader = new BufferedReader(new FileReader(fileName));
           String line;
           while ((line = reader.readLine()) != null) {
             myPatternList.add(line);
           }
           //							for(int i=0;i<myPatternList.size();i++) {
           //								responseArea.append(myPatternList.get(i)+"\n");
           //							}
         }
         choice = 2;
         reader.close();
       } catch (IOException c) {
         c.printStackTrace();
         Object[] options = new String[] {"Load New File", "Exit"};
         choice =
             JOptionPane.showOptionDialog(
                 null,
                 "Invalid FileChoosen." + "Would you like to load a new file " + "or exit?",
                 "Options",
                 JOptionPane.YES_NO_OPTION,
                 JOptionPane.ERROR_MESSAGE,
                 null,
                 options,
                 options[0]);
         if (choice == 1) System.exit(0);
       }
     } else if (result == JFileChooser.CANCEL_OPTION) {
       Object[] options = new String[] {"Load Different File", "Exit"};
       choice =
           JOptionPane.showOptionDialog(
               null,
               "Would you like to load a new file " + " or exit?",
               "Options",
               JOptionPane.YES_NO_OPTION,
               JOptionPane.ERROR_MESSAGE,
               null,
               options,
               options[0]);
       if (choice == 1) System.exit(0);
     }
   } while (choice == 0);
 }
Пример #12
0
  /** @param args */
  public void run(String[] arg0) {
    try {
      boolean chosen = buildUpdateGUI();
      if (!chosen) System.exit(0);

      if (getShotsUsingAssets()) if (confirmShotsToUpdate() == null) System.exit(0);
      processNodes();
      System.err.println("DONE");
      System.exit(0);
    } catch (PipelineException e) {
      e.printStackTrace();
    }
  } // end run(String)
Пример #13
0
  /** @param args */
  public static void main(String[] args) {
    UpdateAssetGUI gui = new UpdateAssetGUI();
    try {
      boolean chosen = gui.buildUpdateGUI();
      if (!chosen) System.exit(0);

      if (gui.getShotsUsingAssets()) if (gui.confirmShotsToUpdate() == null) System.exit(0);
      gui.processNodes();
      System.err.println("DONE");
      System.exit(0);
    } catch (PipelineException e) {
      e.printStackTrace();
    }
  } // end main(args)
  public void launch() {
    try {
      long time = System.nanoTime();
      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

      monitor = new ProgressMonitor();
      monitor.setMaximum(5);

      updateState(BootstrapState.UPDATE_CHECK);
      {
        CountDownLatch latch = new CountDownLatch(2);
        runTask(TaskBootstrapUpdateCheck.class, latch);
        runTask(TaskInstallerUpdateCheck.class, latch);
        latch.await();
      }

      updateState(BootstrapState.LOAD_DEPENDENCIES);
      {
        runTask(TaskLoadDependencies.class);
      }

      updateState(BootstrapState.DOWNLOAD);
      {
        runTask(TaskDownload.class);
      }

      updateState(BootstrapState.SETUP_ENVIRONMENT);
      {
        runTask(TaskCheckJavaVersion.class);
        runTask(TaskBuildClasspath.class);
      }

      System.out.println(
          "Took " + ((System.nanoTime() - time) / 1000000f) + "ms to launch installer");
      updateState(BootstrapState.START_INSTALLER);
      {
        runTask(TaskLaunchInstaller.class);
      }

      updateState(BootstrapState.FINISHED);
    } catch (BootstrapException ex) {
      handleException(ex);
      System.exit(2);
    } catch (Exception ex) {
      handleException(ex);
      System.exit(-1);
    } finally {
      monitor.close();
    }
  }
Пример #15
0
 public void actionPerformed(ActionEvent evt) {
   Object source = evt.getSource();
   if (source == cancelButton) System.exit(0);
   else if (source == prevButton) {
     currentPage--;
     pageChanged();
   } else if (source == nextButton) {
     if (currentPage == pages.length - 1) System.exit(0);
     else {
       currentPage++;
       pageChanged();
     }
   }
 }
Пример #16
0
  @Override
  public void actionPerformed(ActionEvent e) {
    // 对用户不同的选择做出不同的处理
    if (e.getActionCommand().equals("new game")) {
      // 创建游戏界面面板
      mp = new MyPanel("newGame");
      // 启动MyPanel线程
      Thread t = new Thread(mp);
      t.start();
      // 先删除旧Panel
      this.remove(msp);
      this.add(mp);
      // 注册监听
      this.addKeyListener(mp);
      // 显示(刷新JFrame)
      this.setVisible(true);

    } else if (e.getActionCommand().equals("exit")) {
      // 用户点击了退出系统菜单
      // 保存击毁敌人数量.
      Recorder.SaveRecord();

      System.exit(0);
    } // 对存盘退出做处理
    else if (e.getActionCommand().equals("saveExit")) {
      Recorder rd = new Recorder();
      rd.setEts(mp.enemyTanks);
      // 保存击毁敌人的数量和敌人的坐标
      rd.SaveRecAndEnemy();

      // 退出(0代表正常退出,1代表异常退出)
      System.exit(0);
    } else if (e.getActionCommand().equals("continue")) {
      //
      // 创建游戏界面面板
      mp = new MyPanel("con");
      //            mp.flag="con";

      // 启动MyPanel线程
      Thread t = new Thread(mp);
      t.start();
      // 先删除旧Panel
      this.remove(msp);
      this.add(mp);
      // 注册监听
      this.addKeyListener(mp);
      // 显示(刷新JFrame)
      this.setVisible(true);
    }
  }
Пример #17
0
  void doSourceFileUpdate() {
    BufferedReader bufferIn = null;
    String str1 = new String();
    String strContent = new String();
    String sliderValue = new String();
    String newLine = System.getProperty("line.separator");
    StringBuffer strBuf = new StringBuffer();
    int posFound = 0;
    int i = 0;
    PSlider slider;

    // Read the original source file to input buffer
    try {
      bufferIn = new BufferedReader(new FileReader(exampleSource));
    } catch (FileNotFoundException fe) {
      System.err.println("Example Source File not found " + fe);
      System.exit(-1);
    }
    // get the first line of the buffer.
    try {
      str1 = bufferIn.readLine();
    } catch (IOException ie) {
      System.err.println("Error reading line from the buffer " + ie);
      System.exit(-1);
    }
    // Transfer the whole content of the input buffer to the string
    try {
      do strContent += str1 + newLine;
      while ((str1 = bufferIn.readLine()) != null);
    } catch (IOException ie) {
      System.err.println("Error readding content of the input buffer " + ie);
      System.exit(-1);
    }
    // do the replacement.

    for (i = 0; i < COMPONENTS; i++) {
      // get the current value of slider
      slider = (PSlider) vSlider.elementAt(i);
      sliderValue = slider.getValue();
      // construct the search string
      str1 = "$$$" + (i + 1);
      // get the position of the search string in the content string.
      strBuf = new StringBuffer(strContent);
      posFound = strContent.indexOf(str1);
      strBuf.replace(posFound, posFound + str1.length(), sliderValue);
      strContent = new String(strBuf);
    }
    textPane.setText(strContent);
  }
Пример #18
0
    public void actionPerformed(ActionEvent e) {
      JFileChooser chooser = new JFileChooser();
      chooser.setDialogTitle("SaveAs");
      int choice = 0;
      do {
        int result = chooser.showOpenDialog(null);
        if (result == JFileChooser.APPROVE_OPTION) {
          file = chooser.getSelectedFile();
          try {
            if (file != null) {
              fileName = file.getCanonicalPath();
              printWriter = new PrintWriter(new FileOutputStream(fileName), true);
            }
            printWriter.append(responseArea.getText());
            choice = 2;

          } catch (IOException c) {
            c.printStackTrace();
            Object[] options = new String[] {"Choose New File", "Exit"};
            choice =
                JOptionPane.showOptionDialog(
                    null,
                    "Invalid FileChoosen." + "Would you like to choose a new file " + "or exit?",
                    "Options",
                    JOptionPane.YES_NO_OPTION,
                    JOptionPane.ERROR_MESSAGE,
                    null,
                    options,
                    options[0]);
            if (choice == 1) System.exit(0);
          }
        } else if (result == JFileChooser.CANCEL_OPTION) {
          Object[] options = new String[] {"Choose Different File", "Exit"};
          choice =
              JOptionPane.showOptionDialog(
                  null,
                  "Would you like to choose a new file " + " or exit?",
                  "Options",
                  JOptionPane.YES_NO_OPTION,
                  JOptionPane.ERROR_MESSAGE,
                  null,
                  options,
                  options[0]);
          if (choice == 1) System.exit(0);
        }
      } while (choice == 0);
      printWriter.flush();
      printWriter.close();
    }
Пример #19
0
  public UpdateAssetGUI() {
    try {
      PluginMgrClient.init();
      mclient = new MasterMgrClient();
      queue = new QueueMgrClient();
      plug = PluginMgrClient.getInstance();
      log = LogMgr.getInstance();

      pAssetManager = new TreeMap<String, AssetInfo>();

      project = "lr";
      charList = new TreeMap<String, String>();
      setsList = new TreeMap<String, String>();
      propsList = new TreeMap<String, String>();

      potentialUpdates = new TreeSet<String>();
      pSubstituteFields = new TreeMap<String, LinkedList<JBooleanField>>();

      /* load the look-and-feel */
      {
        try {
          SynthLookAndFeel synth = new SynthLookAndFeel();
          synth.load(
              LookAndFeelLoader.class.getResourceAsStream("synth.xml"), LookAndFeelLoader.class);
          UIManager.setLookAndFeel(synth);
        } catch (java.text.ParseException ex) {
          log.log(
              LogMgr.Kind.Ops,
              LogMgr.Level.Severe,
              "Unable to parse the look-and-feel XML file (synth.xml):\n" + "  " + ex.getMessage());
          System.exit(1);
        } catch (UnsupportedLookAndFeelException ex) {
          log.log(
              LogMgr.Kind.Ops,
              LogMgr.Level.Severe,
              "Unable to load the Pipeline look-and-feel:\n" + "  " + ex.getMessage());
          System.exit(1);
        }
      }

      /* application wide UI settings */
      {
        JPopupMenu.setDefaultLightWeightPopupEnabled(false);
        ToolTipManager.sharedInstance().setLightWeightPopupEnabled(false);
      }
    } catch (PipelineException ex) {
      ex.printStackTrace();
    } // end try/catch
  } // end constructor
Пример #20
0
 public static void main(String[] args) {
   ORB orb = null;
   orb = ORB.init(args, null);
   if (orb != null) {
     try {
       new ClientGui(orb);
     } catch (Exception e) {
       System.err.println(e);
       System.exit(-1);
     }
   } else {
     System.err.println("can't initiate orb");
     System.exit(-1);
   }
 } /*end of main*/
Пример #21
0
  public GameFile() {
    game = "";

    // load character names and descriptions
    characters = "";
    File characterFile = new File("/home/cory/Programming/treasure_hunt/data/characters.data");
    try {
      BufferedReader in = new BufferedReader(new FileReader(characterFile));
      for (String s = in.readLine(); s != null; s = in.readLine()) {
        characters += s + "\n";
      }
      characters.trim();
      in.close();
    } catch (IOException e) {
      System.out.println("File I/O error! Couldn't load character data file.");
      System.exit(1);
    }

    // load weapon names and descriptions
    weapons = "";
    File weaponFile = new File("/home/cory/Programming/treasure_hunt/data/weapons.data");
    try {
      BufferedReader in = new BufferedReader(new FileReader(weaponFile));
      for (String s = in.readLine(); s != null; s = in.readLine()) {
        weapons += s + "\n";
      }
      weapons.trim();
      in.close();
    } catch (IOException e) {
      System.out.println("File I/O error! Couldn't load weapon data file.");
      System.exit(1);
    }

    // load treasure names and desciptions
    treasures = "";
    File treasureFile = new File("/home/cory/Programming/treasure_hunt/data/treasures.data");
    try {
      BufferedReader in = new BufferedReader(new FileReader(treasureFile));
      for (String s = in.readLine(); s != null; s = in.readLine()) {
        treasures += s + "\n";
      }
      treasures.trim();
      in.close();
    } catch (IOException e) {
      System.out.println("File I/O error! Couldn't load treasure data file.");
      System.exit(1);
    }
  }
Пример #22
0
  public static void main(String[] args) {
    // read arguments and respond correctly
    File in;
    File out;
    String tileDirectory;
    if (args.length == 0 || args.length > 2) {
      in = null;
      out = null;
      tileDirectory = "";
      System.err.println("Incorrect number of arguments. Required: Filename (tileset path)");
      System.exit(0);
    } else if (args.length == 1) { // load old file
      in = new File(args[0]);
      out = in;
      Scanner s = null;
      try {
        s = new Scanner(in);
      } catch (FileNotFoundException e) {
        System.out.println("Could not find input file.");
        System.exit(0);
      }
      tileDirectory = s.nextLine();
    } else {
      in = null;
      out = new File(args[0]);
      tileDirectory = args[1];
      try {
        File f = new File(tileDirectory);
        if (!f.isDirectory()) {
          throw new IOException("Tileset does not exist");
        }
      } catch (IOException e) {
        System.err.println(e);
        System.out.println("This error is likely thanks to an invalid tileset path");
        System.exit(0);
      }
    }

    MapBuilder test = new MapBuilder("Map Editor", in, out, tileDirectory);

    // Build GUI
    SwingUtilities.invokeLater(
        new Runnable() {
          public void run() {
            test.CreateAndDisplayGUI();
          }
        });
  }
Пример #23
0
 public void initGame() {
   String cfgname = null;
   if (isApplet()) {
     cfgname = getParameter("configfile");
   } else {
     JFileChooser chooser = new JFileChooser();
     chooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
     chooser.setDialogTitle("Choose a config file");
     int returnVal = chooser.showOpenDialog(this);
     if (returnVal == JFileChooser.APPROVE_OPTION) {
       cfgname = chooser.getSelectedFile().getAbsolutePath();
     } else {
       System.exit(0);
     }
     // XXX read this as resource!
     // cfgname = "mygeneratedgame.appconfig";
   }
   gamecfg = new AppConfig("Game parameters", this, cfgname);
   gamecfg.loadFromFile();
   gamecfg.defineFields("gp_", "", "", "");
   gamecfg.saveToObject();
   initMotionPars();
   // unpause and copy settingswhen config window is closed
   gamecfg.setListener(
       new ActionListener() {
         public void actionPerformed(ActionEvent e) {
           start();
           requestGameFocus();
           initMotionPars();
         }
       });
   defineMedia("simplegeneratedgame.tbl");
   setFrameRate(35, 1);
 }
Пример #24
0
 /**
  * The ActionListener implementation
  *
  * @param event the event.
  */
 public void actionPerformed(ActionEvent event) {
   String searchText = textField.getText().trim();
   if (searchText.equals("") && !saveAs.isSelected() && (fileLength > 10000000)) {
     textPane.setText("Blank search text is not allowed for large IdTables.");
   } else {
     File outputFile = null;
     if (saveAs.isSelected()) {
       outputFile = chooser.getSelectedFile();
       if (outputFile != null) {
         String name = outputFile.getName();
         int k = name.lastIndexOf(".");
         if (k != -1) name = name.substring(0, k);
         name += ".txt";
         File parent = outputFile.getAbsoluteFile().getParentFile();
         outputFile = new File(parent, name);
         chooser.setSelectedFile(outputFile);
       }
       if (chooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) System.exit(0);
       outputFile = chooser.getSelectedFile();
     }
     textPane.setText("");
     Searcher searcher = new Searcher(searchText, event.getSource().equals(searchPHI), outputFile);
     searcher.start();
   }
 }
Пример #25
0
  @Override
  public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
      System.exit(0);
    }

    // TODO Auto-generated method stub
    if (state == 1) // we are in a story
    {
      if (fadeCounter < FADETIMELIMIT) {
        fadeCounter = FADETIMELIMIT;
        oldbg = bg;
      }

      fadeUpdate = true;
      fadeCounter = 0;
      progress(); // keep going
    } else if (state == 2) {
      if (e.getKeyCode() == KeyEvent.VK_1) {
        index = next(tag, index, 1);
        progress();
      } else if (e.getKeyCode() == KeyEvent.VK_2) {
        index = next(tag, index, 2);
        progress();
      } else if (e.getKeyCode() == KeyEvent.VK_3) {
        index = next(tag, index, 3);
        progress();
      }
    }
  }
  // set up tic-tac-toe server and GUI that displays messages
  public TicTacToeServer() {
    super("Tic-Tac-Toe Server");

    board = new char[9];
    players = new Player[2];
    currentPlayer = PLAYER_X;
    // checkBoard = [3][3];
    // ExecutorService endGameThread = Executors.newCachedThreadPool();

    // set up ServerSocket
    try {
      server = new ServerSocket(12345, 2);
    }

    // process problems creating ServerSocket
    catch (IOException ioException) {
      ioException.printStackTrace();
      System.exit(1);
    }

    // set up JTextArea to display messages during execution
    outputArea = new JTextArea();
    getContentPane().add(outputArea, BorderLayout.CENTER);
    outputArea.setText("Server awaiting connections\n");

    setSize(300, 300);
    setVisible(true);
  } // end TicTacToeServer constructor
Пример #27
0
  public static void main(String[] args) {
    double n1;
    double n2;
    double n3;
    double sum;
    double average;

    String in, out;
    in = JOptionPane.showInputDialog("Enter the first number");
    n1 = Double.parseDouble(in);
    in = JOptionPane.showInputDialog("Enter the second number");
    n2 = Double.parseDouble(in);
    in = JOptionPane.showInputDialog("Enter the third number");
    n3 = Double.parseDouble(in);

    sum = n1 + n2 + n3;
    average = sum / 3;

    // Build the out String
    out = "";
    out = out + "The sum of " + n1 + "," + n2 + " and " + n3 + " is " + sum;
    out = out + "\nThe average of " + n1 + "," + n2 + " and " + n3 + " is " + average;

    JOptionPane.showMessageDialog(null, out);
    System.exit(0);
  }
Пример #28
0
  public static void main(String[] args) {
    GUI dialog = new GUI();

    dialog.pack();
    dialog.setVisible(true);
    System.exit(0);
  }
Пример #29
0
 public void actionPerformed(ActionEvent ev) {
   if (ev.getSource() == newg) {
     dialog.hide();
     resetBoard();
   }
   if (ev.getSource() == quitg) System.exit(0);
 }
  // wait for two connections so game can be played
  public void execute() {
    // wait for each client to connect
    for (int i = 0; i < players.length; i++) {

      // wait for connection, create Player, start thread
      try {
        players[i] = new Player(server.accept(), i); // array of threads
        players[i].start(); // runs new thread L211
        // players [1] / go to L175
      }

      // process problems receiving connection from client
      catch (IOException ioException) {
        ioException.printStackTrace();
        System.exit(1);
      }
    } // finished this

    // Player X is suspended until Player O connects.
    // Resume player X now.
    synchronized (players[PLAYER_X]) { // this synchronised block for playerx
      players[PLAYER_X].setSuspended(false); // call set suspend = false L278
      players[PLAYER_X].notify(); // We wake up thread
    } // player x is now in L230
  } // end method execute