/** constructor */
 public DanceQueuePanel() {
   //	flow layout
   setLayout(new FlowLayout());
   //	uses buffer	to	draw arrows	based	on	queues in an array
   myImage = new BufferedImage(600, 600, BufferedImage.TYPE_INT_RGB);
   myBuffer = myImage.getGraphics();
   // uses timer to queue buffer changes
   time = 0;
   timer = new Timer(5, new Listener());
   timer.start();
   setFocusable(true);
   // picks instructions	based	on	song & level
   if (Danceoff.getSong() == -1 && Danceoff.getDifficulty() == 0) {
     arrows = new Arrow[] {new UpArrow(1000), new DownArrow(2000), new LeftArrow(3000)};
   }
   // setBorder(BorderFactory.createTitledBorder(BorderFactory.createLineBorder(Color.BLACK, 3),
   //	"DanceQueuePanel"));
   // load images for arrows
   rightArrowImg = null;
   leftArrowImg = null;
   upArrowImg = null;
   downArrowImg = null;
   try {
     rightArrowImg = ImageIO.read(new File("arrowB right.png"));
     leftArrowImg = ImageIO.read(new File("arrowB left.png"));
     upArrowImg = ImageIO.read(new File("arrowB up copy.png"));
     downArrowImg = ImageIO.read(new File("arrowB down.png"));
   } catch (IOException e) {
     warn("YOU FAIL", e);
     System.exit(2);
   }
 }
Example #2
0
  /**
   * Loads the tileset defined in the constructor into a JPanel which it then returns. Makes no
   * assumptions about height or width, which means it needs to read an extra 64 tiles at worst (32
   * down to check height and 32 across for width), since the maximum height/width is 32 tiles.
   */
  public JPanel loadTileset() {
    int height = MAX_TILESET_SIZE;
    int width = MAX_TILESET_SIZE;

    boolean maxHeight = false;
    boolean maxWidth = false;

    // find width
    int j = 0;
    while (!maxWidth) {
      try {
        File f = new File(tileDir + "/" + j + "_" + 0 + ".png");
        ImageIO.read(f);
      } catch (IOException e) {
        width = j;
        maxWidth = true;
      }
      j += TILE_SIZE;
    }

    // find height
    int i = 0;
    while (!maxHeight) {
      try {
        File f = new File(tileDir + "/" + 0 + "_" + i + ".png");
        ImageIO.read(f);
      } catch (IOException e) {
        height = i;
        maxHeight = true;
      }
      i += TILE_SIZE;
    }

    JPanel tileDisplay = new JPanel();
    tileDisplay.setLayout(new GridLayout(height / TILE_SIZE, width / TILE_SIZE));
    tileDisplay.setMinimumSize(new Dimension(width, height));
    tileDisplay.setPreferredSize(new Dimension(width, height));
    tileDisplay.setMaximumSize(new Dimension(width, height));

    for (i = 0; i < height; i += TILE_SIZE) {
      for (j = 0; j < width; j += TILE_SIZE) {
        String fPath = tileDir + "/" + j + "_" + i;
        try {
          int[] mov = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};

          Image icon = getTile(tileDir, j, i, 1);
          Tile tile =
              new Tile(new ImageIcon(icon), "palette", 0, 0, mov, "none", false, "" + j + "_" + i);
          tile.addMouseListener(new PaletteButtonListener());
          tile.setMaximumSize(new Dimension(TILE_SIZE, TILE_SIZE));
          tile.setPreferredSize(new Dimension(TILE_SIZE, TILE_SIZE));
          tile.setMinimumSize(new Dimension(TILE_SIZE, TILE_SIZE));
          tileDisplay.add(tile);
        } catch (IOException e) {
        }
      }
    }
    return tileDisplay;
  }
Example #3
0
 /**
  * Takes a filepath to a tileset folder, x, y coordinates and a scale and returns the desired
  * tile.
  */
 public static Image getTile(String filepath, int x, int y, int scale) throws IOException {
   // System.out.println(filepath+"/"+x+"_"+y);
   try {
     return scaleImage(ImageIO.read(new File(filepath + "/" + x + "_" + y + ".png")), scale);
   } catch (IOException e) {
     return scaleImage(ImageIO.read(new File(filepath + "/" + x + "_" + y)), scale);
   }
 }
