예제 #1
0
 /*setup the game */
 private void setup() {
   t0 = System.currentTimeMillis(); /*Times the beginning of the game */
   // int size;
   Scanner in = new Scanner(System.in);
   // System.out.println("Enter the size of available");
   // size = in.nextInt();
   initiateScores();
   placeWalls();
   placeStates();
   placeLabels();
   randomizeOrderRent(); /*randomizes the order of the equipment for the On Rent state */
   System.out.println(
       "How many High Runners at price $" + EQUIPMENTCOSTS[0] + " do you want to buy?");
   int type1Equip = in.nextInt();
   System.out.println(
       "How many Medium Runners at price $" + EQUIPMENTCOSTS[1] + " do you want to buy?");
   int type2Equip = in.nextInt();
   System.out.println(
       "How many Low Runners at price $" + EQUIPMENTCOSTS[2] + " do you want to buy?");
   int type3Equip = in.nextInt();
   capitalInvested =
       EQUIPMENTCOSTS[0] * type1Equip
           + EQUIPMENTCOSTS[1] * type2Equip
           + EQUIPMENTCOSTS[2] * type3Equip;
   capitalLabel.setLabel("Capital Invested: $" + capitalInvested);
   fillAvailable(type1Equip, type2Equip, type3Equip); // fills with the proper number of equipment
   // fillStates(size,INITRENT,INITSHOP);
   placeEquipments();
 }
예제 #2
0
  /**
   * Opens a file. If the file can be opened, get a drawing time estimate, update recent files list,
   * and repaint the preview tab.
   *
   * @param filename what file to open
   */
  public void LoadGCode(String filename) {
    CloseFile();

    try {
      Scanner scanner = new Scanner(new FileInputStream(filename));
      linesTotal = 0;
      gcode = new ArrayList<String>();
      try {
        while (scanner.hasNextLine()) {
          gcode.add(scanner.nextLine());
          ++linesTotal;
        }
      } finally {
        scanner.close();
      }
    } catch (IOException e) {
      Log("<span style='color:red'>File could not be opened.</span>\n");
      RemoveRecentFile(filename);
      return;
    }

    previewPane.setGCode(gcode);
    fileOpened = true;

    EstimateDrawTime();
    UpdateRecentFiles(filename);
    Halt();
  }
예제 #3
0
  public static void main(String[] args) throws IOException {

    // First reads in the lines from the .txt file.  The first and second lines determine the start
    // and ending point of the maze.
    // The rest of the lines give the locations of the corners of each convex polygon in the maze.

    //        Example map input:
    //        1, 3
    //        34, 19
    //        0, 14; 6, 19; 9, 15; 7, 8; 1, 9
    //        2, 6; 17, 6; 17, 1; 2, 1
    //        12, 15; 14, 8; 10, 8
    //        14, 19; 18, 20; 20, 17; 14, 13
    //        18, 10; 23, 6; 19, 3
    //        22, 19; 28, 19; 28, 9; 22, 9
    //        25, 6; 29, 8; 31, 6; 31, 2; 28, 1; 25, 2
    //        31, 19; 34, 16; 32, 8; 29, 17

    // Open specified text file
    List<String> list = new ArrayList<String>();
    File library = new File(args[0]);
    Scanner sc = new Scanner(library);

    // Reads in every line of the text file
    // creates a new String for every line, then adds it to an arraylist
    while (sc.hasNextLine()) {
      String line;
      line = sc.nextLine();
      list.add(line);
    }

    // Takes the first and second lines as the start and goal points
    int count = 0;

    sPoint = list.get(0);
    ePoint = list.get(1);

    sPoint = sPoint.replace(" ", "");
    ePoint = ePoint.replace(" ", "");

    // remove the first line from the polygon list
    list.remove(0);

    // Create a 2 element array for the start point
    String[] Starter = sPoint.split(",");
    String[] Ender = ePoint.split(",");
    Startx = Double.parseDouble(Starter[0]);
    Starty = Double.parseDouble(Starter[1]);

    Polygon[] FinalPolygons = ListPolygons(list);

    // Text Graph of the polygon maze and the Start/End points
    graph(FinalPolygons);

    // A* search algorithm is performed to find the shortest path
    AStarSearch(FinalPolygons);
  }
예제 #4
0
 public void readFile(String name) { // reads the file and puts everything in the stats list
   Scanner inFile = null;
   stats = new ArrayList<String>();
   chars = new ArrayList<String>();
   powerUps = new ArrayList<String>();
   try {
     inFile = new Scanner(new BufferedReader(new FileReader(name + ".txt")));
     while (inFile.hasNextLine()) {
       stats.add(inFile.nextLine());
     }
   } catch (IOException ex) {
     System.out.println("Did you forget to make the" + name + ".txt file?");
   }
 }
예제 #5
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();
          }
        });
  }
예제 #6
0
  public Map loadMap(File input) throws FileNotFoundException {
    Scanner s = new Scanner(input);
    tileDir = s.nextLine();
    int width = s.nextInt();
    int height = s.nextInt();
    Map toReturn = new Map(width, height, tileDir);
    s.nextLine(); // eat up rest of line.
    for (int y = 0; y < height; y++) {
      String line = s.nextLine();
      Scanner lineReader = new Scanner(line);
      List<Tile> tList = new ArrayList<Tile>();
      for (int x = 0; x < width; x++) {
        String[] values = lineReader.next().split("/");
        String name = values[0];
        int[] picLocation = new int[2];
        for (int i = 0; i < picLocation.length; i++) {
          picLocation[i] = Integer.parseInt(values[1].split("_")[i]);
        }
        ImageIcon img = null;
        try {
          img = new ImageIcon(getTile(tileDir, picLocation[0], picLocation[1], DISPLAY_SCALE));
        } catch (IOException e) {
          System.out.println("Could not find image.");
          img =
              new ImageIcon(
                  new BufferedImage(
                      TILE_SIZE * DISPLAY_SCALE,
                      TILE_SIZE * DISPLAY_SCALE,
                      BufferedImage.TYPE_INT_RGB));
        }
        int avoid = Integer.parseInt(values[2]);
        int def = Integer.parseInt(values[3]);
        String[] movString = values[4].split(",");
        int[] moveCost = new int[movString.length];
        for (int i = 0; i < moveCost.length; i++) {
          moveCost[i] = Integer.parseInt(movString[i]);
        }
        String special = values[5];

        Tile t =
            new Tile(
                img,
                name,
                avoid,
                def,
                moveCost,
                special,
                true,
                "" + picLocation[0] + "_" + picLocation[1]);
        tList.add(t);
        t.setMaximumSize(new Dimension(TILE_SIZE * DISPLAY_SCALE, TILE_SIZE * DISPLAY_SCALE));
        t.setPreferredSize(new Dimension(TILE_SIZE * DISPLAY_SCALE, TILE_SIZE * DISPLAY_SCALE));
        t.addMouseListener(new MapButtonListener());
      }
      toReturn.addRow(tList);
    }
    return toReturn;
  }
예제 #7
0
  /** Display the file in the text area */
  private void showFile() {
    Scanner input = null;
    try {
      // Use a Scanner to read text from the file
      input = new Scanner(new File(jtfFilename.getText().trim()));

      // Read a line and append the line to the text area
      while (input.hasNext()) jtaFile.append(input.nextLine() + '\n');
    } catch (FileNotFoundException ex) {
      System.out.println("File not found: " + jtfFilename.getText());
    } catch (IOException ex) {
      ex.printStackTrace();
    } finally {
      if (input != null) input.close();
    }
  }
예제 #8
0
  public TreeViewer(String title, int ulx, int uly, int pw, int ph) {
    super(title, ulx, uly, pw, ph);

    // code to initialize instance variables before animation begins:
    // ------------------------------------------------------------------

    state = "regular";

    spread = 1;
    levelHeight = 10; // 10 levels for the camera region height

    tree = new SackBST();
    String fileName = FileBrowser.chooseFile(true);

    try {
      Scanner input = new Scanner(new File(fileName));
      String s;

      while (input.hasNext()) {
        s = input.nextLine();
        if (s != null) {
          tree.add(s);
        }
      }

      input.close();
    } catch (Exception e) {
      System.out.println("File load failed");
      System.exit(1);
    }

    // code to finish setting up entire window:
    // ------------------------------------------------------------------

    setBackgroundColor(new Color(128, 128, 200));

    // code to set up camera(s)
    // ------------------------------------------------------------------

    cameras.add(new Camera(10, 50, camw, camh, 0, 100, 0, new Color(255, 200, 255)));

    cameras.add(new Camera(10, 50 + camh + 10, camw, 20, 0, 100, 0, new Color(255, 255, 255)));

    // ------------------------------------------------------------------
    // start up the animation:
    super.start();
  }
예제 #9
0
  // Constructor
  public Ballot(int index, int ID, int numCandidates, String title, ArrayList<String> candidates)
      throws IOException {
    _index = index;
    _ID = ID;
    _numCandidates = numCandidates;
    _votes = new int[_numCandidates];
    _title = title;
    _candidates = candidates;
    _usrVotes = new String[numCandidates];

    // if the ballot file already exists, read in the votes for that ballot
    // otherwise the number of votes for each candidate will default to 0
    file = new File(_ID + ".txt");
    if (file.exists()) {
      Scanner reader = new Scanner(file);
      int i = 0;
      while (reader.hasNextLine()) {
        String strLine = reader.nextLine();
        String arrLine[] = strLine.split(":");
        int vote = Integer.parseInt(arrLine[1]);
        _votes[i] = vote;

        i++;
      }
      reader.close();
    }

    _ballotPanel = new JPanel();
    _ballotPanel.setLayout(new GridLayout(_candidates.size() + 1, 1));

    _titleLabel = new JLabel(_title);
    _titleLabel.setHorizontalAlignment(JLabel.CENTER);
    _titleLabel.setFont(new Font("CourierNew", Font.PLAIN, 15));
    _ballotPanel.add(_titleLabel);

    for (int i = 0; i < _candidates.size(); i++) {
      // Make a JButton for each candidate in the ballot
      // Disable it by default. Will enable when the user logs in
      String cText = _candidates.get(i);
      JButton candidate = new JButton(cText);
      candidate.setEnabled(false);
      candidate.addActionListener(_buttonListener);

      _candidateButtons.add(candidate);
      _ballotPanel.add(candidate);
    }
  }
 @Override
 public StringBuilder doInBackground() throws IOException, InterruptedException {
   int lineNumber = 0;
   try (Scanner in = new Scanner(new FileInputStream(file))) {
     while (in.hasNextLine()) {
       String line = in.nextLine();
       lineNumber++;
       text.append(line);
       text.append("\n");
       ProgressData data = new ProgressData();
       data.number = lineNumber;
       data.line = line;
       publish(data);
       Thread.sleep(1); // to test cancellation; no need to do this
       // in your programs
     }
   }
   return text;
 }
예제 #11
0
  // Loads a Player class
  public void loadPlayer(String file) {
    try {
      Scanner data = new Scanner(new BufferedReader(new FileReader(file + ".txt")));
      level = Integer.parseInt(data.next());
      String charinf = data.next();

      ArrayList<Item> previtems = new ArrayList<Item>();
      while (data.hasNext()) {
        previtems.add(new Item(data.next()));
      }

      player =
          new Creature(
              min(40 + level * 3 / 5, 100) / 2,
              min(40 + level * 3 / 5, 100) / 2,
              charinf,
              previtems);
    } catch (Exception ex) {
      System.out.println(ex);
    }
  }
