Advertisement
Guest User

Monster Defense

a guest
May 1st, 2016
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 20.00 KB | None | 0 0
  1. Entity.java:
  2.  
  3.  
  4. package monster.defense;
  5.  
  6. import java.awt.*;
  7.  
  8. public abstract class Entity {
  9.     protected int x, y, w, h;
  10.     protected boolean removed = false;
  11.     public Entity(int x, int y)
  12. {
  13.     this.x = x;
  14.     this.y = y;
  15. }
  16.     public void draw(Graphics g)
  17.     {  
  18.     }
  19.    
  20.     public int getX() {return x;}
  21.     public int getY() {return y;}
  22.     public int getW() {return w;}
  23.     public int getH() {return h;}
  24. }
  25.  
  26.  
  27. game.java:
  28.  
  29. /*
  30.  * To change this license header, choose License Headers in Project Properties.
  31.  * To change this template file, choose Tools | Templates
  32.  * and open the template in the editor.
  33.  */
  34. package monster.defense;
  35.  
  36. import java.awt.Graphics;
  37. import java.awt.*;
  38. import java.awt.event.*;
  39. import java.util.logging.Level;
  40. import java.util.logging.Logger;
  41.  
  42. public class game extends javax.swing.JPanel implements KeyListener{
  43.     private int x = 20;
  44.     private int y = 20;
  45.     //private player instance;
  46.     private int cnt = 0;
  47.     private player[] enemy;
  48.     private player[] towers;
  49.     private Rectangle[] boxes;
  50.     private int baseH=40;
  51.     public game() {
  52.       //  Player1 = new player(100,100,16,16);
  53.     setFocusable(true);
  54.     addKeyListener(this);
  55.    
  56.     addMouseListener(new MouseAdapter(){
  57.         @Override
  58.         public void mousePressed(MouseEvent m)
  59.             {
  60.               if(cnt==0)
  61.             {
  62.                 setArray();
  63.             }
  64.               int mx=m.getX();
  65.               int my=m.getY();
  66.               towers[cnt].setX(mx);
  67.               towers[cnt].setY(my);
  68.               boxes[cnt].x=(mx);
  69.               boxes[cnt].y=(my);
  70.               cnt++;
  71.             repaint();
  72.             }
  73.     });
  74.    
  75.     setEnArray();
  76.     //for(int i=0; i<enemy.length;i++)
  77.     //{
  78.     //enemy[i] = new player(this, 0,200);
  79.     //}
  80.         initComponents();
  81.     }
  82.     @SuppressWarnings("unchecked")
  83.     // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  84.     private void initComponents() {
  85.  
  86.         setBackground(new java.awt.Color(200, 22, 0));
  87.  
  88.         javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
  89.         this.setLayout(layout);
  90.         layout.setHorizontalGroup(
  91.             layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  92.             .addGap(0, 907, Short.MAX_VALUE)
  93.         );
  94.         layout.setVerticalGroup(
  95.             layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  96.             .addGap(0, 521, Short.MAX_VALUE)
  97.         );
  98.     }// </editor-fold>//GEN-END:initComponents
  99. public int getEnemyNum()
  100. {
  101.     return enemy.length;
  102. }
  103.     public void setEnArray()
  104. {
  105.     this.enemy = new player[20];
  106.     for(int i=0;i<enemy.length;i++)
  107.     {
  108.         enemy[i] = new player(this,0,200);
  109.     }
  110.    
  111. }
  112.     public void setArray()
  113. {
  114.     //Use the global variable and don't create a local one
  115.     this.towers = new player[30];
  116.     this.boxes = new Rectangle[30];
  117.     for(int i = 0; i < 30; i++)
  118.     {
  119.         towers[i] = new player(this, 5,5);
  120.         boxes[i] = new Rectangle(towers[i].x,towers[i].y,100,100);
  121.     }
  122. }
  123.     public Rectangle getBox(int val)
  124.     {
  125.         return boxes[val];
  126.     }
  127.     public int getCnt()
  128.     {
  129.         return cnt;
  130.     }
  131.     public void paint(Graphics g)
  132.     {
  133.         g.setColor(Color.gray);
  134.         g.fillRect(0, 0, getWidth(), getHeight()); //BACKGROUND
  135.         g.setColor(Color.WHITE);
  136.         g.fillRect(0,200, getWidth(), 20);
  137.         Color myColour = new Color(80, 80, 255, 127);
  138.         g.setColor(myColour);
  139.         for(int i=0; i<cnt;i++)
  140.         {
  141.             boxes[i].setBounds(towers[i].x-40, towers[i].y-40, 100, 100); //SETS THE BOX AROUND THE TOWER
  142.             g.fillRect(boxes[i].x,boxes[i].y,boxes[i].width,boxes[i].height); //DRAWS THE TOWER HIT BOX
  143.         }
  144.         for(int i = 0; i < cnt; i++) //Draws the towers
  145.         {
  146.             towers[i].draw(g);
  147.            
  148.         }
  149.         for(int i=0;i<enemy.length;i++)
  150.         {
  151.                     if(enemy[i].x==900&&!(enemy[i].getHealth()<=0))
  152.                     {
  153.                       baseH--;  
  154.                     }
  155.                     System.out.println(baseH);
  156.                     g.setFont(new Font("ArialBlack", Font.BOLD, 30));
  157.                     g.drawString(""+baseH, 800, 100);
  158.         }
  159.         try {
  160.             for(int i=0;i<enemy.length-1;i++)
  161.             {
  162.             enemy[i].drawEnemy(g);
  163.             enemy[i+1].setX(enemy[i].x-50);
  164.             }
  165.  
  166.             Thread.sleep(8);
  167.         } catch (InterruptedException ex) {
  168.             Logger.getLogger(game.class.getName()).log(Level.SEVERE, null, ex);
  169.         }
  170.                  int ok = 1;//if(instance.getBox().x < box.x + box.width && instance.getBox().x + instance.getBox().width > box.x && instance.getBox().y < box.y + box.height && y + instance.getBox().height > box.y)
  171.         for(int i=0;i<enemy.length; i++)
  172.         {
  173.             if(cnt>0)
  174.             {
  175.                 //for(int j=0; j<boxes.length;j++)
  176.                 //{
  177.                   if(enemy[i].getEBox().intersects(boxes[i])) //INTERSECTION CHECK
  178.                     {
  179.                      g.setColor(Color.yellow);
  180.                      enemy[i].setHealth(enemy[i].getHealth()-1);
  181.                      ok=0;
  182.                     // System.out.println(enemy[i].getHealth());
  183.                    
  184.                     }
  185.                    else{}
  186.                 //}
  187.             }
  188.        
  189.          
  190.  
  191.        
  192.         if(ok==1)
  193.         {
  194.               g.setColor(Color.GREEN);
  195.          }
  196.                 else{
  197.             Color dead = new Color(0,0,0,255);
  198.             g.setColor(dead);
  199.             g.fillOval(x,y,16,16);
  200.             this.x++;
  201.         }
  202.         g.fillOval(x,y,16,16);
  203.         Color msColour = new Color(80, 80, 255, 127);
  204.         g.setColor(msColour);
  205.         }
  206.        
  207.  
  208.         repaint();
  209.       }
  210.  
  211.     @Override
  212.     public void keyTyped(KeyEvent e) {
  213.         throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
  214.     }
  215.  
  216.     @Override
  217.     public void keyPressed(KeyEvent e) {
  218.         throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
  219.     }
  220.  
  221.     @Override
  222.     public void keyReleased(KeyEvent e) {
  223.         throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
  224.     }
  225.  }
  226.  
  227.     // Variables declaration - do not modify//GEN-BEGIN:variables
  228.     // End of variables declaration//GEN-END:variables
  229.  
  230. Menu.java:
  231.  
  232.  
  233. package monster.defense;
  234.  
  235. import java.io.BufferedWriter;
  236. import java.io.FileWriter;
  237. import java.util.logging.Level;
  238. import java.util.logging.Logger;
  239.  
  240. public class Menu extends javax.swing.JFrame {
  241.     public Menu() {
  242.         initComponents();
  243.     }
  244.  
  245.     @SuppressWarnings("unchecked")
  246.     // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  247.     private void initComponents() {
  248.  
  249.         jLabel1 = new javax.swing.JLabel();
  250.         jButton1 = new javax.swing.JButton();
  251.         jLabel2 = new javax.swing.JLabel();
  252.         jButton2 = new javax.swing.JButton();
  253.         playername = new javax.swing.JTextField();
  254.  
  255.         setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
  256.  
  257.         jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
  258.         jLabel1.setText("Enter your name:");
  259.  
  260.         jButton1.setFont(new java.awt.Font("Minion Pro Cond", 0, 48)); // NOI18N
  261.         jButton1.setText("PLAY!");
  262.         jButton1.setToolTipText("");
  263.         jButton1.addActionListener(new java.awt.event.ActionListener() {
  264.             public void actionPerformed(java.awt.event.ActionEvent evt) {
  265.                 jButton1ActionPerformed(evt);
  266.             }
  267.         });
  268.  
  269.         jLabel2.setFont(new java.awt.Font("Forte", 0, 36)); // NOI18N
  270.         jLabel2.setText("Monster Defense");
  271.  
  272.         jButton2.setFont(new java.awt.Font("Arial Black", 0, 13)); // NOI18N
  273.         jButton2.setText("EXIT GAME");
  274.         jButton2.addActionListener(new java.awt.event.ActionListener() {
  275.             public void actionPerformed(java.awt.event.ActionEvent evt) {
  276.                 jButton2ActionPerformed(evt);
  277.             }
  278.         });
  279.  
  280.         javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
  281.         getContentPane().setLayout(layout);
  282.         layout.setHorizontalGroup(
  283.             layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  284.             .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
  285.                 .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
  286.                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  287.                     .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
  288.                         .addComponent(jButton2)
  289.                         .addGap(142, 142, 142))
  290.                     .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
  291.                         .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 191, javax.swing.GroupLayout.PREFERRED_SIZE)
  292.                         .addGap(102, 102, 102))
  293.                     .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
  294.                         .addComponent(playername, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE)
  295.                         .addContainerGap())))
  296.             .addGroup(layout.createSequentialGroup()
  297.                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  298.                     .addGroup(layout.createSequentialGroup()
  299.                         .addContainerGap()
  300.                         .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)
  301.                         .addGap(0, 0, Short.MAX_VALUE))
  302.                     .addGroup(layout.createSequentialGroup()
  303.                         .addGap(62, 62, 62)
  304.                         .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 326, Short.MAX_VALUE)))
  305.                 .addContainerGap())
  306.         );
  307.         layout.setVerticalGroup(
  308.             layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  309.             .addGroup(layout.createSequentialGroup()
  310.                 .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 83, Short.MAX_VALUE)
  311.                 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  312.                 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
  313.                     .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
  314.                     .addComponent(playername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
  315.                 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
  316.                 .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)
  317.                 .addGap(18, 18, 18)
  318.                 .addComponent(jButton2)
  319.                 .addGap(16, 16, 16))
  320.         );
  321.  
  322.         pack();
  323.     }// </editor-fold>//GEN-END:initComponents
  324. String kay;
  325.  
  326.     private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
  327.          System.exit(0);
  328.     }//GEN-LAST:event_jButton2ActionPerformed
  329. String clicked = "0";
  330.     private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
  331.      
  332.      String name = playername.getText();
  333.     // System.out.println(playername.getText());
  334.      kay = "yumyum";
  335.         try {
  336.             this.WriteToText();
  337.         } catch (Exception ex) {
  338.             Logger.getLogger(Menu.class.getName()).log(Level.SEVERE, null, ex);
  339.         }
  340.     }//GEN-LAST:event_jButton1ActionPerformed
  341.  
  342.     public String getPName()
  343.   {
  344.      
  345.       String name = playername.getText();
  346.       return name;
  347.   }
  348.  
  349.      public void WriteToText() throws Exception
  350.      {
  351.          //BufferedWriter outF = new BufferedWriter(new FileWriter("playerdetails.txt"));
  352.          //outF.newLine();
  353.          //outF.write(playername.getText());
  354.          
  355.          FileWriter fw = new FileWriter("playerdetails.txt");
  356.      BufferedWriter bw = new BufferedWriter(fw);
  357.      bw.write(playername.getText());
  358.          clicked = "1";
  359.          this.opened = true;
  360.          this.setVisible(false);
  361.      }
  362.          public String getClick()
  363.     {
  364.         return clicked;
  365.     }
  366.          boolean opened = false;
  367.  
  368. public void setOpen(boolean open){
  369. this.opened = open;
  370. }
  371.  
  372. public Boolean isOpened(){
  373. return opened;
  374. }
  375.      public void stop()
  376.      {
  377.          System.exit(0);
  378.      }
  379.      public void run()
  380.              
  381.      {
  382.          new Menu().setVisible(true);
  383.      }
  384.     public static void main(String args[]) {
  385.         //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
  386.         /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
  387.          * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
  388.          */
  389.         try {
  390.             for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
  391.                 if ("Nimbus".equals(info.getName())) {
  392.                     javax.swing.UIManager.setLookAndFeel(info.getClassName());
  393.                     break;
  394.                 }
  395.             }
  396.         } catch (ClassNotFoundException ex) {
  397.             java.util.logging.Logger.getLogger(Menu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  398.         } catch (InstantiationException ex) {
  399.             java.util.logging.Logger.getLogger(Menu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  400.         } catch (IllegalAccessException ex) {
  401.             java.util.logging.Logger.getLogger(Menu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  402.         } catch (javax.swing.UnsupportedLookAndFeelException ex) {
  403.             java.util.logging.Logger.getLogger(Menu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  404.         }
  405.         //</editor-fold>
  406.        
  407.         java.awt.EventQueue.invokeLater(new Runnable() {
  408.             public void run() {
  409.                 new Menu().setVisible(true);
  410.             }
  411.         });
  412.     }
  413.     // Variables declaration - do not modify//GEN-BEGIN:variables
  414.     private javax.swing.JButton jButton1;
  415.     private javax.swing.JButton jButton2;
  416.     private javax.swing.JLabel jLabel1;
  417.     private javax.swing.JLabel jLabel2;
  418.     public javax.swing.JTextField playername;
  419.     // End of variables declaration//GEN-END:variables
  420. }
  421.  
  422. Menu.java:
  423.  
  424. package monster.defense;
  425. import java.io.*;
  426. import javax.swing.*;
  427. import java.awt.*;
  428.  
  429.  
  430. public class MonsterDefense{
  431.     public static void main(String args[]) throws Exception {
  432.  
  433.         Menu hm = new Menu();
  434.         hm.setTitle("Monster Defense");
  435.         hm.setLocationRelativeTo(null);
  436.         hm.setVisible(true);
  437.        // BufferedReader pdetails = new BufferedReader(new FileReader("playerdetails.txt"));
  438.        // BufferedReader inKb = new BufferedReader(new InputStreamReader (System.in));
  439.         int yum = 1;
  440.         while(yum == 1)
  441.         {
  442.             if(hm.isVisible())
  443.             {
  444.                      System.out.print("");
  445.             }
  446.             else if(!hm.isVisible())
  447.             {
  448.                 System.out.println("Button clicked. Proceeding with program.");
  449.                 yum = 2;
  450.             }
  451.         }
  452.         System.out.println("Game will launch now. Player name: "+hm.getPName());
  453.         game md = new game();
  454.        
  455.         JFrame frame = new JFrame();
  456.         frame.setTitle("Monster Defence");
  457.         frame.add(md);
  458.         frame.pack();
  459.         frame.setVisible(true);
  460.         frame.setLocationRelativeTo(null);
  461.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  462.        
  463.      
  464. }
  465. }
  466.  
  467. player.java:
  468.  
  469. package monster.defense;
  470.  
  471. import java.awt.*;
  472. import java.util.logging.Level;
  473. import java.util.logging.Logger;
  474.  
  475. /**
  476.  *
  477.  * @author Morgan
  478.  */
  479. public class player extends Entity
  480. {
  481.     private game instance;
  482.     private int xdir;
  483.     private int ydir;
  484.         private int health = 115;
  485.     private boolean passed = false;
  486.     private Rectangle box; //THIS IS THE ENEMY HITBOX
  487.     public player(game instance, int x, int y) {
  488.         super(x, y);
  489.         this.instance=instance;
  490.         w = 16; h=16;
  491.         box  = new Rectangle(x,y,w,h);
  492.     }
  493.     public int getHealth()
  494.     {
  495.         return this.health;
  496.     }
  497.     public void setHealth(int value)
  498.     {
  499.         if(value <=0)
  500.         {
  501.         health = 0;
  502.         }
  503.         else{health=value;}
  504.     }
  505.     public Rectangle getEBox()
  506.     {
  507.         return this.box;
  508.     }
  509.     public void draw(Graphics g)
  510.     {
  511.         move();
  512.  
  513.         g.setColor(Color.GREEN); //THIS IS THE ENEMY HITBOX
  514.         //box.x=this.x-48; //THESE MAKE THE HITBOX FOLLOW THE TOWER
  515.         //box.y=this.y-48;
  516.        // g.fillRect(box.x, box.y, w+20, h+20);
  517.         g.setColor(Color.RED);
  518.         g.fillOval(x,y,w,h);
  519.  
  520.     }
  521.     public boolean getPassed()
  522.     {
  523.         return passed;
  524.     }
  525.         public void drawEnemy(Graphics g) throws InterruptedException
  526.     {
  527.         if(health>0){
  528.         g.setColor(Color.GREEN); //THIS IS THE ENEMY HITBOX
  529.         box.x=this.x+5; //THESE MAKE THE HITBOX FOLLOW THE TOWER
  530.         box.y=this.y+5;//-48;
  531.         //g.setColor(Color.CYAN);
  532.         g.fillRect(box.x, box.y, 5, 5);
  533.         if(this.x<900)
  534.         {
  535.             this.x++;
  536.             box.x++;
  537.         }
  538.         else if(x==900)
  539.         {
  540.             this.x++;
  541.             box.x++;
  542.         }
  543.         else{
  544.             this.x++;
  545.             box.x++;
  546.         }
  547.          //if(!instance.getBox().intersects(box)) //INTERSECTION TEST TESTING IF THE ENEMY IS WITHIN RANGE
  548.          int ok = 1;//if(instance.getBox().x < box.x + box.width && instance.getBox().x + instance.getBox().width > box.x && instance.getBox().y < box.y + box.height && y + instance.getBox().height > box.y)
  549.         for(int i=0;i<instance.getCnt(); i++)
  550.         {
  551.          if(box.intersects(instance.getBox(i)))
  552.          {
  553.             g.setColor(Color.yellow);
  554.                 health--;
  555.             ok=0;
  556.             System.out.println(health);
  557.         }
  558.          
  559.  
  560.         }
  561.         if(ok==1)
  562.         {
  563.               g.setColor(Color.GREEN);
  564.          }
  565.         g.fillOval(x,y,w,h);
  566.         Color myColour = new Color(80, 80, 255, 127);
  567.         g.setColor(myColour);
  568.         }
  569.         else{
  570.             Color dead = new Color(0,0,0,255);
  571.             g.setColor(dead);
  572.             g.fillOval(x,y,w,h);
  573.             this.x++;
  574.         }
  575.        
  576.     }
  577.     private void move()
  578.     {
  579.         if (this.getX()>=901&&this.getXDir()==1||this.getX()<=0&&this.getXDir()==-1)
  580.         {
  581.            this.setXDir(0);
  582.         }
  583.                 if (this.getY()>=510&&this.getYDir()==1||this.getY()<=0&&this.getYDir()==-1)
  584.         {
  585.            this.setYDir(0);
  586.         }
  587.         x+=xdir;
  588.         y+=ydir;
  589.     }
  590.     public void setXDir(int value)
  591.     {
  592.         xdir = value;
  593.     }
  594.         public void setYDir(int value)
  595.     {
  596.         ydir = value;
  597.     }
  598.        
  599.         public int getXDir()
  600.         {
  601.            return xdir;
  602.         }
  603.         public int getYDir()
  604.         {
  605.             return ydir;
  606.         }
  607.        
  608.         public void setX(int value)
  609.         {
  610.             x=value;
  611.         }
  612.        
  613.         public void setY(int value)
  614.         {
  615.             y=value;
  616.         }
  617.                 public int getX()
  618.         {
  619.             return x;
  620.         }
  621.        
  622.         public int getY()
  623.         {
  624.             return y;
  625.         }
  626.    
  627. }
  628.  
  629.  
  630.  
  631.  
  632.  
  633. SAVE THEM ALL IN A FOLDER TOGETHER TO RUN :)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement