Skip to main content

Program zaliczeniowy: Gra w życie

Gra w życie.
Poniżej zamieszczam mój najnowszy programik napisany w javie. Pisałem go w NetBeans 6.1 co widać jeśli ktoś w nim pracował. Porgram umożliwia rysowanie oraz wykonanie kroku po naciśnięciu przycisku "Krok". W zrozumieniu jest raczej prosty więc jeśli komuś się przyda to bardzo dobrze;-)


 /*

* Main.java

*Gra w życie z użyciem dwóch kolorów

* Created on 7 czerwiec 2008, 19:20

*/

package grawzycie;


import java.awt.Color;

import java.awt.Graphics;


/**

*

* @author  shaman

*/

public class Main extends javax.swing.JFrame {

       /** Creates new form Main */

       public Main( ) {
             tablica = new Color[37][32];

           tymczasowa = new Color[37][32];

           for (int i = 0; i < 37; i++) {
                 for (int j = 0; j < 32; j++) {
                     tablica[i][j] = new Color(255, 255, 255);

               }
           }

           kolor = true;

           initComponents( );

           g = jPanel1.getGraphics( );
       }


       /** This method is called from within the constructor to

        * initialize the form.

        * WARNING: Do NOT modify this code. The content of this method is

        * always regenerated by the Form Editor.

        */

       @SuppressWarnings("unchecked")

       // <editor-fold defaultstate="collapsed" desc="Generated Code">

       private void initComponents( ) {

             jButton1 = new javax.swing.JButton( );

             jPanel1 = new javax.swing.JPanel( );


             setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

             setMinimumSize(new java.awt.Dimension(400, 400));

             setResizable(false);


             jButton1.setText("Krok");

             jButton1.addActionListener(new java.awt.event.ActionListener( ) {
                   public void actionPerformed(java.awt.event.ActionEvent evt) {
                       jButton1ActionPerformed(evt);
                 }
             });


             jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

             jPanel1.setMinimumSize(new java.awt.Dimension(200, 200));

             jPanel1.setPreferredSize(new java.awt.Dimension(200, 200));

             jPanel1.addMouseListener(new java.awt.event.MouseAdapter( ) {
                   public void mousePressed(java.awt.event.MouseEvent evt) {
                       jPanel1MousePressed(evt);
                 }
             });


             javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);

             jPanel1.setLayout(jPanel1Layout);

             jPanel1Layout.setHorizontalGroup(

                 jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

                 .addGap(0, 198, Short.MAX_VALUE)

             );

             jPanel1Layout.setVerticalGroup(

                 jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

                 .addGap(0, 198, Short.MAX_VALUE)

             );


             javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane( ));

             getContentPane( ).setLayout(layout);

             layout.setHorizontalGroup(

                 layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

                 .addGroup(layout.createSequentialGroup( )

                     .addContainerGap( )

                     .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

                         .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)

                         .addComponent(jButton1))

                     .addContainerGap( ))

             );

             layout.setVerticalGroup(

                 layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

                 .addGroup(layout.createSequentialGroup( )

                     .addContainerGap( )

                     .addComponent(jButton1)

                     .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

                     .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)

                     .addContainerGap( ))

             );


             pack( );
         }// </editor-fold>


      private void jPanel1MousePressed(java.awt.event.MouseEvent evt) {                                     
        // TODO add your handling code here:




         int x = evt.getX( );

         System.out.println("x = " + x);

         x = x - x % 10;

         System.out.println("x = " + x);

         int iX = x / 10;

         System.out.println("iX = " + iX);


         int y = evt.getY( );

         System.out.println("y = " + y);

         y = y - y % 10;

         System.out.println("y = " + y);

         int iY = y / 10;

         System.out.println("iY = " + iY);


         if (kolor) {
               tablica[iX][iY] = jeden;

         } else {

             tablica[iX][iY] = dwa;
         }

         kolor = !kolor;




         g.setColor(tablica[iX][iY]);

         g.fillRect(x, y, 7, 7);
      }                                    


      private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:

         //tablica przechowująca ilość sąsiadów w koorze 1 i 2

         IlośćKolorów sasiedzi[ ] = new IlośćKolorów[3];

         sasiedzi[1] = new IlośćKolorów( );

         sasiedzi[2] = new IlośćKolorów( );

         //ilość żywych sąsiadów

         int zywi = 0;


         //pętle sprawdzające każdy element tablicy

         for (int i = 0; i < 37; i++) {
               for (int j = 0; j < 32; j++) {

                   //ilosc zywych sąsiadów

                   zywi = 0;

                   sasiedzi[1].ilość = 0;

                   sasiedzi[2].ilość = 0;

        //górny lewy róg

                   if (i > 0) {
                         if (j > 0) {
                             if (tablica[i - 1][j - 1] == jeden) {
                                 sasiedzi[1].ilość++;

                               zywi++;

                           } else if (tablica[i - 1][j - 1] == dwa) {

                               sasiedzi[2].ilość++;

                               zywi++;
                           }
                       }
                   }


                   //lewy bok

                   if (i > 0) {
                         if (tablica[i - 1][j] == jeden) {
                             sasiedzi[1].ilość++;

                           zywi++;

                       } else if (tablica[i - 1][j] == dwa) {

                           sasiedzi[2].ilość++;

                           zywi++;
                       }

                   }


                   //dolny lewy róg

                   if (i > 0) {
                         if (j < 31) {
                             if (tablica[i - 1][j + 1] == jeden) {
                                 sasiedzi[1].ilość++;

                               zywi++;

                           } else if (tablica[i - 1][j + 1] == dwa) {

                               sasiedzi[2].ilość++;

                               zywi++;
                           }
                       }
                   }


                   //nad badaną

                   if (j > 0) {
                         if (tablica[i][j - 1] == jeden) {
                             sasiedzi[1].ilość++;

                           zywi++;

                       } else if (tablica[i][j - 1] == dwa) {

                           sasiedzi[2].ilość++;

                           zywi++;
                       }

                   }


                   //pod badaną

                   if (j < 31) {
                         if (tablica[i][j + 1] == jeden) {
                             sasiedzi[1].ilość++;

                           zywi++;

                       } else if (tablica[i][j + 1] == dwa) {

                           sasiedzi[2].ilość++;

                           zywi++;
                       }

                   }



                   //górny prawy róg

                   if (i < 36) {
                         if (j > 0) {
                             if (tablica[i + 1][j - 1] == jeden) {
                                 sasiedzi[1].ilość++;

                               zywi++;

                           } else if (tablica[i + 1][j - 1] == dwa) {

                               sasiedzi[2].ilość++;

                               zywi++;
                           }
                       }
                   }


                   //prawy bok

                   if (i < 36) {
                         if (tablica[i + 1][j] == jeden) {
                             sasiedzi[1].ilość++;

                           zywi++;

                       } else if (tablica[i + 1][j] == dwa) {

                           sasiedzi[2].ilość++;

                           zywi++;
                       }

                   }


                   //dolny lewy róg

                   if (i < 36) {
                         if (j < 31) {
                             if (tablica[i + 1][j + 1] == jeden) {
                                 sasiedzi[1].ilość++;

                               zywi++;

                           } else if (tablica[i + 1][j + 1] == dwa) {

                               sasiedzi[2].ilość++;

                               zywi++;
                           }
                       }
                   }


                   //jesli spełnia warunki życia

                   if (zywi != 2 && zywi != 3) {
                         tymczasowa[i][j] = martwa;


                   } else {

                       tymczasowa[i][j] = tablica[i][j];

                   }


                   //jesli ożywa

                   if (zywi == 3 && tablica[i][j].equals(martwa)) {
                         if (sasiedzi[1].ilość >= 2) {
                             tymczasowa[i][j] = jeden;

                       } else if (sasiedzi[2].ilość >= 2) {

                           tymczasowa[i][j] = dwa;
                       }

                       System.out.println("ozywa" + "jeden" + sasiedzi[1].ilość);

                       System.out.println("ozywa" + "dwa" + sasiedzi[2].ilość);
                   }

               }
           }


           //przepisanie tablicy tymczasowej do głównej

           for (int i = 0; i < 37; i++) {
                 for (int j = 0; j < 32; j++) {

                     tablica[i][j] = tymczasowa[i][j];

                     ///

                     //rysowanie tablicy!!!!

                     g.setColor(tablica[i][j]);


                     g.fillRect(i * 10, j * 10, 7, 7);
                 }
             }

          }                                        


             /**

             * @param args the command line arguments

             */

             public static void main(String args[ ]) {
                   java.awt.EventQueue.invokeLater(new Runnable( ) {
                       public void run( ) {
                           new Main( ).setVisible(true);
                     }
                 });
             }


             // Variables declaration - do not modify

             private javax.swing.JButton jButton1;

             private javax.swing.JPanel jPanel1;

             // End of variables declaration

             

             //tablica przechowująca stany komórek - ich kolory

             private Color tablica[ ][ ],tymczasowa[ ][ ]; 

             private boolean kolor = true; 

             private Color jeden = new Color(255,0,0);

             private Color dwa = new Color(0,255,0);

             private Color martwa = new Color(255,255,255);

             private Graphics g;

             //klasa przechowująca ilość sasiadów w danym kolorze

             private class IlośćKolorów{
                   public int ilość;

                 IlośćKolorów( ){
                       ilość = 0;
                 }
                  }

             
          }


          Kod wygenerowany za pomocą programu: Code Generator

          Comments

          1. Podziękowania i gratulacje dla Autora. Realizacja tej samej gry w C++ Builderze jest przedstawiona w książce Andrzeja Stasiewicza "C++ Builder całkiem inny świat", ma więcej możliwości, ale korzysta z bibliotecznego komponentu TGridBag, którego odpowiednika w Javie nie ma (albo go nie znalazłem). Właśnie się zastanawiałem, jak to samo zrealizować w Javie

            ReplyDelete
          2. Miło przeczytać taki komentarz:)
            Pozdrawiam!

            ReplyDelete

          Post a Comment

          Comments:

          Popular posts from this blog

          Course Review: The Bitfountain iOS 8 with Swift Immersive

          This is second big iOS learning project. For first one read iOS Programming book review. As I only have two of them done I have to compare them somehow.

          I am mindful that it took me a really long time to finish it (since last autumn). For a couple of months this year I didn't even have the internet to learn it, so it could not be helped. But last half of the June I've spent watching the videos every day and managed to finish it before any new internet problems.

          So how was it?
          In my opinion, it's great if you're starting out. There are a lot of basics, and seeing how to do things in XCode just makes your learning much easier than looking at the photos in the book. On the other hand, learning is more shallow and it is much easier to just follow the videos and learn only the basics without bigger picture about iOS SDK. I somehow missed more challenging exercises (even though I don't like to do them ;)

          Length:
          Course it pretty long but many videos are quite short (1-2…

          How to Learn when Life is Short

          I haven't really think this through but I have read really interesting articles recently and I just wanted to write for myself later.

          Life is Short by Paul Graham

          It's just that, learn from people older that you what is most important, and that life actually is short...

          Instead of Goals or Resolutions, Try Creating Rules by Leo Babuta

          In the time of New Year Resolutions, it's good to read something that is proposing different way of achieving things. Still I see much more value in habits than setting goals. But...

          The Easy Way To Learn Hard Stuff by Per Harald Borgen
          It's something that I read from time to time and I know it works sometimes for me. The things I learn then are really learned and something Jakub Wasilewski  has told me many times to do. Still it's uncomfortable and for some reason, I have failed to use this method more than once or twice. Writing it here so maybe I can think about it more and figure out how to do that more often.

          Towards an understandin…

          Hero's Journey in Presentations

          Artur Skowroński recommended me: Want a Better Pitch? Watch This. by Andy Raskin and I think it is so great and applicable to all kinds of talks that I want to help it get more popular.
          So the plan of presentation is going to follow these steps: Enemy - ProblemWhy now? - call to actionShow how the world will look like without the problemProblemsEvidence that you fixed the problem The image at the top is because it reminds me of Hero's Jurney. It has fewer steps but there is a lot of similarities. Especially #3 made me realize that grand vision of the future is something that I should have used in my talks.  The result at the start of the presentation makes a lot of sense actually. Everyone already knows that I speak about something because I probably fixed it and if you tell about it at the end then it might be hard for some people to see the bigger picture in the solution you're going to present.