예제 #12
0
  /**
   * Makes a POST request and returns the server response.
   *
   * @param urlString the URL to post to
   * @param nameValuePairs a map of name/value pairs to supply in the request.
   * @return the server reply (either from the input stream or the error stream)
   */
  public static String doPost(String urlString, Map<String, String> nameValuePairs)
      throws IOException {
    URL url = new URL(urlString);
    URLConnection connection = url.openConnection();
    connection.setDoOutput(true);

    PrintWriter out = new PrintWriter(connection.getOutputStream());

    boolean first = true;
    for (Map.Entry<String, String> pair : nameValuePairs.entrySet()) {
      if (first) first = false;
      else out.print('&');
      String name = pair.getKey();
      String value = pair.getValue();
      out.print(name);
      out.print('=');
      out.print(URLEncoder.encode(value, "UTF-8"));
    }

    out.close();

    Scanner in;
    StringBuilder response = new StringBuilder();
    try {
      in = new Scanner(connection.getInputStream());
    } catch (IOException e) {
      if (!(connection instanceof HttpURLConnection)) throw e;
      InputStream err = ((HttpURLConnection) connection).getErrorStream();
      if (err == null) throw e;
      in = new Scanner(err);
    }

    while (in.hasNextLine()) {
      response.append(in.nextLine());
      response.append("\n");
    }

    in.close();
    return response.toString();
  }
예제 #13
0
  public void readFile() throws IOException, FileNotFoundException {
    Scanner inp = new Scanner(System.in);
    System.out.print("Enter the name of the file to process:  ");
    String file;
    file = inp.nextLine();
    System.out.println(file);
    Scanner fileScan = new Scanner(new FileReader(file));
    fileScan.useDelimiter(",");

    numBars = fileScan.nextInt();
    values = new int[numBars];
    labels = new String[numBars];
    for (int i = 0; i < numBars - 1; i++) {
      values[i] = fileScan.nextInt();
      labels[i] = fileScan.next();
      System.out.println(values[i] + " " + labels[i]);
    }
    inp.close();
    fileScan.close();
  }
  private String getFileWords(String s) {
    String output = "";
    try {
      // THIS CODE SEGMENT WILL NOT RUN IN AN APPLET THAT IS NOT "SIGNED"
      // By default applets cannot alter files on the hard drive of the user.
      // If the panel is opened in a regular application the save button should work.
      // This can be tested in HomeworkApplication.java through HomeworkRun.java only

      File inputFile = new File(s);
      Scanner inputScanner = new Scanner(inputFile);

      while (inputScanner.hasNext()) {
        output = output + inputScanner.nextLine() + "\n";
      }

      inputScanner.close();
      String numWords = getWords(output);
      return numWords;
    } catch (IOException e) {
      outputLabel.append(e + "");
    }

    return output;
  }
예제 #15
0
 public void loadData(String file) {
   try {
     Scanner txt = new Scanner(new File(file));
     mp3File = txt.nextLine();
     artist = txt.nextLine();
     album = txt.nextLine();
     while (txt.hasNext()) {
       long noteTime = txt.nextLong();
       int lengthThrowaway = txt.nextInt();
       String states = txt.next().trim();
       lines.add(new Line(noteTime, states));
     }
     song = new Music(mp3File);
     song.load();
   } catch (Exception e) {
     System.out.println(e);
   }
 } // end loadData
예제 #16
0
 public void fileScan(String filename) throws IOException {
   Scanner sf = new Scanner(new File(filename));
   int maxIndex = -1;
   String s = "";
   while (sf.hasNext()) {
     maxIndex++;
     s = sf.nextLine();
     dtr[maxIndex] = s;
     odtr[maxIndex] = s;
     s = sf.nextLine();
     d1[maxIndex] = s;
     od1[maxIndex] = s;
     d2[maxIndex] = sf.nextLine();
     d3[maxIndex] = sf.nextLine();
     d4[maxIndex] = sf.nextLine();
   }
   sf.close();
 }
예제 #17
0
  // experimental
  // ====================================================================
  // ====================================================================
  // ====================================================================
  private void readAndDrawBIGGraph(String file) {
    // behövs inte än
    // @TODO
    // hur rita flera linjer mellan 2 noder? (för flera linjer)
    // reading of the graph should be done in the graph itself
    // it should be possible to get an iterator over nodes and one over edges
    // read in all the stops and lines and draw the lmap
    Scanner indata = null;
    // insert into p-queue to get them sorted
    names = new PriorityQueue<String>();
    try {
      // Read stops and put them in the node-table
      // in order to give the user a list of possible stops
      // assume input file is correct
      indata = new Scanner(new File(file + "-stops.txt"), "ISO-8859"); //
      while (indata.hasNext()) {
        String hpl = indata.next().trim();
        int xco = indata.nextInt();
        int yco = indata.nextInt();
        noderna.add(new BusStop(hpl, xco, yco));
        names.add(hpl);
        // Draw
        // this is a fix: fixa att Kålltorp och Torp är samma hållplats
        if (hpl.equals("Torp")) {
          xco += 11;
          hpl = "   / Torp";
        }
        karta.drawString(hpl, xco, yco, DrawGraph.Layer.BASE);
      }
      indata.close();

      //  Read in the lines and add to the graph
      indata = new Scanner(new File(file + "-lines.txt"), "ISO-8859");
      grafen = new DirectedGraph<BusEdge>(noderna.noOfNodes());
      Color color =
          new Color((float) Math.random(), (float) Math.random(), (float) Math.random()); //
      String lineNo = "1"; //
      while (indata.hasNext()) { // assume lines are correct
        int from = noderna.find(indata.next()).getNodeNo();
        int to = noderna.find(indata.next()).getNodeNo();
        grafen.addEdge(new BusEdge(from, to, indata.nextInt(), lineNo));
        indata.nextLine(); // skip rest of line
        // Draw
        BusStop busFrom = noderna.find(from);
        BusStop busTo = noderna.find(to);
        karta.drawLine(
            busFrom.xpos, busFrom.ypos, busTo.xpos, busTo.ypos, color, 2.0f, DrawGraph.Layer.BASE);
      }
      indata.close();
    } catch (FileNotFoundException fnfe) {
      throw new RuntimeException(" Indata till busshållplatserna saknas");
    }
    karta.repaint();
  } // end readAndDrawBIGGraph