Example #4
0
 public PanImage1() {
   try {
     image = ImageIO.read(new File("WALLPAPER02.jpg"));
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Example #5
0
  public void readImg(String in) {
    try {
      character = ImageIO.read(new File(in));
    } catch (IOException e) {

    }
  }
Example #6
0
 /**
  * Returns the specified image.
  *
  * @param url image url
  * @return image
  */
 public static Image get(final URL url) {
   try {
     return ImageIO.read(url);
   } catch (final IOException ex) {
     throw Util.notExpected(ex);
   }
 }
Example #7
0
 public void init() throws Exception {
   table = ImageIO.read(new File("image/board.jpg"));
   black = ImageIO.read(new File("image/black.gif"));
   white = ImageIO.read(new File("image/white.gif"));
   selected = ImageIO.read(new File("image/selected.gif"));
   // 把每个元素赋为"╋",用于在控制台画出棋盘
   for (int i = 0; i < BOARD_SIZE; i++) {
     for (int j = 0; j < BOARD_SIZE; j++) {
       board[i][j] = "╋";
     }
   }
   chessBoard.setPreferredSize(new Dimension(TABLE_WIDTH, TABLE_HETGHT));
   chessBoard.addMouseListener(
       new MouseAdapter() {
         public void mouseClicked(MouseEvent e) {
           // 将用户鼠标事件的座标转换成棋子数组的座标。
           int xPos = (int) ((e.getX() - X_OFFSET) / RATE);
           int yPos = (int) ((e.getY() - Y_OFFSET) / RATE);
           board[xPos][yPos] = "●";
           /*
           电脑随机生成2个整数,作为电脑下棋的座标,赋给board数组。
           还涉及:
           1.如果下棋的点已经棋子,不能重复下棋。
           2.每次下棋后,需要扫描谁赢了
           */
           chessBoard.repaint();
         }
         // 当鼠标退出棋盘区后,复位选中点座标
         public void mouseExited(MouseEvent e) {
           selectedX = -1;
           selectedY = -1;
           chessBoard.repaint();
         }
       });
   chessBoard.addMouseMotionListener(
       new MouseMotionAdapter() {
         // 当鼠标移动时,改变选中点的座标
         public void mouseMoved(MouseEvent e) {
           selectedX = (e.getX() - X_OFFSET) / RATE;
           selectedY = (e.getY() - Y_OFFSET) / RATE;
           chessBoard.repaint();
         }
       });
   f.add(chessBoard);
   f.pack();
   f.setVisible(true);
 }
Example #8
0
  public PanImage2() {
    try {
      image2 = ImageIO.read(new File("Initial.D.full.501729.jpg"));

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Example #9
0
  public PanImage3() {
    try {
      image3 = ImageIO.read(new File("sleeping_dogs_2012_video_game-wallpaper-1024x768.jpg"));

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Example #10
0
  public void initialize() {

    // openLevelFile images:
    try {
      boxSpriteSheet = ImageIO.read(new File("ItemContainer.png"));
      coinSpriteSheet = ImageIO.read(new File("Coin.png"));
    } catch (Exception e) {
    }

    if (openLevelFile == false) {
      try {
        loadLevel(initLevel);
      } catch (Exception e) {
        System.out.println(e);
      }
    } else {
      loadLevel(FileOpenDialog("Open ..."));
    }

    // create tile layer:
    renderTileLayer();

    // create bg layer:
    backgroundLayer = new VolatileImage[backgroundImage.length];

    // render layer:
    for (int i = 0; i < backgroundImage.length; i++) {
      renderBackgroundLayer(0);
      renderBackgroundLayer(1);
    }

    // create hardware accellerated rendering layer:
    renderImage =
        this.getGraphicsConfiguration()
            .createCompatibleVolatileImage(
                loadedLevel.getWidth() * 16,
                loadedLevel.getHeight() * 16,
                Transparency.TRANSLUCENT);
    Graphics2D g2d = renderImage.createGraphics();
    g2d.setComposite(AlphaComposite.Src);

    // Clear the image.
    g2d.setColor(new Color(0, 0, 0, 0));
    g2d.fillRect(0, 0, renderImage.getWidth(), renderImage.getHeight());
    g2d.setBackground(new Color(0, 0, 0, 0));
  }
 public void paintComponent(Graphics g) {
   if (paint) {
     try {
       Rectangle vis = getVisibleRect();
       File fi = ImageLoader.getFile("images/inventoryback.png");
       BufferedImage bg = ImageIO.read(fi.toURL());
       g.drawImage(bg, vis.x, vis.y, null);
     } catch (Exception e) {
     }
   }
 }
  public BufferedImage getImage(String Direct, String FName) {
    // JOptionPane.showMessageDialog(null, "GameCharacter");
    try {
      BufferedImage bg = ImageIO.read(getClass().getResource(Direct + FName));
      return bg;

    } catch (Exception e) {
      JOptionPane.showMessageDialog(null, getClass().toString());
    }
    return null;
  }
Example #13
0
  /**
   * Loads an image from a given image identifier.
   *
   * @param imageID The identifier of the image.
   * @return The image for the given identifier.
   */
  public static ImageIcon getImage(String imageID) {
    BufferedImage image = null;

    String path = IMAGE_RESOURCE_BUNDLE.getString(imageID);

    try {
      image = ImageIO.read(Resources.class.getClassLoader().getResourceAsStream(path));
    } catch (IOException e) {
      log.error("Failed to load image:" + path, e);
    }

    return new ImageIcon(image);
  }
    Sidebar() {
      super(BoxLayout.Y_AXIS);

      try {
        back =
            ImageIO.read(
                ClassLoader.getSystemClassLoader()
                    .getResource("org/madeirahs/editor/ui/help_sidebar.png"));
        scaleImage();
        setPreferredSize(new Dimension(back.getWidth(), back.getHeight()));
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
Example #15
0
 public MainPanel() {
   super(new BorderLayout());
   BufferedImage bi = null;
   try {
     bi = ImageIO.read(getClass().getResource("test.jpg"));
   } catch (IOException ioe) {
     ioe.printStackTrace();
   }
   bufferedImage = bi;
   List<AbstractAction> list =
       Arrays.asList(
           new AbstractAction("NONE") {
             @Override
             public void actionPerformed(ActionEvent e) {
               mode = Flip.NONE;
               repaint();
             }
           },
           new AbstractAction("VERTICAL") {
             @Override
             public void actionPerformed(ActionEvent e) {
               mode = Flip.VERTICAL;
               repaint();
             }
           },
           new AbstractAction("HORIZONTAL") {
             @Override
             public void actionPerformed(ActionEvent e) {
               mode = Flip.HORIZONTAL;
               repaint();
             }
           });
   Box box = Box.createHorizontalBox();
   box.add(Box.createHorizontalGlue());
   box.add(new JLabel("Flip: "));
   for (AbstractAction a : list) {
     JRadioButton rb = new JRadioButton(a);
     if (bg.getButtonCount() == 0) {
       rb.setSelected(true);
     }
     box.add(rb);
     bg.add(rb);
     box.add(Box.createHorizontalStrut(5));
   }
   add(p);
   add(box, BorderLayout.SOUTH);
   setOpaque(false);
   setPreferredSize(new Dimension(320, 240));
 }
  /** Open a file and load the image. */
  public void openFile() {
    JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(new File("."));
    String[] extensions = ImageIO.getReaderFileSuffixes();
    chooser.setFileFilter(new FileNameExtensionFilter("Image files", extensions));
    int r = chooser.showOpenDialog(this);
    if (r != JFileChooser.APPROVE_OPTION) return;

    try {
      Image img = ImageIO.read(chooser.getSelectedFile());
      image =
          new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
      image.getGraphics().drawImage(img, 0, 0, null);
    } catch (IOException e) {
      JOptionPane.showMessageDialog(this, e);
    }
    repaint();
  }
Example #17
0
  // we define the method for downloading when pressing on the download button
  public void qrvidlink() {
    try {
      System.setSecurityManager(new SecurityManager());

      ipadd = tfIP.getText();
      Interface client = (Interface) Naming.lookup("rmi://" + ipadd + "/getvid");

      // Get the String entered into the TextField tfInput, convert to int
      link = tfInput.getText();
      vlink = client.getvid(link);

      // here we receive the image serialized into bytes from the server and
      // saved it on the client as png image
      byte[] bytimg = client.qrvid(vlink);
      BufferedImage img = ImageIO.read(new ByteArrayInputStream(bytimg));
      File outputfile = new File("qrcode.png");
      ImageIO.write(img, "png", outputfile);

      // img= new ImageIcon(bytimg.toByteArray());
    } catch (Exception e) {
      System.out.println("[System] Server failed: " + e);
    }
  }
Example #18
0
  public ImageFont(String pathToImage, int numCols, int numRows) {
    try {
      tilesImg = convertToARGB(ImageIO.read(new File(pathToImage)));

      this.imgW = tilesImg.getWidth();
      this.imgH = tilesImg.getHeight();
      this.numCols = numCols;
      this.numRows = numRows;
      this.numTiles = numCols * numRows;
      this.tW = this.imgW / this.numCols;
      this.tH = this.imgH / this.numRows;

      this.tiles = new BufferedImage[this.numTiles];

      for (int i = 0; i < numCols; i++) {
        for (int j = 0; j < numRows; j++) {
          tiles[(numCols * j) + i] = tilesImg.getSubimage(i * tW, j * tH, tW, tH);
        }
      }
    } catch (IOException e) {
      System.out.println("Couldn't load the image: " + e);
    }
  }
Example #19
0
  /**
   * Creates an instance of <tt>ShowPreviewDialog</tt>
   *
   * @param chatPanel The <tt>ChatConversationPanel</tt> that is associated with this dialog.
   */
  ShowPreviewDialog(final ChatConversationPanel chatPanel) {
    this.chatPanel = chatPanel;

    this.setTitle(
        GuiActivator.getResources().getI18NString("service.gui.SHOW_PREVIEW_DIALOG_TITLE"));
    okButton = new JButton(GuiActivator.getResources().getI18NString("service.gui.OK"));
    cancelButton = new JButton(GuiActivator.getResources().getI18NString("service.gui.CANCEL"));

    JPanel mainPanel = new TransparentPanel();
    mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
    mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
    // mainPanel.setPreferredSize(new Dimension(200, 150));
    this.getContentPane().add(mainPanel);

    JTextPane descriptionMsg = new JTextPane();
    descriptionMsg.setEditable(false);
    descriptionMsg.setOpaque(false);
    descriptionMsg.setText(
        GuiActivator.getResources().getI18NString("service.gui.SHOW_PREVIEW_WARNING_DESCRIPTION"));

    Icon warningIcon = null;
    try {
      warningIcon =
          new ImageIcon(
              ImageIO.read(
                  GuiActivator.getResources().getImageURL("service.gui.icons.WARNING_ICON")));
    } catch (IOException e) {
      logger.debug("failed to load the warning icon");
    }
    JLabel warningSign = new JLabel(warningIcon);

    JPanel warningPanel = new TransparentPanel();
    warningPanel.setLayout(new BoxLayout(warningPanel, BoxLayout.X_AXIS));
    warningPanel.add(warningSign);
    warningPanel.add(Box.createHorizontalStrut(10));
    warningPanel.add(descriptionMsg);

    enableReplacement =
        new JCheckBox(
            GuiActivator.getResources()
                .getI18NString("plugin.chatconfig.replacement.ENABLE_REPLACEMENT_STATUS"));
    enableReplacement.setOpaque(false);
    enableReplacement.setSelected(cfg.getBoolean(ReplacementProperty.REPLACEMENT_ENABLE, true));
    enableReplacementProposal =
        new JCheckBox(
            GuiActivator.getResources()
                .getI18NString("plugin.chatconfig.replacement.ENABLE_REPLACEMENT_PROPOSAL"));
    enableReplacementProposal.setOpaque(false);

    JPanel checkBoxPanel = new TransparentPanel();
    checkBoxPanel.setLayout(new BoxLayout(checkBoxPanel, BoxLayout.Y_AXIS));
    checkBoxPanel.add(enableReplacement);
    checkBoxPanel.add(enableReplacementProposal);

    JPanel buttonsPanel = new TransparentPanel(new FlowLayout(FlowLayout.CENTER));
    buttonsPanel.add(okButton);
    buttonsPanel.add(cancelButton);

    mainPanel.add(warningPanel);
    mainPanel.add(Box.createVerticalStrut(10));
    mainPanel.add(checkBoxPanel);
    mainPanel.add(buttonsPanel);

    okButton.addActionListener(this);
    cancelButton.addActionListener(this);

    this.setPreferredSize(new Dimension(390, 230));
  }
Example #20
0
 public void setImage(String filename) throws IOException {
   setImage(ImageIO.read(new File(filename)));
 }
  public LoginPanel(Image img, ActionListener listener) {
    super(null);
    this.listener = listener;
    if (img == null) {
      InputStream inData = getClass().getResourceAsStream("/resources/background.gif");
      BufferedImage back = null;
      if (inData != null)
        try {
          back = ImageIO.read(inData);
        } catch (IOException e) {
          loger.finest("LoginPanel class can't get the background image");
        }
      this.background = back;
    }

    setLayout(null);
    JPanel logingPanel = new JPanel();
    loginTitle = new JLabel("Autentificare");
    logingPanel.setSize(250, 150);
    logingPanel.setBorder(new javax.swing.border.LineBorder(Color.black, 2));
    logingPanel.setLayout(null);
    loginTitle.setBounds(3, 0, logingPanel.getWidth(), 20);
    logingPanel.add(loginTitle);
    JLabel loginUser = new JLabel("Utilizator");
    loginUser.setBounds(
        80 - loginUser.getPreferredSize().width,
        40,
        loginUser.getPreferredSize().width,
        loginUser.getPreferredSize().height);
    logingPanel.add(loginUser);
    user = new JTextField(10);
    user.setBounds(85, 40, user.getPreferredSize().width, user.getPreferredSize().height);
    // user.setText("test");
    // loginUser.setLabelFor(user);
    logingPanel.add(user);
    JLabel loginPass = new JLabel("Parola");
    loginPass.setBounds(
        80 - loginPass.getPreferredSize().width,
        80,
        loginPass.getPreferredSize().width,
        loginPass.getPreferredSize().height);
    logingPanel.add(loginPass);
    // JTextField pass = new JTextField(10);
    pass = new JPasswordField(10);
    pass.setBounds(85, 80, pass.getPreferredSize().width, pass.getPreferredSize().height);
    pass.addKeyListener(this);
    // pass.setText("test");
    // loginUser.setLabelFor(user);
    logingPanel.add(pass);
    JButton loginButton = new JButton("Start");
    loginButton.setActionCommand("LOGIN");
    loginButton.setBounds(
        60, 110, loginButton.getPreferredSize().width, loginButton.getPreferredSize().height);
    // loginButton.setOpaque(false);
    loginButton.setFocusPainted(false);
    // loginButton.setContentAreaFilled(false);
    // loginButton.setBorderPainted(false);
    loginButton.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    loginButton.addActionListener(listener);
    logingPanel.add(loginButton);

    add(logingPanel);
  }
Example #22
0
  public static void loadLevel(File levelFile) {

    // clean up old loads:
    loadedLevel.clean();

    if (levelFile != null) {
      GameObject[] go = new GameObject[0];

      try {
        loadedLevel = new Level(levelFile.getPath());
        camera = loadedLevel.getCamera();
        go = loadedLevel.getGameObjects();
      } catch (Exception e) {
        System.out.println(e);
      }

      // Reset numberOf ...
      numberOfBoxes = 0;
      numberOfSprites = 0;
      numberOfTiles = 0;

      for (int i = 0; i < actor.length; i++) {
        actor[i] = null;
      }

      backgroundImage = new Image[2];

      try {
        tileSheet = ImageIO.read(new File(loadedLevel.levelName + "/tilesheet.png"));
        backgroundImage[0] = ImageIO.read(new File(loadedLevel.levelName + "/bg0.png"));
        backgroundImage[1] = ImageIO.read(new File(loadedLevel.levelName + "/bg1.png"));
      } catch (Exception e) {
        System.out.println("ERROR loading images: " + e);
      }

      int MapWidth = loadedLevel.getWidth();
      int MapHeight = loadedLevel.getHeight();

      for (int y = 0; y < MapHeight; y++) {
        for (int x = 0; x < MapWidth; x++) {
          // Number entered in the position represents tileNumber;
          // position of the sprite x*16, y*16

          // get char at position X/Y in the levelLoaded string
          char CharAtXY =
              loadedLevel.level.substring(MapWidth * y, loadedLevel.level.length()).charAt(x);

          // Load objects into the engine/game
          for (int i = 0; i < go.length; i++) {
            if (CharAtXY == go[i].objectChar) {
              try {
                invoke(
                    "game.objects." + go[i].name,
                    "new" + go[i].name,
                    new Class[] {Point.class},
                    new Object[] {new Point(x * 16, y * 16)});
              } catch (Exception e) {
                System.out.println("ERROR trying to invoke method: " + e);
              }
            }
          }

          // Load tiles into engine/game
          // 48 = '0' , 57 = '9'
          if ((int) CharAtXY >= 48 && (int) CharAtXY <= 57) {
            tileObject[gameMain.numberOfTiles] = new WorldTile(Integer.parseInt(CharAtXY + ""));
            tileObject[gameMain.numberOfTiles - 1].sprite.setPosition(x * 16, y * 16);
          }
        }
      }

      // clean up:
      loadedLevel.clean();

      // additional game-specific loading options:
      camera.forceSetPosition(new Point(mario.spawn.x, camera.prefHeight));
      pCoin = new PopupCoin(new Point(-80, -80));

      levelLoaded = true;
    } else {
      System.out.println("Loading cancelled...");
    }
  }
  /**
   * Constructor to create a character
   *
   * @param x X Position
   * @param y Y Position
   * @param w Width of Image
   * @param h Height of Image
   * @param FileN Name of image file
   * @param S Max number of frames
   */
  public GameCharacter(
      double x, double y, double w, double h, String FileN, int S, int Ty, String c) {
    // Set position and size
    X = x;
    Y = y;
    W = w;
    H = h;

    BASIC_PROCESS = new ProgressBar(new Font("Arial", 36, 36), this);
    BASIC_EFFECTS = new ProgressBar(new Font("Arial", 36, 36), this);
    // Add magic attacks
    // Fireball
    for (int i = 0; i < FIREBALL.length; i++) {
      FIREBALL[i] = new MagicAttack(-500, -500, 39, 41, "Fireball.png", 3, 1, 2, "Fireball");
      FIREBALL[i].STATS.setStats(new String[] {"Damage=10", "Points=10"});
      FIREBALL[i].CASTER = this;
    }
    // Shock
    for (int i = 0; i < SHOCK.length; i++) {
      SHOCK[i] = new MagicAttack(-500, -500, 39, 41, "Shock.png", 2, 1, 0, "Shock");
      SHOCK[i].STATS.setStats(new String[] {"Damage=20", "Points=15"});
      SHOCK[i].CASTER = this;
    }
    // Darkness
    for (int i = 0; i < DARKNESS.length; i++) {
      DARKNESS[i] = new MagicAttack(-500, -500, 165, 164, "Darkness.png", 3, 1, 2, "Darkness");
      DARKNESS[i].STATS.setStats(new String[] {"Damage=100", "Points=50"});
      DARKNESS[i].CASTER = this;
    }
    // Life Drain
    for (int i = 0; i < LIFE_DRAIN.length; i++) {
      LIFE_DRAIN[i] = new MagicAttack(-500, -500, 32, 32, "Life Drain.png", 7, 1, 0, "Life Drain");
      LIFE_DRAIN[i].STATS.setStats(new String[] {"Damage=50", "Points=25"});
      LIFE_DRAIN[i].CASTER = this;
    }
    // Get Image
    try {

      if (isJar()) {
        // Character
        imgCHARAC = getImage("/Graphics/Character/", FileN);

        // Blood
        int BloodType = (int) Math.round(Math.random() * 3) + 1;
        imgBLOOD = getImage("/Graphics/Effects/", "Dead" + BloodType + ".png");

        // Quest
        imgQStart = getImage("/Graphics/Effects/", "Quest_Start.png");
        imgQEnd = getImage("/Graphics/Effects/", "Quest_Complete.png");

      } else {
        // Character
        imgCHARAC = ImageIO.read(Paths.get(DIRECT + FileN).toFile());

        // Blood
        int BloodType = (int) Math.round(Math.random() * 3) + 1;
        imgBLOOD = ImageIO.read(Paths.get(DIRECT2 + "Dead" + BloodType + ".png").toFile());

        // Quest
        imgQStart = ImageIO.read(Paths.get(DIRECT2 + "Quest_Start.png").toFile());
        imgQEnd = ImageIO.read(Paths.get(DIRECT2 + "Quest_Complete.png").toFile());
      }

    } catch (Exception e) {
    }

    // Max number of frames
    SIZE = S;

    // Sprite type
    TYPE = Ty;

    // Assign class
    CLASS = c;
    Cl = c;

    // Add items and attacks according to class
    if (CLASS.equals("Player")) {

      // Add items
      INVENTORY.addItem(
          "Health Potion", 25, 1, "Health Pot.png", "Potion", new String[] {"Points=50"});
      INVENTORY.addItem(
          "Rusted Dagger",
          20,
          1,
          "Dagger_4.png",
          "Meele",
          new String[] {"Damage=10", "Attack Speed=1"});
      INVENTORY.addItem(
          "Wooden Staff",
          20,
          1,
          "Staff_1.png",
          "Meele",
          new String[] {"Damage=5", "Attack Speed=1"});

      // Equip items
      INVENTORY.ItemEffect(1, this);
      // MEELE_WEAPON=null;
      // Assign Magic
      SPELL_LIST.add(FIREBALL);

      // Inventory type
      INVENTORY.Type = "Player";
    } else if (CLASS.equals("Citizen")) {

      // Add items
      INVENTORY.addItem(
          "Health Potion", 25, 1, "Health Pot.png", "Potion", new String[] {"Points=50"});

      // Add Ai
      NAI = new NPCAI(this);

      // Add Gold
      this.GOLD = (int) Math.round(Math.random() * 15 + 5);

      INVENTORY.Type = "Friendly";
    } else if (CLASS.equals("Blacksmith")) {

      // Add items
      INVENTORY.addItem(
          "Silver Dagger",
          250,
          1,
          "Dagger_3.png",
          "Meele",
          new String[] {"Damage=10", "Attack Speed=1"});
      INVENTORY.addItem(
          "Steel Dagger",
          450,
          1,
          "Dagger_5.png",
          "Meele",
          new String[] {"Damage=35", "Attack Speed=1"});
      // INVENTORY.addItem("Assassin blade", 750,1, "Dagger_6.png","Meele",new
      // String[]{"Damage=45","Attack Speed=1"});
      // INVENTORY.addItem("Serpent Dagger", 5000,1, "Dagger_2.png","Meele",new
      // String[]{"Damage=50","Attack Speed=1"});
      // INVENTORY.addItem("Dagger of Time", 5050,1, "Dagger_1.png","Meele",new
      // String[]{"Damage=75","Attack Speed=1"});

      INVENTORY.addItem(
          "Steel Sword",
          450,
          1,
          "Sword_1.png",
          "Meele",
          new String[] {"Damage=30", "Attack Speed=0.65"});
      INVENTORY.addItem(
          "Iron Sword",
          50,
          1,
          "Sword_2.png",
          "Meele",
          new String[] {"Damage=15", "Attack Speed=0.65"});
      INVENTORY.addItem(
          "Silver Sword",
          100,
          1,
          "Sword_5.png",
          "Meele",
          new String[] {"Damage=20", "Attack Speed=0.5"});
      // INVENTORY.addItem("Iron Scimitar", 150,1, "Sword_7.png","Meele",new
      // String[]{"Damage=15","Attack Speed=0.75"});
      // INVENTORY.addItem("Steel Scimitar", 500,1, "Sword_4.png","Meele",new
      // String[]{"Damage=50","Attack Speed=0.75"});
      // INVENTORY.addItem("Steel Katana", 450,1, "Sword_6.png","Meele",new
      // String[]{"Damage=40","Attack Speed=0.95"});
      // INVENTORY.addItem("Butcher's Sword", 5000,1, "Sword_3.png","Meele",new
      // String[]{"Damage=100","Attack Speed=0.55"});
      // INVENTORY.addItem("Blood Thirster", 6000,1, "Sword_8.png","Meele",new
      // String[]{"Damage=200","Attack Speed=0.75"});

      INVENTORY.addItem(
          "Iron Hammer",
          150,
          1,
          "Hammer_1.png",
          "Meele",
          new String[] {"Damage=40", "Attack Speed=0.15"});
      // INVENTORY.addItem("Steel Hammer", 450,1, "Hammer_0.png","Meele",new
      // String[]{"Damage=60","Attack Speed=0.15"});
      // INVENTORY.addItem("Iron Mace", 50,1, "Mace_1.png","Meele",new String[]{"Damage=15","Attack
      // Speed=0.5"});

      INVENTORY.addItem("Steel Helmet", 250, 1, "Head_1.png", "H_armor", new String[] {"Armor=20"});
      INVENTORY.addItem("Iron Helmet", 150, 1, "Head_2.png", "H_armor", new String[] {"Armor=5"});
      // INVENTORY.addItem("Iron Horn Helmet", 350,1, "Head_6.png","H_armor",new
      // String[]{"Armor=50","Magic Resist=0"});
      // INVENTORY.addItem("Steel Horn Helmet", 500,1, "Head_7.png","H_armor",new
      // String[]{"Armor=80","Magic Resist=0"});
      // INVENTORY.addItem("Skysteel Helmet", 4000,1, "Head_4.png","H_armor",new
      // String[]{"Armor=60","Magic Resist=25"});

      INVENTORY.addItem(
          "Iron Cuirass", 250, 1, "Chest_4.png", "C_armor", new String[] {"Armor=20"});
      INVENTORY.addItem(
          "Steel Cuirass", 350, 1, "Chest_1.png", "C_armor", new String[] {"Armor=30"});
      // INVENTORY.addItem("Scale Cuirass", 550,1, "Chest_3.png","C_armor",new
      // String[]{"Armor=50"});
      // INVENTORY.addItem("Dark metal Cuirass", 750,1, "Chest_6.png","C_armor",new
      // String[]{"Armor=70"});
      // INVENTORY.addItem("Master Cuirass", 3050,1, "Chest_5.png","C_armor",new
      // String[]{"Armor=80","Magic Resist=25"});
      // INVENTORY.addItem("Legendary Cuirass", 3050,1, "Chest_2.png","C_armor",new
      // String[]{"Armor=100","Magic Resist=100"});

      INVENTORY.addItem(
          "Wooden Shield",
          50,
          1,
          "Shield_1.png",
          "Shield",
          new String[] {"Armor=5", "Magic Resist=0"});

      // Add AI
      NAI = new NPCAI(this);

      // Identify as trader
      INVENTORY.Type = "Trader";

      // Set Stats
      STATS.setStats(new String[] {"Level = 5 "});
      MAX_HEALTH = 200;
      HEALTH = (int) MAX_HEALTH;
    } else if (CLASS.equals("Alchemist")) {
      // Add Items
      INVENTORY.addItem(
          "Health Potion", 25, 50, "Health Pot.png", "Potion", new String[] {"Points=50"});
      INVENTORY.addItem(
          "Mana Potion", 20, 50, "Mana Pot.png", "Potion", new String[] {"Points=50"});
      INVENTORY.addItem(
          "Speed Potion", 10, 50, "Speed Pot.png", "Potion", new String[] {"Points=5"});
      // INVENTORY.addItem("Invisib Potion", 50, 10, "Invisibility Pot.png","Potion",new
      // String[]{"Points=5"});

      // Add AI
      NAI = new NPCAI(this);

      // Identify as trader
      INVENTORY.Type = "Trader";
    } else if (CLASS.equals("Inn Keeper")) {
      // Add Items
      INVENTORY.addItem("Roasted Fish", 15, 10, "Fish.png", "Food", new String[] {"Points=5"});
      INVENTORY.addItem("Apple", 15, 10, "Apple.png", "Food", new String[] {"Points=2"});

      // Add AI
      NAI = new NPCAI(this);

      // Identify as trader
      INVENTORY.Type = "Trader";
    } else if (CLASS.equals("Mage")) {

      INVENTORY.addItem(
          "Leather Cap",
          250,
          1,
          "Head_8.png",
          "H_armor",
          new String[] {"Armor=5", "Magic Resist=25"});
      INVENTORY.addItem(
          "Dark Leather Cap",
          300,
          1,
          "Head_9.png",
          "H_armor",
          new String[] {"Armor=5", "Magic Resist=50"});
      // INVENTORY.addItem("Jesters Cap", 500,1, "Head_5.png","H_armor",new
      // String[]{"Armor=10","Magic Resist=90"});
      // INVENTORY.addItem("Skull Helmet", 5000,1, "Head_3.png","H_armor",new
      // String[]{"Armor=100","Magic Resist=100"});
      INVENTORY.addItem(
          "Shock Spell Stone",
          250,
          1,
          "Stone_1.png",
          "SpellStoner",
          new String[] {"Damage=" + SHOCK[0].STATS.DAMAGE});
      // INVENTORY.addItem("Darkness Spell Stone", 500,1, "Stone_1.png","SpellStoner",new
      // String[]{"Damage="+DARKNESS[0].STATS.DAMAGE});
      INVENTORY.addItem(
          "Life Drain Spell Stone",
          300,
          1,
          "Stone_1.png",
          "SpellStoner",
          new String[] {"Damage=" + LIFE_DRAIN[0].STATS.DAMAGE});

      // Add AI
      NAI = new NPCAI(this);

      // Identify as trader
      INVENTORY.Type = "Trader";

    } else if (CLASS.equals("Skeleton")) {

      // Add items
      INVENTORY.addItem(
          "Bone Club", 5, 1, "Mace_2.png", "Meele", new String[] {"Damage=5", "Attack Speed=1"});

      // Add Gold
      this.GOLD = (int) Math.round(Math.random() * 10 + 2);

      // Use Item
      INVENTORY.ItemEffect(0, this);

      // Add AI
      EAI = new EnemyAI(this);
    } else if (CLASS.equals("Skeleton Chieftan")) {

      // Add Item
      INVENTORY.addItem(
          "Iron Sword",
          50,
          1,
          "Sword_2.png",
          "Meele",
          new String[] {"Damage=15", "Attack Speed=0.65"});
      INVENTORY.addItem(
          "Health Potion", 25, 1, "Health Pot.png", "Potion", new String[] {"Points=50"});

      // Add Gold
      this.GOLD = (int) Math.round(Math.random() * 50 + 25);

      // Use Item
      INVENTORY.ItemEffect(0, this);

      // Assign Stats
      STATS.LEVEL = 3;
      HEALTH = 250;
      MAX_HEALTH = 250;

      // Opify
      Opify(1 / 1.25);

      // Add AI
      EAI = new EnemyAI(this);
    } else if (CLASS.equals("Shaman")) {

      // Add items
      INVENTORY.addItem(
          "Health Potion", 25, 1, "Health Pot.png", "Potion", new String[] {"Points=50"});

      // Add Ai
      NAI = new NPCAI(this);

    } else if (CLASS.equals("Dark Elf")) {

      // Add items
      INVENTORY.addItem(
          "Rusted Dagger",
          20,
          1,
          "Dagger_4.png",
          "Meele",
          new String[] {"Damage=10", "Attack Speed=1"});
      INVENTORY.addItem("Iron Helmet", 150, 1, "Head_2.png", "H_armor", new String[] {"Armor=5"});

      // Assign Stats
      STATS.LEVEL = 2;
      HEALTH = 150;
      MAX_HEALTH = 150;

      // Add Gold
      this.GOLD = (int) Math.round(Math.random() * 15 + 2);

      // Use Item
      INVENTORY.ItemEffect(0, this);
      INVENTORY.ItemEffect(1, this);

      // Add Ai
      EAI = new EnemyAI(this);

    } else if (CLASS.equals("Prisoner")) {
      INVENTORY.addItem("Key", 0, 1, "Key.png", "Key", new String[] {});
      // NAI= new NPCAI(this);
    }
  }
Example #24
0
  // Thread's run method aimed at creating a bitmap asynchronously
  public void run() {
    Drawing drawing = new Drawing();
    PicText rawPicText = new PicText();
    String s = ((PicText) element).getText();
    rawPicText.setText(s);
    drawing.add(
        rawPicText); // bug fix: we must add a CLONE of the PicText, otherwise it loses it former
                     // parent... (then pb with the view )
    drawing.setNotparsedCommands(
        "\\newlength{\\jpicwidth}\\settowidth{\\jpicwidth}{"
            + s
            + "}"
            + CR_LF
            + "\\newlength{\\jpicheight}\\settoheight{\\jpicheight}{"
            + s
            + "}"
            + CR_LF
            + "\\newlength{\\jpicdepth}\\settodepth{\\jpicdepth}{"
            + s
            + "}"
            + CR_LF
            + "\\typeout{JPICEDT INFO: \\the\\jpicwidth, \\the\\jpicheight,  \\the\\jpicdepth }"
            + CR_LF);
    RunExternalCommand.Command commandToRun = RunExternalCommand.Command.BITMAP_CREATION;
    // RunExternalCommand command = new RunExternalCommand(drawing, contentType,commandToRun);
    boolean isWriteTmpTeXfile = true;
    String bitmapExt = "png"; // [pending] preferences
    String cmdLine =
        "{i}/unix/tetex/create_bitmap.sh {p} {f} "
            + bitmapExt
            + " "
            + fileDPI; // [pending] preferences
    ContentType contentType = getContainer().getContentType();
    RunExternalCommand.isGUI = false; // System.out, no dialog box // [pending] debug
    RunExternalCommand command =
        new RunExternalCommand(drawing, contentType, cmdLine, isWriteTmpTeXfile);
    command
        .run(); // synchronous in an async. thread => it's ok (anyway, we must way until the LaTeX
                // process has completed)

    if (wantToComputeLatexDimensions) {
      // load size of text:
      try {
        File logFile = new File(command.getTmpPath(), command.getTmpFilePrefix() + ".log");
        BufferedReader reader = null;
        try {
          reader = new BufferedReader(new FileReader(logFile));
        } catch (FileNotFoundException fnfe) {
          System.out.println("Cannot find log file! " + fnfe.getMessage());
          System.out.println(logFile);
        } catch (IOException ioex) {
          System.out.println("Log file IO exception");
          ioex.printStackTrace();
        } // utile ?
        System.out.println("Log file created! file=" + logFile);
        getDimensionsFromLogFile(reader, (PicText) element);
        syncStringLocation(); // update dimensions
        syncBounds();
        syncFrame();
        SwingUtilities.invokeLater(
            new Thread() {
              public void run() {
                repaint(null);
              }
            });
        // repaint(null); // now that dimensions are available, we force a repaint() [pending]
        // smart-repaint ?
      } catch (Exception e) {
        e.printStackTrace();
      }
    }

    if (wantToGetBitMap) {
      // load image:
      try {
        File bitmapFile =
            new File(command.getTmpPath(), command.getTmpFilePrefix() + "." + bitmapExt);
        this.image = ImageIO.read(bitmapFile);
        System.out.println(
            "Bitmap created! file="
                + bitmapFile
                + ", width="
                + image.getWidth()
                + "pixels, height="
                + image.getHeight()
                + "pixels");
        if (image == null) return;
        syncStringLocation(); // sets strx, stry, and dimensions of text
        syncBounds();
        // update the AffineTransform that will be applied to the bitmap before displaying on screen
        PicText te = (PicText) element;
        text2ModelTr.setToIdentity(); // reset
        PicPoint anchor = te.getCtrlPt(TextEditable.P_ANCHOR, ptBuf);
        text2ModelTr.rotate(getRotation(), anchor.x, anchor.y); // rotate along P_ANCHOR !
        text2ModelTr.translate(te.getLeftX(), te.getTopY());
        text2ModelTr.scale(
            te.getWidth() / image.getWidth(),
            -(te.getHeight() + te.getDepth()) / image.getHeight());
        // [pending]  should do something special to avoid dividing by 0 or setting a rescaling
        // factor to 0 [non invertible matrix] (java will throw an exception)
        syncFrame();
        SwingUtilities.invokeLater(
            new Thread() {
              public void run() {
                repaint(null);
              }
            });
        // repaint(null); // now that bitmap is available, we force a repaint() [pending]
        // smart-repaint ?
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
Example #25
0
  /** Constructor to set everything up */
  public TicTac() {
    // Set defaults before settings are changed via menus
    // (defaults are vs AI, play as X, with graphics on)
    multiPlayers = false;
    temp = false;
    currentPlayer = Symbol.X;
    ai = Symbol.O;
    difficulty = Difficulty.IMPOSSIBLE;

    frame = new JFrame("Tic Tac Toe");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    // Set preferred size so game fills window nicely
    this.setPreferredSize(new Dimension(cellSize * ROWS, cellSize * COLS));
    frame.add(this);

    // Load images
    try {
      sword = ImageIO.read(new File("swordsBlue.png"));
      saber = ImageIO.read(new File("saber2.png"));
      skull = ImageIO.read(new File("skull.png"));
      ring = ImageIO.read(new File("ring.png"));
      smiley = ImageIO.read(new File("smiley.png"));
      hydra = ImageIO.read(new File("hydra.png"));
      finalfantasy = ImageIO.read(new File("finalfantasy.jpg"));
      dragon = ImageIO.read(new File("dargon.jpg"));
      night = ImageIO.read(new File("night.jpg"));
    } catch (IOException e) {
      System.out.println("Could not open image files, turning images off!");
      useImages = false;
    }

    imageX = saber;
    imageO = ring;
    background = dragon;

    // Create menu bars.  Each one item will need a listener
    menuBar = new JMenuBar();
    JMenu menu = new JMenu("Mode");
    JMenu menu2 = new JMenu("Side");
    JMenu menu3 = new JMenu("Graphics");
    JMenu menu4 = new JMenu("Other");
    JMenu menu5 = new JMenu("Difficulty");
    JMenu xImageMenu = new JMenu("Image for X");
    JMenu oImageMenu = new JMenu("Image for O");
    JMenu backgroundMenu = new JMenu("Set Background");
    menuBar.add(menu);
    menuBar.add(menu2);
    menuBar.add(menu5);
    menuBar.add(menu3);
    menuBar.add(menu4);

    // Create checkbox menu items for choices
    final JCheckBoxMenuItem item = new JCheckBoxMenuItem("2 Player");
    final JCheckBoxMenuItem item2 = new JCheckBoxMenuItem("VS Computer");
    final JCheckBoxMenuItem item3 = new JCheckBoxMenuItem("Play as X");
    final JCheckBoxMenuItem item4 = new JCheckBoxMenuItem("Play as O");
    final JCheckBoxMenuItem item5 = new JCheckBoxMenuItem("On");
    final JCheckBoxMenuItem item6 = new JCheckBoxMenuItem("Off");
    JMenuItem item7 = new JMenuItem("Restart");
    JMenuItem item8 = new JMenuItem("Exit");
    final JCheckBoxMenuItem item9 = new JCheckBoxMenuItem("Easy");
    final JCheckBoxMenuItem item10 = new JCheckBoxMenuItem("Hard");
    final JCheckBoxMenuItem item11 = new JCheckBoxMenuItem("Impossible");
    final JCheckBoxMenuItem itemSword = new JCheckBoxMenuItem("Sword");
    final JCheckBoxMenuItem itemSaber = new JCheckBoxMenuItem("Sabers");
    final JCheckBoxMenuItem itemSkull = new JCheckBoxMenuItem("Skull");
    final JCheckBoxMenuItem itemRing = new JCheckBoxMenuItem("One Ring");
    final JCheckBoxMenuItem itemSmiley = new JCheckBoxMenuItem("Red Smiley");
    final JCheckBoxMenuItem itemHydra = new JCheckBoxMenuItem("Hydra");
    final JCheckBoxMenuItem itemDragon = new JCheckBoxMenuItem("Dragon");
    final JCheckBoxMenuItem itemFinalFantasy = new JCheckBoxMenuItem("Final Fantasy 7");
    final JCheckBoxMenuItem itemNight = new JCheckBoxMenuItem("Nighttime");

    // Set the initial checkboxes to true (for play vs ai, as X, with graphics on)
    item2.setSelected(true);
    item3.setSelected(true);
    item5.setSelected(true);
    item11.setSelected(true);
    itemSaber.setSelected(true);
    itemRing.setSelected(true);
    itemDragon.setSelected(true);

    // Play against friend
    item.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            item.setSelected(true);
            item2.setSelected(false);
            multiPlayers = true;
            repaint();
          }
        });
    menu.add(item);

    // Checkbox for Selecting to play against AI
    item2.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            item2.setSelected(true);
            item.setSelected(false);
            if (currentPlayer == Symbol.X) ai = Symbol.O;
            else ai = Symbol.X;
            item3.setSelected(true);
            item4.setSelected(false);
            multiPlayers = false;
          }
        });
    menu.add(item2);

    // Play as X
    item3.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            // use temp variable to move after assigning symbols
            if (item4.getState() && !multiPlayers) temp = true;
            item3.setSelected(true);
            item4.setSelected(false);
            currentPlayer = Symbol.X;
            ai = Symbol.O;
            if (temp) aiMove();
            repaint();
            temp = false;
          }
        });
    menu2.add(item3);

    // Play as O
    item4.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            if (item3.getState() && !multiPlayers) temp = true;
            item4.setSelected(true);
            item3.setSelected(false);
            currentPlayer = Symbol.O;
            ai = Symbol.X;
            if (temp) aiMove();
            repaint();
            temp = false;
          }
        });
    menu2.add(item4);

    // Turn Graphics on
    item5.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            item5.setSelected(true);
            item6.setSelected(false);
            useImages = true;
            repaint();
          }
        });
    menu3.add(item5);

    // Turn Graphics off
    item6.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            item5.setSelected(false);
            item6.setSelected(true);
            useImages = false;
            repaint();
          }
        });
    menu3.add(item6);
    menu3.addSeparator();
    menu3.add(xImageMenu);
    menu3.add(oImageMenu);
    menu3.add(backgroundMenu);

    // Choose Saber for X
    itemSaber.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            itemSword.setSelected(false);
            itemSaber.setSelected(true);
            itemSkull.setSelected(false);
            imageX = saber;
            repaint();
          }
        });
    xImageMenu.add(itemSaber);

    // Choose Sword for X
    itemSword.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            itemSword.setSelected(true);
            itemSaber.setSelected(false);
            itemSkull.setSelected(false);
            imageX = sword;
            repaint();
          }
        });
    xImageMenu.add(itemSword);

    // Choose Skull for X
    itemSkull.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            itemSword.setSelected(false);
            itemSaber.setSelected(false);
            itemSkull.setSelected(true);
            imageX = skull;
            repaint();
          }
        });
    xImageMenu.add(itemSkull);

    // Choose ring for O
    itemRing.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            itemRing.setSelected(true);
            itemSmiley.setSelected(false);
            itemHydra.setSelected(false);
            imageO = ring;
            repaint();
          }
        });
    oImageMenu.add(itemRing);

    // Choose red smiley for O
    itemSmiley.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            itemRing.setSelected(false);
            itemSmiley.setSelected(true);
            itemHydra.setSelected(false);
            imageO = smiley;
            repaint();
          }
        });
    oImageMenu.add(itemSmiley);

    // Choose hydra for O
    itemHydra.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            itemRing.setSelected(false);
            itemSmiley.setSelected(false);
            itemHydra.setSelected(true);
            imageO = hydra;
            repaint();
          }
        });
    oImageMenu.add(itemHydra);

    // Set dragon as background
    itemDragon.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            itemDragon.setSelected(true);
            itemFinalFantasy.setSelected(false);
            itemNight.setSelected(false);
            background = dragon;
            repaint();
          }
        });
    backgroundMenu.add(itemDragon);

    // Set final fantasy 7 as background
    itemFinalFantasy.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            itemDragon.setSelected(false);
            itemFinalFantasy.setSelected(true);
            itemNight.setSelected(false);
            background = finalfantasy;
            repaint();
          }
        });
    backgroundMenu.add(itemFinalFantasy);

    // Set night as background
    itemNight.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            itemDragon.setSelected(false);
            itemFinalFantasy.setSelected(false);
            itemNight.setSelected(true);
            background = night;
            repaint();
          }
        });
    backgroundMenu.add(itemNight);

    // Reset game
    item7.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            initialize();
          }
        });
    menu4.add(item7);

    // Exit game
    item8.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            System.exit(0);
          }
        });
    menu4.add(item8);

    // Difficulty easy
    item9.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            difficulty = Difficulty.EASY;
            item9.setSelected(true);
            item10.setSelected(false);
            item11.setSelected(false);
          }
        });
    menu5.add(item9);

    // Difficulty hard
    item10.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            difficulty = Difficulty.HARD;
            item10.setSelected(true);
            item9.setSelected(false);
            item11.setSelected(false);
          }
        });
    menu5.add(item10);

    // Difficulty impossible
    item11.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            difficulty = Difficulty.IMPOSSIBLE;
            item11.setSelected(true);
            item9.setSelected(false);
            item10.setSelected(false);
          }
        });
    menu5.add(item11);

    // Add Whole menu bar to frame
    frame.setJMenuBar(menuBar);

    // Create statusBar (updates will take place in paintComponent)
    statusBar = new JLabel("  ");
    statusBar.setFont(new Font(Font.DIALOG_INPUT, Font.BOLD, 15));
    statusBar.setBorder(BorderFactory.createEmptyBorder(2, 5, 4, 5));
    // Use container variable to set layout and pack everything nicely
    Container cp = frame.getContentPane();
    cp.setLayout(new BorderLayout());
    cp.add(this, BorderLayout.CENTER);
    cp.add(statusBar, BorderLayout.SOUTH);
    frame.pack();

    board = new Symbol[ROWS][COLS];
    initialize();

    // Add the mouse listener.  Use MouseAdapter rather than implement it
    this.addMouseListener(
        new MouseAdapter() {
          @Override
          public void mouseClicked(MouseEvent e) {
            int currentCol = e.getX() / cellSize;
            int currentRow = e.getY() / cellSize;

            if (gameStatus == GameStatus.CONTINUE) {
              // If valid click, and spot is empty, make the move.  Then check
              // to see if game is won. If not, and facing AI, ai moves.
              // Otherwise switch X and O
              if (currentRow >= 0
                  && currentRow < ROWS
                  && currentCol >= 0
                  && currentCol < COLS
                  && board[currentRow][currentCol] == Symbol.EMPTY) {
                board[currentRow][currentCol] = currentPlayer;
                checkState(currentPlayer);

                if (multiPlayers) currentPlayer = (currentPlayer == Symbol.X) ? Symbol.O : Symbol.X;

                if (gameStatus == GameStatus.CONTINUE && !multiPlayers) aiMove();
              }
            } else {
              // Game is over, so re-initialize everything
              initialize();
            }
            repaint();
          }
        });
  }
