Memory Game Two players

Asked

Viewed 395 times

1

I have here a game of Memoria, but still have to implement play against another player.For example I start playing, if you do not hit step to Victory (another player), if you hit I have the right to try to discover another pair of cards (houses). How should I start, start assigning who plays first ? player 1 or 2.After that what I must do, each player plays in their game window, and sees the other player’s play. I can not find any code in the game net of old for two players (multiplayer). So it is very difficult for min. What I’ve done so far:

import java.awt.*;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.FlowLayout;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.ButtonGroup;
import javax.swing.JRadioButton;
import javax.swing.event.ChangeListener;
import java.util.Arrays;
import java.util.Collections;
import java.util.ArrayList;
import java.util.Random;
import java.util.Vector;
import java.util.List;
import java.applet.Applet;
import java.net.*;
import java.applet.*;
import java.io.*;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import javax.swing.JTextField;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JScrollPane;

import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.JScrollBar;

public class MemoryGame7 extends JFrame implements ActionListener
{
    ClassLoader cl = null;          
    public int delay = 1000; 

    public void Contador()
    {
    ActionListener counter = new ActionListener() 
    {
            public void actionPerformed(ActionEvent e) 
            {
        tempo++;
        TempoScore.setText("Tempo: " + tempo);
            }
    };
    new Timer(delay, counter).start();
    }

    public void updateHitMiss() 
    {
        HitScore.setText("Acertou: " + Hit);
        MissScore.setText("Falhou: " + Miss);
    PontosScore.setText("Pontos: " + Pontos);
    }

    private JFrame window = new JFrame("Jogo da Memoria");
    private static final int WINDOW_WIDTH = 500; 
    private static final int WINDOW_HEIGHT = 500;
    private JButton exitBtn, baralharBtn, solveBtn, restartBtn, maximoBtn, definicoesBtn;
    ImageIcon ButtonIcon = createImageIcon("card1.png"); //.jpg 
    private JButton[] gameBtn = new JButton[16];
    private ArrayList<Integer> gameList = new ArrayList<Integer>();
    //List<Integer> lista = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8);
    private int Hit, Miss, Pontos, Maximo;
    public int tempo = 0;   
    private int counter = 0;
    private int[] btnID = new int[2];
    private int[] btnValue = new int[2];
    private JLabel HitScore, MissScore, TempoScore, PontosScore, MaximoScore;
    private JPanel gamePnl = new JPanel();
    private JPanel buttonPnl = new JPanel();
    private JPanel scorePnl = new JPanel();
    private JTextArea textArea;
    int player;
    private DataInputStream input;
    private JTextField id;
    private boolean myTurn;
     private DataOutputStream output;
    //private Square board[][], currentSquare;

    protected static ImageIcon createImageIcon(String path) 
    {
        java.net.URL imgURL = MemoryGame7.class.getResource(path);
        if (imgURL != null) 
    {
            return new ImageIcon(imgURL);
        } 
    else  return null;
    }

    public MemoryGame7()
    {
        createGUI();
        createJPanels();
        setArrayListText();
        window.setTitle("Jogo da Memoria");
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
        Contador();

        //             INFORMAÇOES
        JPanel middlePanel=new JPanel();     
        JTextArea display=new JTextArea(12,12);
        display.setEditable(true); //false
        JScrollPane scroll=new JScrollPane(display);
        scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        middlePanel.add(scroll);
        window.add(middlePanel, BorderLayout.EAST);
        display.setText("Jogador(Player) 1");

        //             CHAT 
        middlePanel.setBorder(new TitledBorder(new EtchedBorder(),"Informações                            Chat"));        
        JTextArea display2=new JTextArea(12,12);
        display2.setEditable(true); 
        JScrollPane scroll2=new JScrollPane(display2);
        scroll2.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        middlePanel.add(scroll2);
        window.add(middlePanel, BorderLayout.EAST);
        window.pack();
        window.setLocationRelativeTo(null);
        window.setVisible(true);    
        window.resize(700,500);

        /*
        JPanel pSouth = new JPanel();
        pSouth.setLayout(new BorderLayout());
        pSouth.setPreferredSize(new Dimension(width/3, 50));*/
        //display2 = new JTextField(" ");
        //display2.setEditable(false);
        //display2.setFont(fontText);
        display2.addKeyListener(new KeyAdapter()                
                {
            public void keyPressed(KeyEvent e) 
            {  /*
                if(e.getKeyCode() == KeyEvent.VK_ENTER) 
                {
                    textArea.append(getText() + ":" + display2.getText() + "\n");

                    //scrollToBottom();
                    //posaljiPoruku(display2.getText());
                    display2.setText(" \n"); 
                     }*/
            } 
                });
                id = new JTextField();
        id.setEditable( false );

        getContentPane().add( id, BorderLayout.NORTH );
    }