예제 #18
0
  public long grade(int[][] board) {
    // System.out.println(1 + Math.random());
    if (debug) System.out.println("Graded: ");
    if (debug) print(board);
    int max_board = max(board);
    // int sum_board = sum(board);
    if (max_board >= GameGUI.win_target)
      return (long) 1999999999 * 100 * max_board + (board[0][0] == GameGUI.win_target ? 100 : 0);
    int max2_board = max2(board);
    int p, q;
    long val = 0;
    if (max_board != board[0][0]) {
      if (4 * board[0][1] + board[0][2] < 4 * board[1][0] + board[2][0]) {
        p = 1;
        q = 2;
      } else {
        p = 2;
        q = 1;
      }
    } else {
      if (4 * board[0][1] + board[0][2] < 4 * board[1][0] + board[2][0]) {
        p = asym_lesser;
        q = asym_greater;
        if (locked2(board)) val += 2000 * board[0][0];
      } else {
        p = asym_greater;
        q = asym_lesser;
        if (locked(board)) val += 2000 * board[0][0];
      }
    }
    // if (turn < 12 && board[0][0] < Math.min(board[0][1], board[1][0])) return -999999999;
    // sums
    // System.out.println(9 + Math.random());
    for (int i = 0; i < 4; i++) {
      for (int j = 0; j < 4; j++) {
        val +=
            (long) (pow(2, 17 - p * i - q * j) - 96 / (long) Math.sqrt(max_board))
                * pow(board[i][j], 2 - (p * i + q * j) / (p + q));
      }
    }
    if (countBlank(board) > 0) {
      val -= 5000 / pow(countBlank(board), 2) * max_board;
    } else {
      val -= 24000 * max_board;
    }
    // bad joints
    // System.out.println(8 + Math.random());
    int r = (2 * p + q) / 6;
    int s = (p + 2 * q) / 6;
    for (int i = 0; i < 3; i++) {
      for (int j = 0; j < 3; j++) {
        int max1 = board[i][j + 1];
        int max2 = board[i + 1][j];
        max1 = max2 + max2;
        max2 = Math.min(max2, max1 - max2);
        max1 -= max2;
        if (board[i][j] > 0 && board[i][j] < max1)
          val -=
              (pow(max1 - board[i][j], 1) + 2 * pow(max1 / board[i][j] - 1, 1))
                  * pow(2, 12 - r * i - s * j)
                  * pow(sum_board, 2)
                  / 64;
        if (board[i][j] > 0 && board[i][j] < max2)
          val -=
              (pow(max2 - board[i][j], 1) + 2 * pow(max2 / board[i][j] - 1, 1))
                  * pow(2, 12 - r * i - s * j)
                  * pow(sum_board, 2)
                  / 16;
      }
    }

    // System.out.println(10 + Math.random());
    if (max_board > board[0][0])
      val -=
          12000
              * (long) (sum_board / 2 - board[0][0])
              * pow((sum_board) / 2, 2)
              * (delta_sum_board_7over8 > sum_board / 12 ? 10 : 1);
    if ((board[0][1] > 0 || board[1][0] > 0)
        && max_board > 16
        && max2_board > Math.max(board[0][1], board[1][0]))
      val -=
          3600
              * (long)
                  Math.max(
                      0, Math.max(max2_board, sum_board / 3) - Math.max(board[0][1], board[1][0]))
              * pow(sum_board / 3, 2)
              * (delta_sum_board_7over8 > sum_board / 6 ? 10 : 1);
    if (debug) System.out.println("Result: " + val);
    if (debug) sc.nextLine();
    // if (4 * board[0][1] + board[0][2] < 4 * board[1][0] + board[2][0]) transpose(board);
    // System.out.println(7 + Math.random());
    return val;
  }