Example #26
0
  public erosion(String nombre) {

    imageName = nombre;

    // BufferedImage image2;
    String aux;

    // int ancho=image.getWidth();

    // BufferedImage image = ImageIO.read( new File( imageName ) );
    try {
      image = ImageIO.read(new File(imageName));
    } catch (IOException e) {
      System.out.println("image missing");
    }

    try {
      image2 = ImageIO.read(new File(imageName));
    } catch (IOException e) {
      System.out.println("image missing");
    }

    int k;
    int a;
    int b;
    int i;
    int j;

    int rojo;
    int verde;
    int azul;

    int promedio;
    try {
      int ancho, alto;
      alto = image.getHeight();
      ancho = image.getWidth();
      for (i = 0; i < ancho; i++) {
        for (j = 0; j < alto; j++) {
          k = image.getRGB(i, j);
          k = 0xFFFFFF + k;

          rojo = k / 0x10000;

          k = k % 0x10000;
          verde = k / 0x100;

          k = k % 0x100;
          azul = k;

          if (rojo < 0) rojo = 255 + rojo;
          if (verde < 0) verde = 255 + verde;
          if (azul < 0) azul = 255 + azul;

          promedio = azul + verde + rojo;
          promedio = promedio / 3;
          /*if(promedio<0)
          promedio=promedio+128;*/

          rojo = promedio;
          verde = promedio;
          azul = promedio;
          // printf("")

          if (promedio >= 128) promedio = 255;
          else promedio = 0;
          k = promedio + promedio * 0x100 + promedio * 0x10000;

          this.image.setRGB(i, j, k);
        }
      }
    } catch (Exception e) {
      System.out.printf("n");
    }
    //
    try {
      int ancho, alto;
      alto = image2.getHeight();
      ancho = image2.getWidth();
      for (i = 0; i < ancho; i++) {
        for (j = 0; j < alto; j++) {
          k = image2.getRGB(i, j);
          k = 0xFFFFFF + k;

          rojo = k / 0x10000;

          k = k % 0x10000;
          verde = k / 0x100;

          k = k % 0x100;
          azul = k;

          if (rojo < 0) rojo = 255 + rojo;
          if (verde < 0) verde = 255 + verde;
          if (azul < 0) azul = 255 + azul;

          promedio = azul + verde + rojo;
          promedio = promedio / 3;
          /*if(promedio<0)
          promedio=promedio+128;*/

          rojo = promedio;
          verde = promedio;
          azul = promedio;
          // printf("")

          k = promedio + promedio * 0x100 + promedio * 0x10000;

          this.image2.setRGB(i, j, k);
        }
      }
    } catch (Exception e) {
      System.out.printf("n");
    }

    //
    try {
      int ancho, alto;
      alto = image.getHeight();
      ancho = image.getWidth();
      for (i = 0; i < ancho; i++) {
        for (j = 0; j < alto; j++) {
          k = image.getRGB(i, j);
          k = 0xFFFFFF + k;

          rojo = k / 0x10000;

          k = k % 0x10000;
          verde = k / 0x100;

          k = k % 0x100;
          azul = k;

          if (rojo < 0) rojo = 255 + rojo;
          if (verde < 0) verde = 255 + verde;
          if (azul < 0) azul = 255 + azul;

          /*promedio=azul+verde+rojo;
          promedio=promedio/3;
          /*if(promedio<0)
           promedio=promedio+128;*/

          if (i < ancho - 2) {
            if (rojo >= 128) {
              k = image.getRGB(i + 1, j);
              k = 0xFFFFFF + k;

              rojo = k / 0x10000;

              k = k % 0x10000;
              verde = k / 0x100;

              k = k % 0x100;
              azul = k;

              if (rojo < 0) rojo = 255 + rojo;
              if (verde < 0) verde = 255 + verde;
              if (azul < 0) azul = 255 + azul;

              if (rojo >= 128) {
                k = image.getRGB(i + 2, j);
                k = 0xFFFFFF + k;

                rojo = k / 0x10000;

                k = k % 0x10000;
                verde = k / 0x100;

                k = k % 0x100;
                azul = k;

                if (rojo < 0) rojo = 255 + rojo;
                if (verde < 0) verde = 255 + verde;
                if (azul < 0) azul = 255 + azul;
                if (rojo < 128) {
                  k = 0;
                  this.image2.setRGB(i, j, k);
                  this.image2.setRGB(i + 1, j, k);
                  this.image2.setRGB(i + 2, j, k);
                }
              }

            } else {
              k = rojo + rojo * 0x100 + rojo * 0x10000;
              this.image2.setRGB(i, j, k);
            }
          }
        }
      }
    } catch (Exception e) {
      System.out.printf("n");
    }
    //

    /*else if(l==4)
    posterizacion();*/

    // Toolkit tool = Toolkit.getDefaultToolkit();
    // image = tool.getImage(imageName);

    // dialogo.setLocationRelativeTo(f);

  }
  // Constructor connection receiving a socket number
  public ClientGUI(String host, int port, int udpPort) {

    super("Clash of Clans");
    defaultPort = port;
    defaultUDPPort = udpPort;
    defaultHost = host;

    // the server name and the port number
    JPanel serverAndPort = new JPanel(new GridLayout(1, 5, 1, 3));
    tfServer = new JTextField(host);
    tfPort = new JTextField("" + port);
    tfPort.setHorizontalAlignment(SwingConstants.RIGHT);

    // CHAT COMPONENTS
    chatStatus = new JLabel("Please login first", SwingConstants.LEFT);
    chatField = new JTextField(18);
    chatField.setBackground(Color.WHITE);

    JPanel chatControls = new JPanel();
    chatControls.add(chatStatus);
    chatControls.add(chatField);
    chatControls.setBounds(0, 0, 200, 50);

    chatArea = new JTextArea("Welcome to the Chat room\n", 80, 80);
    chatArea.setEditable(false);
    JScrollPane jsp = new JScrollPane(chatArea);
    jsp.setBounds(0, 50, 200, 550);

    JPanel chatPanel = new JPanel(null);
    chatPanel.setSize(1000, 600);
    chatPanel.add(chatControls);
    chatPanel.add(jsp);

    // LOGIN COMPONENTS
    mainLogin = new MainPanel();
    mainLogin.add(new JLabel("Main Login"));

    usernameField = new JTextField("user", 15);
    passwordField = new JTextField("password", 15);
    login = new CButton("Login");
    login.addActionListener(this);

    sideLogin = new SidePanel(new FlowLayout(FlowLayout.LEFT));
    sideLogin.add(usernameField);
    sideLogin.add(passwordField);
    sideLogin.add(login);

    // MAIN MENU COMPONENTS
    mainMenu = new MainPanel();
    mmLabel = new JLabel("Main Menu");
    timer = new javax.swing.Timer(1000, this);
    mainMenu.add(mmLabel);

    sideMenu = new SidePanel(new FlowLayout(FlowLayout.LEFT));
    cmButton = new CButton("Customize Map");
    tmButton = new CButton("Troop Movement");
    gsButton = new CButton("Game Start");
    logout = new CButton("Logout");
    cmButton.addActionListener(this);
    tmButton.addActionListener(this);
    gsButton.addActionListener(this);
    logout.addActionListener(this);
    sideMenu.add(cmButton);
    // sideMenu.add(tmButton);
    sideMenu.add(gsButton);
    sideMenu.add(logout);

    // CM COMPONENTS
    mainCM = new MainPanel(new GridLayout(mapSize, mapSize));
    tiles = new Tile[mapSize][mapSize];
    int tileSize = mainCM.getWidth() / mapSize;
    for (int i = 0; i < mapSize; i++) {
      tiles[i] = new Tile[mapSize];
      for (int j = 0; j < mapSize; j++) {
        tiles[i][j] = new Tile(i, j);
        tiles[i][j].setPreferredSize(new Dimension(tileSize, tileSize));
        tiles[i][j].setSize(tileSize, tileSize);
        tiles[i][j].addActionListener(this);

        if ((i + j) % 2 == 0) tiles[i][j].setBackground(new Color(102, 255, 51));
        else tiles[i][j].setBackground(new Color(51, 204, 51));

        mainCM.add(tiles[i][j]);
      }
    }

    sideCM = new SidePanel(new FlowLayout(FlowLayout.LEFT));
    cmBack = new CButton("Main Menu");
    cmBack.setSize(150, 30);
    cmBack.setPreferredSize(new Dimension(150, 30));
    cmBack.addActionListener(this);
    sideCM.add(cmBack);

    // TM COMPONENTS
    mainTM = new MainPanel(null);
    mapTM = new Map(600);
    mapTM.setPreferredSize(new Dimension(600, 600));
    mapTM.setSize(600, 600);
    mapTM.setBounds(0, 0, 600, 600);
    mainTM.add(mapTM);

    sideTM = new SidePanel(new FlowLayout(FlowLayout.LEFT));
    tmBack = new CButton("Main Menu");
    tmBack.setSize(150, 30);
    tmBack.setPreferredSize(new Dimension(150, 30));
    tmBack.addActionListener(this);
    sideTM.add(tmBack);

    JRadioButton button;
    ButtonGroup group;

    ub = new ArrayList<JRadioButton>();
    group = new ButtonGroup();

    button = new JRadioButton("Barbarian");
    button.addActionListener(this);
    ub.add(button);
    sideTM.add(button);
    group.add(button);

    button = new JRadioButton("Archer");
    button.addActionListener(this);
    ub.add(button);
    sideTM.add(button);
    group.add(button);

    createBuildings();
    bb = new ArrayList<JRadioButton>();

    group = new ButtonGroup();

    JRadioButton removeButton = new JRadioButton("Remove Building");
    bb.add(removeButton);
    sideCM.add(removeButton);
    group.add(removeButton);

    for (int i = 0; i < bList.size(); i++) {
      button = new JRadioButton(bList.get(i).getName() + '-' + bList.get(i).getQuantity());
      bb.add(button);
      sideCM.add(button);
      group.add(button);
    }

    mainPanels = new MainPanel(new CardLayout());
    mainPanels.add(mainLogin, "Login");
    mainPanels.add(mainMenu, "Menu");
    mainPanels.add(mainCM, "CM");
    mainPanels.add(mainTM, "TM");

    sidePanels = new SidePanel(new CardLayout());
    sidePanels.add(sideLogin, "Login");
    sidePanels.add(sideMenu, "Menu");
    sidePanels.add(sideCM, "CM");
    sidePanels.add(sideTM, "TM");

    JPanel mainPanel = new JPanel(null);
    mainPanel.setSize(1000, 600);
    mainPanel.add(sidePanels);
    mainPanel.add(mainPanels);
    mainPanel.add(chatPanel);

    add(mainPanel, BorderLayout.CENTER);

    try {
      setIconImage(ImageIO.read(new File("images/logo.png")));
    } catch (IOException exc) {
      exc.printStackTrace();
    }

    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setSize(1000, 600);
    setVisible(true);
    setResizable(false);
    chatField.requestFocus();
  }
  public void insertBuilding(int i, int j, int index) {

    if (!tiles[i][j].getValue().equals("")) {
      JOptionPane.showMessageDialog(null, "There is already a building here");
      return;
    }

    String temp = bb.get(index).getText();
    String[] parts = temp.split("-");

    int newQ = Integer.parseInt(parts[1]) - 1;
    if (newQ < 0) return;

    Building tB = bList.get(0);
    for (int b = 0; b < bList.size(); b++) {
      if (bList.get(b).getName().equals(parts[0])) {
        tB = bList.get(b);
        // System.out.println("here");
        break;
      }
    }

    Image image = null;
    BufferedImage buffered;
    try {
      image = ImageIO.read(new File("images/" + tB.getName().replace(" ", "_") + ".png"));
      System.out.println("Loaded image");
    } catch (IOException e) {
      System.out.println("Failed to load image");
    }
    buffered = (BufferedImage) image;

    for (int c = 0; c < tB.getQWidth(); c++) {
      for (int r = 0; r < tB.getQHeight(); r++) {
        if (i + c == 40 || j + r == 40) {
          JOptionPane.showMessageDialog(null, "Placing a building here would be out of bounds");
          return;
        }

        if (!tiles[i + c][j + r].getValue().equals("")) {
          JOptionPane.showMessageDialog(null, "Placing a building here will result to a overlap");
          return;
        }
      }
    }

    double w = buffered.getWidth() / tB.getQWidth();
    double h = buffered.getHeight() / tB.getQHeight();

    for (int c = 0; c < tB.getQWidth(); c++) {
      for (int r = 0; r < tB.getQHeight(); r++) {
        tiles[i + c][j + r].setBackground(new Color(51, 204, 51));
        tiles[i + c][j + r].setIcon(
            new ImageIcon(
                resize(
                    buffered.getSubimage((int) w * r, (int) h * c, (int) w, (int) h),
                    tiles[i + c][j + r].getWidth(),
                    tiles[i + c][j + r].getHeight())));

        String tValue = (c == 0 && r == 0) ? tB.getName() : i + "-" + j;
        // System.out.println(tValue);
        tiles[i + c][j + r].setValue(tValue);
      }
    }

    // tiles[i][j].setBackground(Color.BLUE);
    bb.get(index).setText(parts[0] + "-" + newQ);
  }