    public void createGUI()
    {
        for (int i = 0; i < gameBtn.length; i++)
        {
            gameBtn[i] = new JButton(ButtonIcon);
            gameBtn[i].addActionListener(this);
        }
        HitScore = new JLabel("Acertou: " + Hit);
        MissScore = new JLabel("Falhou: " + Miss);
    TempoScore = new JLabel("Tempo: " + tempo);
    PontosScore = new JLabel("Pontos: " + Pontos);  
        exitBtn = new JButton("Sair");
        exitBtn.addActionListener(this);
        baralharBtn = new JButton("Baralhar");
        baralharBtn.addActionListener(this);
        solveBtn = new JButton("Resolver");
        solveBtn.addActionListener(this);
    restartBtn = new JButton("Recomecar");
        restartBtn.addActionListener(this);
    maximoBtn = new JButton("Pontuacoes");
        maximoBtn.addActionListener(this);
    definicoesBtn = new JButton("Definicoes");
        definicoesBtn.addActionListener(this);

    }

    public void createJPanels()
    {
        gamePnl.setLayout(new GridLayout(4, 4));
        for (int i = 0; i < gameBtn.length; i++)
        {
            gamePnl.add(gameBtn[i]);
        }
        buttonPnl.add(baralharBtn);
        buttonPnl.add(exitBtn);
        buttonPnl.add(solveBtn);
    buttonPnl.add(restartBtn);
    buttonPnl.add(maximoBtn);
    buttonPnl.add(definicoesBtn);
        buttonPnl.setLayout(new GridLayout(2, 1));
        scorePnl.add(HitScore);
        scorePnl.add(MissScore);
    scorePnl.add(TempoScore);
    scorePnl.add(PontosScore);
        scorePnl.setLayout(new GridLayout(1, 0));
        window.add(scorePnl, BorderLayout.NORTH);
        window.add(gamePnl, BorderLayout.CENTER);
        window.add(buttonPnl, BorderLayout.SOUTH);   
    }

    public void run()
    {
        // Primeiro a jogar jogador 1, segundo 2
        try 
        {          
            player=input.readChar();
            textArea.setText("You are player \""+ player + "\"");
            myTurn=(player == '1' ? true : false);
        }
        catch ( IOException e ) 
        {
            e.printStackTrace();         
        }

        // Receive messages sent to client
        while ( true ) 
        {
            try 
            {
                String s = input.readUTF();
                processMessage( s );
            }
            catch ( IOException e ) 
            {
                e.printStackTrace();         
            }
        }
    }

    public void processMessage( String s )
    {
        if ( s.equals( "Valid move." ) )  //s -> square
        {
            textArea.append( "Valid move, please wait.\n" );
             //currentSquare.setMark( myMark );
             //currentSquare.repaint();
        }
        else if ( s.equals( "Invalid move, try again" ) ) 
        {
            textArea.append( s + "\n" );
            myTurn = true;
        }
        else if ( s.equals( "Opponent moved" ) ) 
        {
            try 
            {
                int loc = input.readInt();
                 /*
                board[ loc / 3 ][ loc % 3 ].setMark(
                      ( myMark == 'X' ? 'O' : 'X' ) );
                board[ loc / 3 ][ loc % 3 ].repaint();
                      */
                textArea.append("Opponent moved. Your turn.\n" );
                myTurn = true;
            }
            catch ( IOException e ) 
            {
                e.printStackTrace();         
            }
        }
        else
        textArea.append( s + "\n" );
        textArea.setCaretPosition(textArea.getText().length() );
   }

   public void sendClickedSquare( int loc )
   {
   if ( myTurn )
        try 
        {
            output.writeInt( loc );
            myTurn = false;
        }
         catch ( IOException ie ) 
        {
            ie.printStackTrace();         
        }
   }
   /*
   public void setCurrentSquare( Square s )
   {
      //currentSquare = s;
   }
} */

    // Maintains one square on the board
    class Square extends JPanel 
    {
        private char mark;
        private int location;

        public Square( char m, int loc)
        {
            mark = m;
            location = loc;
            setSize ( 30, 30 );

            setVisible(true);
        }

        public Dimension getPreferredSize() 
        { 
            return ( new Dimension( 30, 30 ) );
        }

        public Dimension getMinimumSize() 
        {
            return ( getPreferredSize() );
        }

        public void setMark( char c ) { mark = c; }

        public int getSquareLocation() { return location; }