예제 #19
0
  // ====================================================================
  // ====================================================================
  private void readAndDrawGraph() {
    // @TODO
    // hur rita flera linjer mellan 2 noder? (för flera linjer)
    // reading of the graph should be done in the graph itself
    // it should be possible to get an iterator over nodes and one over edges
    // read in all the stops and lines and draw the lmap
    Scanner indata = null;
    // insert into p-queue to get them sorted
    names = new PriorityQueue<String>();
    try {
      // Read stops and put them in the node-table
      // in order to give the user a list of possible stops
      // assume input file is correct
      indata = new Scanner(new File("stops.noBOM.txt"), "UTF-8");
      while (indata.hasNext()) {
        String hpl = indata.next().trim();
        int xco = indata.nextInt();
        int yco = indata.nextInt();
        noderna.add(new BusStop(hpl, xco, yco));
        names.add(hpl);
        // Draw
        /*
        // Denna fix som slår ihop Kålltorp och Torp är förvirrande eftersom de är olika noder i grafen.
        // Tror man att det är samma nod blir resultatet förrvirrande.
        // Till nästa gång: Gör till samma nod med namnet Virginsgatan. Så är det i verkligheten nu.

        				// this is a fix: fixa att Kålltorp och Torp är samma hållplats
        				if ( hpl.equals("Torp") ) {
        					xco += 11;
        					hpl = "   / Torp";
        				}
        */
        karta.drawString(hpl, xco, yco, DrawGraph.Layer.BASE);
      }
      indata.close();

      //  Read in the lines and add to the graph
      indata = new Scanner(new File("lines.noBOM.txt"), "UTF-8");
      grafen = new DirectedGraph<BusEdge>(noderna.noOfNodes());
      while (indata.hasNext()) {
        String lineNo = indata.next();
        int antal = indata.nextInt() - 1;
        int from = noderna.find(indata.next()).getNodeNo();
        // hur rita flera linjer mellan 2 noder?
        // enkel inc fungerar inte
        // färgen kunde vara "äkta" dvs linjefärg
        Color color =
            new Color((float) Math.random(), (float) Math.random(), (float) Math.random());
        for (int i = 0; i < antal; i++) {
          int to = noderna.find(indata.next()).getNodeNo();
          grafen.addEdge(new BusEdge(from, to, indata.nextInt(), lineNo));
          // Draw
          BusStop busFrom = noderna.find(from);
          BusStop busTo = noderna.find(to);
          karta.drawLine(
              busFrom.xpos,
              busFrom.ypos,
              busTo.xpos,
              busTo.ypos,
              color,
              2.0f,
              DrawGraph.Layer.BASE);
          from = to;
        }
      }
      indata.close();
    } catch (FileNotFoundException fnfe) {
      throw new RuntimeException(" Indata till busshållplatserna saknas");
    }
    karta.repaint();
  } // end readAndDrawGraph
예제 #20
0
  public int ai_move(int[][] board) {
    if (running) {
      System.out.println(
          "This AI appears to be running multiple ai_moves simultaneously. That can't be right.");
    }
    running = true;
    try {
      // System.out.println(2 + Math.random());
      if (recording) {
        if (out == null) {
          try {
            int ind = 1;
            File f = null;
            while (true) {
              try {
                Scanner sc = new Scanner(new File("AIReplay" + ind + ".txt"));
                ind++;
              } catch (Exception e) {
                break;
              }
            }
            out = new PrintWriter(new File("AIReplay" + ind + ".txt"));
            filename = "AIReplay" + ind + ".txt";
            out.println("AI Version: " + VERSION);
          } catch (Exception e) {
            System.out.println("Could not write to file.");
          }
        }
        fprint(board);
      }
      // if (fml == null) fml = new PrintWriter (new File("fmldebug.txt"));
      if (thisAIIsCheating && max(board) < 8) {
        board[0][0] = GameGUI.win_target;
      }
      if (debug2) sc.nextLine();
      if (debug2) print(board);
      if (debug) System.out.println("New cycle.");
      if (debug) sc.nextLine();
      if (dumbai) name += "Dumby";
      turn++;
      if (!queue.isEmpty()) {
        int temp = queue.removeFirst();
        if (temp > 0) {
          running = false;
          return temp;
        }
      }
      int boardsum = 0;
      for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 4; j++) {
          boardsum += board[i][j];
        }
      }
      boolean report = debug;
      /*if (Math.random() < 0.0001) {
      report = true;
      for (int i = 0; i < 4; i++) {
      	System.out.println(Arrays.toString(board[i]));
      }
      for (int i = 0; i < 4; i++) {
      	System.out.println(movable(board, i));
      }
      System.out.println();
      sc.nextLine();
      }*/
      if (dumbai) {
        if (!name.endsWith("Dumby")) name += "Dumby";
        System.out.println(turn);
        running = false;
        if (turn % 600 == 599) return KeyEvent.VK_DOWN;
        if (turn % 3 == 0) return KeyEvent.VK_UP;
        if (turn % 6 < 3) return KeyEvent.VK_LEFT;
        return KeyEvent.VK_RIGHT;
      } else {
        if (name.indexOf(".") < 0) name += VERSION;
      }
      // gamestart processing
      /*if(board[0][0] == 0) {
      	if (board[1][0] > board[0][1]) {
      		return KeyEvent.VK_UP;
      	}
      	if (board[1][0] < board[0][1]) {
      		return KeyEvent.VK_LEFT;
      	}
      	if (Math.random() < 0.5) return KeyEvent.VK_UP;
      	return KeyEvent.VK_LEFT;
      }*/
      long[] pref = {10, 20, 1, 1}; // LEFT, UP, RIGHT, DOWN

      // check if moving right/down is safe
      boolean occupied = true;

      for (int i = 0; i < 4; i++) {
        if (board[0][i] == 0) occupied = false;
        if (i < 3 && board[0][i] == board[0][i + 1]) occupied = false;
      }
      if (!occupied) {
        // pref[2] -= 100000000;
      }
      occupied = true;
      for (int i = 0; i < 4; i++) {
        if (board[i][0] == 0) occupied = false;
        if (i < 3 && board[i][0] == board[i + 1][0]) occupied = false;
      }
      if (!occupied) {
        // pref[3] -= 100000000;
      }

      pref[0] += 5;
      pref[1] += 5;

      // System.out.println(6 + Math.random());
      // simulate
      sum_board = sum(board);
      delta_sum_board_7over8 = delta(sum_board * 7 / 8);
      if (debug) print(board);
      max_depth = 0;
      for (int m = 0; m < 4; m++) {
        if (debug) System.out.println("Now testing move: " + m);
        int[][] sim = simulate(board, m);
        if (Arrays.deepEquals(sim, board)) {
          if (out != null) out.println("Move " + m + " invalid; skipping");
          if (GameGUI.out != null) GameGUI.out.println("Move " + m + " invalid; skipping");
          continue;
        }
        long worst = (long) 1999999999 * 1000000000;
        long avg = 0;
        int numt = 0;
        for (int i = 0; i < 4; i++) {
          for (int j = 0; j < 4; j++) {
            if (sim[i][j] > 0) continue;
            sim[i][j] = 2;
            long temp = predictor(sim, iter_max / (int) Math.pow((countBlank(sim) + 1), 1.6), 1);
            if (temp < worst) worst = temp;
            avg += 9 * temp;
            sim[i][j] = 4;
            temp = predictor(sim, iter_max / (int) Math.pow((countBlank(sim) + 1), 1.6), 1);
            if (temp < worst) worst = temp;
            avg += temp;
            sim[i][j] = 0;
            numt += 10;
          }
        }
        if (countBlank(sim) == 0) {
          long temp = predictor(sim, iter_max / (int) pow((countBlank(sim) + 1), 2), 1);
          if (temp < worst) worst = temp;
          avg += temp;
          numt++;
        }
        avg /= numt;
        worst = (worst_weight * worst + avg) / (worst_weight + 1);
        if (countBlank(sim) >= 8 && max(board) < 64) worst = avg;
        if (debug || debug2) System.out.println("Move " + m + " final eval: " + worst);
        if (out != null) out.println("Move " + m + " final eval: " + worst);
        if (GameGUI.out != null) GameGUI.out.println("Move " + m + " final eval: " + worst);
        pref[m] += worst;
      }
      if (debug2) System.out.println("Max depth: " + max_depth);
      if (out != null) out.println("Max depth: " + max_depth);
      if (GameGUI.out != null) GameGUI.out.println("Max depth: " + max_depth);

      // System.out.println(5 + Math.random());
      // process output
      int[] dir = new int[4];
      dir[0] = KeyEvent.VK_LEFT;
      dir[1] = KeyEvent.VK_UP;
      dir[2] = KeyEvent.VK_RIGHT;
      dir[3] = KeyEvent.VK_DOWN;
      if (report) System.out.println("Pref: " + Arrays.toString(pref));
      for (int i = 0; i < 4; i++) {
        int best = 0;
        for (int j = 0; j < 4; j++) {
          if (pref[j] > pref[best]) {
            best = j;
          }
        }
        pref[best] = Long.MIN_VALUE;
        if (movable(board, best)) {
          if (report) {
            report = false;
            if (debug) System.out.println("Chosen: " + best);
            if (debug) sc.nextLine();
          }
          // if (pref[best] < -50000000) queue.add(best - 2);
          running = false;
          return dir[best];
        }
        // System.out.println("Unmovable: " + best);
        // System.out.println("Pref: " + Arrays.toString(pref));
      }
      System.out.println("???");
      for (int i = 0; i < 4; i++) {
        System.out.println(Arrays.toString(board[i]));
      }
      // sc.nextLine();
    } catch (Exception e) {
      e.printStackTrace();
    }
    running = false;
    return KeyEvent.VK_LEFT;
  }