Example #29
0
  private void makeMenuScreen() {
    menu = new JPanel();
    menu.setBackground(Color.BLACK);
    menu.setLayout(null);
    menu.setBounds(0, 0, width, height);

    try {
      BufferedImage menuIMG =
          ImageIO.read(this.getClass().getResource("/Resources/MenuBackground.png"));
      // BufferedImage menuIMG = ImageIO.read(new
      // File("M:/ComputerProgrammingJava/InsaneMouse_03/src/Resources/MenuBackground.png"));
      menuIMGL =
          new JLabel(
              new ImageIcon(
                  menuIMG.getScaledInstance(
                      (int) (width * 0.8), (int) (height * 0.8), Image.SCALE_SMOOTH)));
      menuIMGL.setBounds(0, 0, width, height);
    } catch (Exception e) {
    }

    highscoreL = new JLabel(String.valueOf(highscore));
    highscoreL.setBackground(Color.darkGray);
    highscoreL.setBounds((width / 2) + 100, (height / 2) + 70, 500, 100);
    highscoreL.setForeground(Color.white);

    easy = new JButton("Easy");
    hard = new JButton("Hard");

    easy.addActionListener(this);
    hard.addActionListener(this);

    easy.setBounds((width / 2) - 60, (height / 2) - 50, 120, 20);
    hard.setBounds((width / 2) - 60, height / 2 - 10, 120, 20);

    onePlayerRB = new JRadioButton("One Player");
    twoPlayerRB = new JRadioButton("Two Player");
    mouseRB = new JRadioButton("Mouse (Player 1)");
    keyboardRB = new JRadioButton("Keyboard (Player 1)");
    keyboardSpeedS1 = new JSlider(JSlider.HORIZONTAL, 10, 300, 50);
    keyboardSpeedS2 = new JSlider(JSlider.HORIZONTAL, 10, 300, 50);
    musicCB = new JCheckBox("Music");

    onePlayerRB.setBackground(null);
    twoPlayerRB.setBackground(null);
    mouseRB.setBackground(null);
    keyboardRB.setBackground(null);
    keyboardSpeedS1.setBackground(null);
    keyboardSpeedS2.setBackground(null);
    musicCB.setBackground(null);

    onePlayerRB.setForeground(Color.WHITE);
    twoPlayerRB.setForeground(Color.WHITE);
    mouseRB.setForeground(Color.WHITE);
    keyboardRB.setForeground(Color.WHITE);
    keyboardSpeedS1.setForeground(Color.WHITE);
    keyboardSpeedS2.setForeground(Color.WHITE);
    musicCB.setForeground(Color.WHITE);

    ButtonGroup playerChoice = new ButtonGroup();
    playerChoice.add(onePlayerRB);
    playerChoice.add(twoPlayerRB);
    onePlayerRB.setSelected(true);

    ButtonGroup peripheralChoice = new ButtonGroup();
    peripheralChoice.add(mouseRB);
    peripheralChoice.add(keyboardRB);
    mouseRB.setSelected(true);

    musicCB.setSelected(true);

    onePlayerRB.setBounds((width / 2) + 100, (height / 2) - 50, 100, 20);
    twoPlayerRB.setBounds((width / 2) + 100, (height / 2) - 30, 100, 20);
    mouseRB.setBounds((width / 2) + 100, (height / 2), 200, 20);
    keyboardRB.setBounds((width / 2) + 100, (height / 2) + 20, 200, 20);
    keyboardSpeedS1.setBounds(width / 2 - 120, height / 2 + 100, 200, 50);
    keyboardSpeedS2.setBounds(width / 2 - 120, height / 2 + 183, 200, 50);
    musicCB.setBounds((width / 2) + 100, (height / 2) + 50, 100, 20);

    keyboardSpeedL1 = new JLabel("Keyboard Speed (Player One)");
    keyboardSpeedL1.setForeground(Color.WHITE);
    keyboardSpeedL1.setBounds(width / 2 - 113, height / 2 + 67, 200, 50);

    keyboardSpeedL2 = new JLabel("Keyboard Speed (Player Two)");
    keyboardSpeedL2.setForeground(Color.WHITE);
    keyboardSpeedL2.setBounds(width / 2 - 113, height / 2 + 150, 200, 50);

    howTo = new JButton("How To Play");
    howTo.addActionListener(this);
    howTo.setBounds((width / 2) - 60, height / 2 + 30, 120, 20);

    try {
      BufferedImage howToIMG = ImageIO.read(this.getClass().getResource("/Resources/HowTo.png"));
      // BufferedImage howToIMG = ImageIO.read(new
      // File("M:/ComputerProgrammingJava/InsaneMouse_03/src/Resources/HowTo.png"));
      howToIMGL = new JLabel(new ImageIcon(howToIMG));
      howToIMGL.setBounds(
          width / 2 - howToIMG.getWidth() / 2,
          height / 2 - howToIMG.getHeight() / 2,
          howToIMG.getWidth(),
          howToIMG.getHeight());
    } catch (Exception e) {
    }

    howToBack = new JButton("X");
    howToBack.setBounds(
        (int) (width / 2 + width * 0.25) - 50, (int) (height / 2 - height * 0.25), 50, 50);
    howToBack.setBackground(Color.BLACK);
    howToBack.setForeground(Color.WHITE);
    howToBack.addActionListener(this);

    menu.add(easy);
    menu.add(hard);
    menu.add(howTo);
    menu.add(highscoreL);
    menu.add(onePlayerRB);
    menu.add(twoPlayerRB);
    menu.add(mouseRB);
    menu.add(keyboardRB);
    menu.add(keyboardSpeedL1);
    menu.add(keyboardSpeedL2);
    menu.add(keyboardSpeedS1);
    menu.add(keyboardSpeedS2);
    menu.add(musicCB);
    menu.add(menuIMGL);

    back = new JButton("Back");
    back.setBounds(width / 2 - 40, height / 2, 100, 20);
    back.addActionListener(this);
    back.setVisible(false);
    this.add(back);
  }