        public void paintComponent( Graphics g )
        {
            super.paintComponent( g );
            g.drawRect( 0, 0, 29, 29 );
            g.drawString( String.valueOf( mark ), 11, 20 );   
        }
    }

    public void setArrayListText() // gera numeros aleatorios
    { 
    List<Integer> lista = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8);
    Collections.shuffle(lista);
    gameList.addAll(lista);
    }

    public boolean sameValues()
    {
        if (btnValue[0] == btnValue[1])
        {
            return true;
        }
        return false;
    }

    public void actionPerformed(ActionEvent e)
    {
        if (exitBtn == e.getSource())
        {
            System.exit(0);
        }

        if (baralharBtn == e.getSource())
        {
            List<Integer> lista = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8);
            Collections.shuffle(lista);
            gameList.addAll(lista);
        }

        if (solveBtn == e.getSource())
        {
            for (int i = 0; i < gameBtn.length; i++)
            {   // enable false, ao clicar, não modifica o aspecto(cor) da quadricula,
        gameBtn[i].setEnabled(false); // enabled false-> cor cinzenta(padrão de fundo), true azul                
        gameBtn[i].setVisible(true); // visible true-> fica nºs visiveis
                gameBtn[i].setText("" + gameList.get(i));       
            }
        }

        for (int i = 0; i < gameBtn.length; i++)
        {           
            if (gameBtn[i] == e.getSource())
            {
                gameBtn[i].setText("" + gameList.get(i));
                gameBtn[i].setEnabled(false);
                counter++;

        if(Hit==7)
        {
                    if (counter == 2)
                    {
            gameBtn[btnID[0]].setEnabled(false);
            gameBtn[btnID[1]].setEnabled(false);
            gameBtn[btnID[0]].setVisible(false);
            gameBtn[btnID[1]].setVisible(false);
            Hit = Hit +1;
            Pontos = Pontos + 25;
                    }                   
        }

        if(Hit==8)
        {  
                    int PontuacaoMax=0;
                    PontuacaoMax=Pontos;
                    window = new JFrame(" FIM DO JOGO ");           
                    JLabel label3 = new JLabel("\n PARABENS FINALIZOU O JOGO ! TOTAL DE PONTOS: "+PontuacaoMax);    
                    int[] anArray;
                    int w=0;
                    int h=1;
                    anArray = new int[20];
                    anArray[w] = PontuacaoMax;  
                    System.out.printf("Jogo %d,",h);
                    System.out.println(" Pontuacao final : "+PontuacaoMax);
                    w++;h++;
                    window.add("Center", label3);               
                    window.show();                      
                    ImageIcon img = new ImageIcon("C:\\Users\\bruno.azevedo8\\Documents\\NetBeansProjects\\Jogo_Memoria\\resources\\fogo.jpg");
                    JLabel label = new JLabel(img);
                    window.add(label, BorderLayout.NORTH);
                    window.pack();  
                    window.setVisible(true); 
                    gameBtn[btnID[0]].setEnabled(false);
                    gameBtn[btnID[1]].setEnabled(false);
                    gameBtn[btnID[0]].setVisible(true);
                    gameBtn[btnID[1]].setVisible(true);
                    cl = getClass().getClassLoader();
                    //AudioClip audio = Applet.newAudioClip(cl.getResource("C:\\Users\\bruno.azevedo8\\Documents\\NetBeansProjects\\Memoria\\Jogo_Memoria\\resources\\bottle-open.wav"));
                    //audio.play();                 
                }

                if (counter == 3)
                {               
                    if (sameValues())
                    {
                        gameBtn[btnID[0]].setEnabled(false);
                        gameBtn[btnID[1]].setEnabled(false);
                        gameBtn[btnID[0]].setVisible(true);
                        gameBtn[btnID[1]].setVisible(true);
                        Hit = Hit +1;
                        Pontos = Pontos + 25;
                    }
                    else
                    {
                        gameBtn[btnID[0]].setEnabled(true);
                        gameBtn[btnID[0]].setText("");
                        gameBtn[btnID[1]].setEnabled(true);
                        gameBtn[btnID[1]].setText("");
                        Miss = Miss +1;
                        Pontos = Pontos - 5;                       
                    }
                    counter = 1; 
                }
                /*if (Pontos <= 0)
                {
                        Pontos=0;
                } */
                if (counter == 1) // na grelha identifica o 1º clique do rato
                {
                    btnID[0] = i;
                    btnValue[0] = gameList.get(i);
                }
                if (counter == 2) // na grelha identifica o 2º clique do rato(diferente do 1º)
                {
                    btnID[1] = i;
                    btnValue[1] = gameList.get(i);
                }
            }
        }

    if (restartBtn == e.getSource()) // apaga a grelha
        { 
            Hit=0;
            Miss=0;
            tempo=-1;
            Pontos=0;
            for (int i = 0; i < gameBtn.length; i++)
            {
                gameBtn[i].setText("");
                gameBtn[i].setEnabled(true);
                gameBtn[i].setVisible(true);    
            }
        }  

    if (maximoBtn == e.getSource()) //mostra melhor pontucao
        {
            window = new JFrame(" Jogo da Memoria - Melhores Pontuacoes:"); 
            int Max=0,PontuacaoMax=0;           

            //private static int maxValue(char[] chars) 
            //{
                //int  = chars[0]; 
                /*
                int[] anArray;
                anArray = new int[20];
                for (int w = 0; w < anArray.length; w++) 
                {
                    if (anArray[w]>= Max) 
                    {
                        Max = anArray[w];
                        JLabel label2 = new JLabel(" Pontuacao Maxima: "+Max);
                        window.add("Center", label2);
                    }
                }

                System.out.println(PontuacaoMax);
                JLabel label5 = new JLabel(" Pontuacao: " +PontuacaoMax );
                window.add("Center", label5); */
                //return Pontos;
            //}
            /*
            anArray[w]=0;
            int w;
            for(w=0;w<20;w++)
            {
                if (anArray[w]>=PontuacaoMax)
                {
                    PontuacaoMax=anArray[w];
                    JLabel label2 = new JLabel(" Pontuacao Maxima: "+PontuacaoMax);
                    window.add("Center", label2);
                }
            } 
            */ 
            if (Pontos >= PontuacaoMax)
            {
                PontuacaoMax = Pontos;
                JLabel label2 = new JLabel(" Pontuacao Maxima: "+PontuacaoMax); 
                //Vector<Integer> v = new Vector<>();
                //v.add(PontuacaoMax);System.out.println(PontuacaoMax);
                window.add("Center", label2);
            }
            if (Pontos < PontuacaoMax)
            {
                PontuacaoMax = Pontos;
                JLabel label2 = new JLabel(" Pontuacao Maxima: 0");         
                window.add("Center", label2);
            }    

            window.show();                      
            ImageIcon img = new ImageIcon("C:\\Users\\bruno.azevedo8\\Documents\\NetBeansProjects\\Jogo_Memoria\\resources\\trofeu.jpg");         
            JLabel label = new JLabel(img); 
            window.add(label, BorderLayout.NORTH);
            window.pack();  
            window.setVisible(true); 
        }

    if (definicoesBtn == e.getSource()) //mostra as definicoes
        {   

            definicoesBtn.addActionListener(new ActionListener()
            {    
                public void actionPerformed(ActionEvent evento)
                {    
                    window = new JFrame(" Jogo da Memoria - Definicoes:");              
                    JLabel label3 = new JLabel("Escolha Nivel Dificuldade:");           
                    window.add("West", label3);                                     
                    ImageIcon img = new ImageIcon("C:\\Users\\bruno.azevedo8\\Documents\\NetBeansProjects\\Jogo_Memoria\\resources\\definicoes.jpg");
                    JLabel label = new JLabel(img); 
                    window.add(label, BorderLayout.NORTH);
                    JPanel panel = new JPanel(new GridLayout(0, 1));
                    ButtonGroup group = new ButtonGroup();
                    JRadioButton aRadioButton = new JRadioButton(" Facil ");
                    JRadioButton bRadioButton = new JRadioButton(" Medio ");
                    JRadioButton cRadioButton = new JRadioButton(" Dificil ");

                    ChangeListener changeListener = new ChangeListener() 
                    {
                        public void stateChanged(ChangeEvent changEvent) 
                        {
                            AbstractButton aButton = (AbstractButton)changEvent.getSource();
                            ButtonModel aModel = aButton.getModel();
                            boolean armed = aModel.isArmed();
                            boolean pressed = aModel.isPressed();
                            boolean selected = aModel.isSelected();

                            aRadioButton.addActionListener(new ActionListener()
                            {
                                public void actionPerformed(ActionEvent e) 
                                {                           
                                    gamePnl.setLayout(new GridLayout(4, 4));
                                    //System.out.println("4x4");
                                }
                            });
                            bRadioButton.addActionListener(new ActionListener()
                            {
                                public void actionPerformed(ActionEvent e) 
                                {                                       
                                    JButton[] gameBtn = new JButton[18];

                                     for (int i = 0; i < gameBtn.length; i++)
                                    {
                                        gameBtn[i] = new JButton(ButtonIcon);
                                        gameBtn[i].addActionListener(this);
                                    } 

                                    gamePnl.setLayout(new GridLayout(6, 6)); /*
                                    for (int i = 0; i < gameBtn.length; i++)
                                    {
                                            gamePnl.add(gameBtn[i]);
                                    }           */                                                  
                                }
                            });
                            cRadioButton.addActionListener(new ActionListener()
                            {
                                public void actionPerformed(ActionEvent e) 
                                {                                                                                   
                                    gamePnl.setLayout(new GridLayout(5, 5));                                                
                                }
                            });
                        }
                    };
                    panel.add(aRadioButton);
                    group.add(aRadioButton);
                    panel.add(bRadioButton);
                    group.add(bRadioButton);
                    panel.add(cRadioButton);
                    group.add(cRadioButton);
                    aRadioButton.addChangeListener(changeListener);
                    bRadioButton.addChangeListener(changeListener);
                    cRadioButton.addChangeListener(changeListener);
                    window.add(panel);                      
                    window.pack();  
                    window.setVisible(true); 
                }    
            });             
        }
        updateHitMiss();
    }

    public static void main(String[] argv)
    {      
        new MemoryGame7();         
        try 
        {
            // criação do socket TCP de ligação ao servidor, o 1º argumento
            // é o nome da máquina, o 2º é o número do porto
            Socket sd = new Socket(InetAddress.getByName(argv[0]), (new Integer(argv[1])).intValue());
            // obtenção dos canais de leitura e escrita do socket
            InputStream in = sd.getInputStream();
            OutputStream out = sd.getOutputStream();
            // criação do buffer para envio e recepção de informação
            byte[] buffer = new byte[1024];
            for (;;) 
            {
                // pede a mensagem ao utilizador
                System.out.print("Introduza a mensagem: ");
                System.out.flush();
                int length = System.in.read(buffer);
                // envia ao servidor o buffer através do outputstream
                out.write(buffer, 0, length);
                out.flush();
                // se premiu return, fecho da ligação
                if (length == 1) break;
                // leitura da mensagem ecoada pelo servidor
                length = in.read(buffer);
                System.out.println(new String(buffer,0,0,length));
            }
        } 
        catch (IOException e) 
        {
                // Surgiu algum problema com a ligação ao socket
                System.out.println(e.toString());
        }
        System.out.println("ligação fechada");

    }
}  