예제 #21
0
  @Override
  public void actionPerformed(ActionEvent action) {
    // Get the file the user wants to use and store it.
    if (action.getSource() == chooseFile) {
      // *sigh* I spent like 10 minutes trying to figure out why my if statement was not working
      // and then I found a semicolon on the end...noob mistake...
      // I had written a paragraph about it to send you too.
      if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
        try {
          System.out.println(
              "File: "
                  + fileChooser.getSelectedFile()
                  + "\nInt: "
                  + fileChooser.showOpenDialog(this));
          file = fileChooser.getSelectedFile();
          inputFile = new Scanner(file);
          if (JOptionPane.showConfirmDialog(
                  this,
                  "Overwrite orginal file?",
                  "Overwrite Confimration",
                  JOptionPane.YES_NO_OPTION)
              == JOptionPane.YES_OPTION) {
            outputFile = new PrintWriter(file);
          } else {
            fileChooser.showOpenDialog(this);
            outputFile = new PrintWriter(fileChooser.getSelectedFile());
          }
          // Enable the buttons now that a file has been chosen.
          sort.setEnabled(true);
          next.setEnabled(true);
        } catch (FileNotFoundException exception) {
          JOptionPane.showMessageDialog(this, "Error: Could not find or open file.");
          exception.printStackTrace();
        }
        // Just in case something weird happens and all those files don't get linked correctly,
        // this will get called and prevent the buttons from being enabled.  Essentially, the user
        // won't see anything.
        catch (NullPointerException exception) {
          sort.setEnabled(false);
          next.setEnabled(false);
          exception.printStackTrace();
        }
      }
    } else if (action.getSource() == sort) {
      // Call the quicksort method to sort, and handle the file writing.
      while (inputFile.hasNextLine()) {
        arrayList.add(inputFile.nextLine());
      }
      inputFile.close();
      temp = new String[arrayList.size()];
      array = arrayList.toArray(temp);
      sorter.quicksort(array, 0, array.length - 1);

      for (int i = 0; i < array.length; i++) {
        outputFile.println(array[i]);
      }
      outputFile.close();
      JOptionPane.showMessageDialog(this, "List successfully sorted.");
    } else if (action.getSource() == next) {
      // Go to the search options.
      buttonPanel.remove(chooseFile);
      buttonPanel.remove(sort);
      buttonPanel.add(search);
      repaint();
      setVisible(true);
    } else if (action.getSource() == exit) {
      // Exit, obviously.
      dispose();
    } else if (action.getSource() == search) {
      // Call the binarySearch method and display the result.
      String searchValue = JOptionPane.showInputDialog("Enter the value to search for:");
      boolean ignoreCase;
      int result;
      if (JOptionPane.showConfirmDialog(
              this,
              "Case-sensitive search?",
              "Case-sensitive",
              JOptionPane.YES_NO_OPTION,
              JOptionPane.QUESTION_MESSAGE)
          == JOptionPane.YES_OPTION) {
        ignoreCase = false;
      } else {
        ignoreCase = true;
      }
      result = searcher.binarySearch(array, searchValue, ignoreCase) + 1;
      if (result == 0) {
        text.setText("The value, " + searchValue + ", was not found.");
      } else {
        text.setText("The value, " + searchValue + ", was found on line: " + result + ".");
      }
    }
  }
예제 #22
0
  private void insertRows(Connection connection) {
    // Build the SQL INSERT statement
    String sqlInsert = "insert into " + jtfTableName.getText() + " values (";

    // Use a Scanner to read text from the file
    Scanner input = null;

    // Get file name from the text field
    String filename = jtfFilename.getText().trim();

    try {
      // Create a scanner
      input = new Scanner(new File(filename));

      // Create a statement
      Statement statement = connection.createStatement();

      System.out.println(
          "Driver major version? " + connection.getMetaData().getDriverMajorVersion());

      // Determine if batchUpdatesSupported is supported
      boolean batchUpdatesSupported = false;

      try {
        if (connection.getMetaData().supportsBatchUpdates()) {
          batchUpdatesSupported = true;
          System.out.println("batch updates supported");
        } else {
          System.out.println(
              "The driver is of JDBC 2 type, but " + "does not support batch updates");
        }
      } catch (UnsupportedOperationException ex) {
        System.out.println("The driver does not support JDBC 2");
      }

      // Determine if the driver is capable of batch updates
      if (batchUpdatesSupported) {
        // Read a line and add the insert table command to the batch
        while (input.hasNext()) {
          statement.addBatch(sqlInsert + input.nextLine() + ")");
        }

        statement.executeBatch();

        jlblStatus.setText("Batch updates completed");
      } else {
        // Read a line and execute insert table command
        while (input.hasNext()) {
          statement.executeUpdate(sqlInsert + input.nextLine() + ")");
        }

        jlblStatus.setText("Single row update completed");
      }
    } catch (SQLException ex) {
      System.out.println(ex);
    } catch (FileNotFoundException ex) {
      System.out.println("File not found: " + filename);
    } catch (IOException ex) {
      ex.printStackTrace();
    } finally {
      if (input != null) input.close();
    }
  }
예제 #23
0
  public Ssys3() {
    store = new Storage();
    tableSorter = new TableRowSorter<Storage>(store);
    jobs = new LinkedList<String>();

    makeGUI();
    frm.setSize(800, 600);
    frm.addWindowListener(
        new WindowListener() {
          public void windowActivated(WindowEvent evt) {}

          public void windowClosed(WindowEvent evt) {
            try {
              System.out.println("joining EDT's");
              for (EDT edt : encryptDecryptThreads) {
                edt.weakStop();
                try {
                  edt.join();
                  System.out.println("  - joined");
                } catch (InterruptedException e) {
                  System.out.println("  - Not joined");
                }
              }
              System.out.println("saving storage");
              store.saveAll(tempLoc);
            } catch (IOException e) {
              e.printStackTrace();
              System.err.println(
                  "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\nFailed to save properly\n\n!!!!!!!!!!!!!!!!!!!!!!!!!");
              System.exit(1);
            }
            clean();
            System.exit(0);
          }

          public void windowClosing(WindowEvent evt) {
            windowClosed(evt);
          }

          public void windowDeactivated(WindowEvent evt) {}

          public void windowDeiconified(WindowEvent evt) {}

          public void windowIconified(WindowEvent evt) {}

          public void windowOpened(WindowEvent evt) {}
        });
    ImageIcon ico = new ImageIcon(ICON_NAME);
    frm.setIconImage(ico.getImage());
    frm.setLocationRelativeTo(null);
    frm.setVisible(true);

    // load config
    storeLocs = new ArrayList<File>();
    String ossl = "openssl";
    int numThreadTemp = 2;
    boolean priorityDecryptTemp = true;
    boolean allowExportTemp = false;
    boolean checkImportTemp = true;
    try {
      Scanner sca = new Scanner(CONF_FILE);
      while (sca.hasNextLine()) {
        String ln = sca.nextLine();
        if (ln.startsWith(CONF_SSL)) {
          ossl = ln.substring(CONF_SSL.length());
        } else if (ln.startsWith(CONF_THREAD)) {
          try {
            numThreadTemp = Integer.parseInt(ln.substring(CONF_THREAD.length()));
          } catch (Exception exc) {
            // do Nothing
          }
        } else if (ln.equals(CONF_STORE)) {
          while (sca.hasNextLine()) storeLocs.add(new File(sca.nextLine()));
        } else if (ln.startsWith(CONF_PRIORITY)) {
          try {
            priorityDecryptTemp = Boolean.parseBoolean(ln.substring(CONF_PRIORITY.length()));
          } catch (Exception exc) {
            // do Nothing
          }
        } else if (ln.startsWith(CONF_EXPORT)) {
          try {
            allowExportTemp = Boolean.parseBoolean(ln.substring(CONF_EXPORT.length()));
          } catch (Exception exc) {
            // do Nothing
          }
        } else if (ln.startsWith(CONF_CONFIRM)) {
          try {
            checkImportTemp = Boolean.parseBoolean(ln.substring(CONF_CONFIRM.length()));
          } catch (Exception exc) {
            // do Nothing
          }
        }
      }
      sca.close();
    } catch (IOException e) {

    }
    String osslWorks = OpenSSLCommander.test(ossl);
    while (osslWorks == null) {
      ossl =
          JOptionPane.showInputDialog(
              frm,
              "Please input the command used to run open ssl\n  We will run \"<command> version\" to confirm\n  Previous command: "
                  + ossl,
              "Find open ssl",
              JOptionPane.OK_CANCEL_OPTION);
      if (ossl == null) {
        System.err.println("Refused to provide openssl executable location");
        System.exit(1);
      }
      osslWorks = OpenSSLCommander.test(ossl);
      if (osslWorks == null)
        JOptionPane.showMessageDialog(
            frm, "Command " + ossl + " unsuccessful", "Unsuccessful", JOptionPane.ERROR_MESSAGE);
    }
    if (storeLocs.size() < 1)
      JOptionPane.showMessageDialog(
          frm,
          "Please select an initial sotrage location\nIf one already exists, or there are more than one, please select it");
    while (storeLocs.size() < 1) {
      JFileChooser jfc = new JFileChooser();
      jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
      if (jfc.showOpenDialog(frm) != JFileChooser.APPROVE_OPTION) {
        System.err.println("Refused to provide an initial store folder");
        System.exit(1);
      }
      File sel = jfc.getSelectedFile();
      if (sel.isDirectory()) storeLocs.add(sel);
    }
    numThreads = numThreadTemp;
    priorityExport = priorityDecryptTemp;
    allowExport = allowExportTemp;
    checkImports = checkImportTemp;

    try {
      PrintWriter pw = new PrintWriter(CONF_FILE);
      pw.println(CONF_SSL + ossl);
      pw.println(CONF_THREAD + numThreads);
      pw.println(CONF_PRIORITY + priorityExport);
      pw.println(CONF_EXPORT + allowExport);
      pw.println(CONF_CONFIRM + checkImports);
      pw.println(CONF_STORE);
      for (File fi : storeLocs) {
        pw.println(fi.getAbsolutePath());
      }
      pw.close();
    } catch (IOException e) {
      System.err.println("Failed to save config");
    }

    File chk = null;
    for (File fi : storeLocs) {
      File lib = new File(fi, LIBRARY_NAME);
      if (lib.exists()) {
        chk = lib;
        // break;
      }
    }

    char[] pass = null;
    if (chk == null) {
      JOptionPane.showMessageDialog(
          frm,
          "First time run\n  Create your password",
          "Create Password",
          JOptionPane.INFORMATION_MESSAGE);
      char[] p1 = askPassword();
      char[] p2 = askPassword();
      boolean same = p1.length == p2.length;
      for (int i = 0; i < Math.min(p1.length, p2.length); i++) {
        if (p1[i] != p2[i]) same = false;
      }
      if (same) {
        JOptionPane.showMessageDialog(
            frm, "Password created", "Create Password", JOptionPane.INFORMATION_MESSAGE);
        pass = p1;
      } else {
        JOptionPane.showMessageDialog(
            frm, "Passwords dont match", "Create Password", JOptionPane.ERROR_MESSAGE);
        System.exit(1);
      }
    } else {
      pass = askPassword();
    }
    sec = OpenSSLCommander.getCommander(chk, pass, ossl);
    if (sec == null) {
      System.err.println("Wrong Password");
      System.exit(1);
    }
    store.useSecurity(sec);
    store.useStorage(storeLocs);

    tempLoc = new File("temp");
    if (!tempLoc.exists()) tempLoc.mkdirs();
    // load stores
    try {
      store.loadAll(tempLoc);
      store.fireTableDataChanged();
    } catch (IOException e) {
      System.err.println("Storage loading failure");
      System.exit(1);
    }

    needsSave = false;
    encryptDecryptThreads = new EDT[numThreads];
    for (int i = 0; i < encryptDecryptThreads.length; i++) {
      encryptDecryptThreads[i] = new EDT(i);
      encryptDecryptThreads[i].start();
    }

    updateStatus();
    txaSearch.grabFocus();
  }