Server:

import java.io.*;
import java.net.*;
public class ServidorMult2 
{
    protected final int DIM = 10;
    protected ServeCliente clientes[];
    protected ServerSocket SocketEscuta;
    public ServidorMult2 (int listenPort) throws IOException 
    {
        clientes = new ServeCliente[DIM];
        SocketEscuta = new ServerSocket(listenPort, DIM);
    }
    public void waitForClients()
    {
        int n = 0;
        try 
        { 
            while ( n < clientes.length )
            { 
                clientes[n] = new ServeCliente( this, SocketEscuta.accept(), n);
                clientes[n].start();
                n++;
            }
        } catch (Exception e) {e.printStackTrace();}
    }
    public static void main(String[] args)
    {
        try 
        { 
            ServidorMult2 servidor = new ServidorMult2(5013);
            servidor.waitForClients(); 
        } 
                catch (Exception e) 
        { 
            System.out.println("Erro:"); 
            e.printStackTrace(); 
        }
    }
}
class ServeCliente extends Thread 
{
    protected ServidorMult2 servidor; 
    protected Socket sockCliente; 
    protected int n; 
    protected InputStream input; 
    protected OutputStream output; 
    public ServeCliente(ServidorMult2 servidor, Socket sockCliente, int n) throws IOException 
    {
        this.servidor = servidor;
        this.sockCliente = sockCliente; 
        this.n = n;
        input = sockCliente.getInputStream();
        output = sockCliente.getOutputStream();
    }
    public void run () 
    {
        byte[] buffer = new byte[1024];
        try 
        {
            for (;;) 
            {
                int length =input.read(buffer);
                if ( length == 1 ) break;
                System.out.println("Cliente "+n+": "+new String(buffer,0,0,length));
                output.write(buffer,0,length);
            }
        }
                catch(IOException e) 
        {
            e.printStackTrace();
        } 
    } 
}
  • Is the old game or that game of matching tiles? Do you want to do it in rede right? Starts studying the Sockets java, it is very easy to implement something server/client. As for your doubt, it is very broad, it seems that you want us to do your duty, try to elaborate better.

  • It is the game of Memory (equal pieces). I have studied sockets, I have implemented client and server, but it is still incomplete.

  • I have a specific question as I show to the

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.