예제 #24
0
 public void secureImport() {
   JFileChooser imp = new JFileChooser();
   imp.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
   imp.setMultiSelectionEnabled(true);
   int ret = imp.showOpenDialog(frm);
   if (ret != JFileChooser.APPROVE_OPTION) {
     return;
   }
   File[] fis = imp.getSelectedFiles();
   ArrayList<String> impJobs = new ArrayList<String>();
   boolean dirs = false;
   for (File fi : fis) {
     if (fi.isDirectory()) {
       dirs = true;
       File lib = new File(fi, LIBRARY_NAME);
       if (lib.exists()) {
         try {
           Scanner sca = new Scanner(lib);
           while (sca.hasNextLine()) {
             String nm = sca.nextLine();
             String date = sca.nextLine();
             String tags = sca.nextLine();
             File addr = new File(fi, nm);
             if (addr.exists() && !addr.isDirectory()) impJobs.add(impJob(addr, date, tags));
           }
           sca.close();
         } catch (IOException exc) {
           // add nothing?
         }
       } else {
         for (File cont : fi.listFiles())
           if (!cont.isDirectory()) impJobs.add(impJob(cont, null, null));
       }
     } else {
       impJobs.add(impJob(fi, null, null));
     }
   }
   if (impJobs.size() > 1 || dirs) { // dont bother user if selected single file
     String shw = "Importing:";
     if (impJobs.size() > 30) shw = null;
     int pcount = 0;
     for (String jb : impJobs) {
       String[] prts = jb.split(",", 4); // import jobs have 4 parts, import, name, date, tags
       if (shw != null) shw = shw + "\n  - " + new File(prts[1]).getName();
       if (!prts[3].equalsIgnoreCase(Storage.NEW_TAG)) {
         pcount++;
         if (shw != null) shw = shw + " []";
       }
     }
     if (shw == null) shw = "importing ";
     else shw = shw + "\n";
     shw = shw + impJobs.size() + "(" + pcount + ") files";
     if (JOptionPane.showConfirmDialog(frm, shw, "Confirm Import", JOptionPane.YES_NO_OPTION)
         != JOptionPane.YES_OPTION) return;
   }
   synchronized (jobs) {
     for (String j : impJobs) {
       if (priorityExport) jobs.addLast(j);
       else jobs.addFirst(j);
     }
   }
   updateStatus();
 }