Old Game / Cock Game with Application Level Protocol

1

General Information

I'm using Notepad ++ .

I plan to have the Game of the Rooster program fully functional.

Replicating the problem

First I run the TicTacToeServerProtocol this way, using a plugin:

cd "$(CURRENT_DIRECTORY)"
javac $(FILE_NAME)
java -classpath "$(CURRENT_DIRECTORY)" "$(NAME_PART)" 5000

So far so good, I think. that is, with these commands above opens a new server window named " Tic Tac Toe Server " With the message " TicTacToeServer is running. "

Then I open a new Command Prompt window, for the client . I go into the folder that contains all the code (the 5 programs: client , server , player , protocol in> client.html )

Sequentially, I type in the command line: appletviewer TicTacToeClientProtocolo.html .

Open new client window, with the graphic interface of the 3x3 rooster game. The following message is then returned: " applet started ".

When I right-click on one of the rows of the Rooster game, the message "Wait for your turn" is displayed, which means "Wait for your turn" > ". If you select another square, a new message will appear saying "Wait for your turn again."

At the same time in the client window the following message appears:

"java.security.AcessControlException:acess denied ("java.net.SocketPermission" "127.0.0.1:5000" "connect,resolve" at java.security.AcessControlContext.checkPermission(AcessCoOntrolContext.java:457)
at TicTacToeClientProtocolo.start(TicTacToeClientProtocolo.java:69)

That corresponds to the following line:

connection  = new Socket(InetAddress.getByName("localhost"), 5000 );

Therefore I am doing something wrong; I also do not know to activate the 'X' and 'O', in the quadriculas, I do not know if it is by mouse button, if by keyboard.

I may be doing the procedure incorrectly. Or until the command line code is incomplete.

Codes

TicTacToeServerProtocolo.java

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.net.*;
import java.io.*;

public class TicTacToeServerProtocolo extends JFrame 
{
    private ServerSocket server = null;
    private TextArea output = null;
    private JScrollPane sp  = null;
    private Player players[] = null;
    private int numberOfPlayers;
    private int currentPlayer;
    private byte board[];
    private boolean gameOver = false;
    private char winner = ' ';          // '-' -> empate; 'X' -> ganhou o jogador 'X', 'O' -> ganhou o jogador 'O'

    public TicTacToeServerProtocolo () 
    {
        super( "Tic-Tac-Toe Server" );
        Container cont = getContentPane();
        board = new byte[9];
        players = new Player[2];
        currentPlayer = 0;
        try
        {
            server = new ServerSocket(5000, 2 );
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
            System.exit( 1 );
        }
        output = new TextArea(10, 30);
        output.setEditable(false);
        JScrollPane sp = new JScrollPane(output);
        cont.add( "Center", sp);

        display("Tic-Tac-Toe Server running.");

        addWindowListener(new ProcessaJanela());
        setVisible(true);
        pack();
    }

    public void execute() 
    {
        for ( int i = 0 ; i < players.length; i++ ) 
        {
            try 
            {
                players[i] = new Player( server.accept(), this, i );
                players[i].start();
                ++numberOfPlayers;
            } 
            catch ( IOException e) 
            {
                e.printStackTrace();
                System.exit( 1 );
            }
        }
        setTurn();
    }

    public int getNumberOfPlayers() 
    {
        return numberOfPlayers;
    }

    public int getCurrentPlayer() 
    {
        return currentPlayer;
    }

    public int getWinner() 
    {
        return winner;
    }

    public boolean getGameOver()
    {
        return gameOver;
    }

    public void setTurn()
    {
        try
        {
            players[currentPlayer].setTurn("OK");
            players[(currentPlayer == 0 ? 1 : 0 )].setTurn("NOK");
        }
        catch (Exception e)
        { 
            e.printStackTrace();
        }
    }

    public void setRes()
    {
        try
        {
            players[0].setRes(winner);
            players[1].setRes(winner);
        }
        catch (Exception e)
        { 
            e.printStackTrace();
        }
    }

    public void setGameOver(boolean status)
    {
        gameOver = status;
    }

    public void display( String s ) 
    {
        output.append( s + "\n" );
    }

    public boolean validMove( int loc, int player ) 
    {
        if( player != currentPlayer ) return false;

        if ( !isOccupied( loc ) ) 
        {
            board[loc] = (byte)(currentPlayer == 0 ? 'X': 'O' );
            currentPlayer = ++currentPlayer % 2;
            players[ currentPlayer ].otherPlayerMoved( loc );
            if (gameOver())
            {
                System.out.println("Winner is "+winner+".");
            }
            else setTurn();
            return true;
        }
        return false;
    }

    public boolean isOccupied( int loc ) 
    {
        if( board[loc] == 'X' || board[loc] == 'O' ) return true;
        return false;
    }

     public boolean contentIsEqual( int i, int j, int k ) 
    {
        if( board[i] != 0 && board[i] == board[j] && board[j] == board[k]) 
        {
            winner = (char)board[i];
            return true;
        }
        return false;
    }

    public boolean gameOver() 
    {   
        // em linha
        if ( contentIsEqual(0, 1, 2) || contentIsEqual(3, 4, 5) || contentIsEqual(6, 7, 8) ) return true;

        // em coluna
        if ( contentIsEqual(0, 3, 6) || contentIsEqual(1, 4, 7) || contentIsEqual(2, 5, 8) ) return true;

        // em diagonal
        if ( contentIsEqual(0, 4, 8) || contentIsEqual(2, 4, 6) ) return true;

        // tabuleiro cheio
        int i = 0;
        for (i = 0; i < board.length; i++) if (!isOccupied(i)) break;
        if (i == board.length) { winner = '-'; return true;}

        return false;
    }

    class ProcessaJanela extends WindowAdapter
    {
        public void windowClosing( WindowEvent event ) 
        {
            setVisible(false);
            setGameOver(true);
            System.exit(0);
        }
    }; 

    public static void main( String args[] ) 
    {
        JFrame.setDefaultLookAndFeelDecorated(true);
        TicTacToeServerProtocolo game = new TicTacToeServerProtocolo();
        game.execute();
    }
}

TicTacToeClientProtocolo.java

//import java.applet.Applet;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;

public class TicTacToeClientProtocolo extends JApplet implements Runnable //JFrame
{
    Socket connection           = null;
    ObjectInputStream input     = null;
    ObjectOutputStream output   = null;
    Thread inputThread          = null;
    Square board[][]            = null;
    Square currentSquare        = null;
    JButton close               = null;
    JTextField id               = null;
    JTextArea display           = null;
    JScrollPane sp              = null;
    JPanel north                = null;
    JPanel center               = null;
    JPanel south                = null;
    boolean done                = false;
    boolean myTurn              = false;
    char myMark;

    public void init() 
    {
        JPanel sq = null;
        Container cont = getContentPane();
        cont.setLayout( new BorderLayout() );
        id = new JTextField(); 
        id.setEditable( false );
        cont.add("North", id );
        center = new JPanel();
        center.setLayout(new GridLayout(3, 3, 0, 0));
        board = new Square[3][3];
        TrataRato tr = new TrataRato();
        for( int row = 0; row < board.length ; row++ ) 
        {
            for ( int col = 0 ; col < board[row].length ; col++ ) 
            {
                board[row][col] = new Square();
                board[row][col].addMouseListener(tr);
                sq = new JPanel(new FlowLayout()); 
                sq.add(board[row][col]);
                center.add( sq );
            }
        }
        cont.add("Center", center); 

        display = new JTextArea(4, 20);
        display.setEditable( false );
        sp = new JScrollPane(display);
        close = new JButton("Close");
        close.addActionListener(new TrataBotao());
        close.setAlignmentX(Component.CENTER_ALIGNMENT);
        south = new JPanel();
        south.setLayout(new BoxLayout(south, BoxLayout.Y_AXIS));
        south.add(sp);
        south.add(close);
        cont.add( "South", south ); 
    }

    public void start() 
    {
        try 
        {
            connection  = new Socket(InetAddress.getByName("localhost"), 5000 );
            output      = new ObjectOutputStream(connection.getOutputStream());
            input       = new ObjectInputStream(connection.getInputStream());
            inputThread = new Thread( this );
            inputThread.start();
            MsgIdt msg = new MsgIdt();
            msg.envia(output);
            System.out.println(msg);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public void run() 
    {
        try 
        {
            while( !done ) 
            {
                processaMsg(Protocolo.recebe(input));
            }
        }
        catch( Exception e ) 
        {
            e.printStackTrace();
        }
        setVisible(false);
    }

    public void processaMsg(Protocolo msg)  throws Exception
    {
        if(msg instanceof MsgIdt)
            processaMsgIdt((MsgIdt)msg);
            else if(msg instanceof MsgVez)
                processaMsgVez((MsgVez)msg);
                else if(msg instanceof MsgPos)
                    processaMsgPos((MsgPos)msg);
                        else if(msg instanceof MsgRes)
                            processaMsgRes((MsgRes)msg);         
                            else if(msg instanceof MsgFim)
                                 processaMsgFim((MsgFim)msg);         
    }

    public void processaMsgIdt(MsgIdt msg) throws Exception
    {
        //display.append(msg.toString()+"\n");
        myMark = msg.getMarca();
        id.setText("You are player \"" + myMark + "\"");    
    }

    public void processaMsgVez(MsgVez msg)  throws Exception
    {
        //display.append(msg.toString()+"\n"); 
        if (msg.getEstado().equals("OK")) myTurn = true; 
        else myTurn = false;
    }

    public void processaMsgPos(MsgPos msg)  throws Exception
    {
        //display.append(msg.toString()+"\n");
        if ( msg.getMarca() == myMark ) {
            if( msg.getEstado().equals("OK") ) 
            {
                display.append("Valid move, please wait.\n");
                currentSquare.setMark( myMark );
                currentSquare.repaint();
            }
            else if( msg.getEstado().equals("NOK") ) 
            {
                display.append("Invalid move. Try again.\n");
            }
        }
        else if(  msg.getEstado().equals("OK") ) 
        {
                int loc = msg.getPos();
                boolean found = false;
                for( int row = 0; row < board.length && !found; row++ )
                {
                    for ( int col = 0 ; col < board[row].length  && !found; col++ )
                    {
                        if( row*3+col == loc ) 
                        {
                            board[row][col].setMark( (myMark == 'X'?'O':'X') );
                            board[row][col].repaint();
                            found = true;
                        }                        
                    }
                }
                display.append("Opponent moved. Your turn.\n");                
        }       
    }

    public void processaMsgRes(MsgRes msg)  throws Exception
    {
        //display.append(msg.toString()+"\n");  
        switch (msg.getEstado().charAt(0))
        {
            case '-': display.append("Empate.\n"); break;
            case 'X': if (myMark == 'X') 
                            display.append("Parabéns, ganhou o jogo!\n"); 
                            else display.append("Perdeu o jogo...\n"); 
                        break;
            case 'O': if (myMark == 'O') 
                            display.append("Parabéns, ganhou o jogo!\n"); 
                            else display.append("Perdeu o jogo...\n"); 
                        break;      
        }
    }

    public void processaMsgFim(MsgFim msg)  throws Exception
    {
        display.append(msg.toString()+"\n");  
        if (msg.getEstado().equals("OK")) done = true;
    }


    class TrataBotao implements ActionListener
    {
        public void actionPerformed(ActionEvent evt)
        {
            try
            {
                if( evt.getSource() == close ) 
                {
                    MsgFim fim = new MsgFim(myMark);
                    fim.envia(output);
                    System.out.println(fim);
                }
            }
            catch(Exception ie) 
            {
                ie.printStackTrace(); System.exit(1);
            }
        }
    }

    class TrataRato extends MouseAdapter
    {
        public void mouseReleased(MouseEvent evt)
        {
            if (!myTurn)
            {
                display.append("Wait for your turn.\n");
                return;
            }
            for( int row = 0; row < board.length ; row++ ) 
            {
                for ( int col = 0 ; col < board[row].length ; col++ ) 
                {
                    try
                    {
                        if( evt.getSource() == board[row][col] ) 
                        {
                            currentSquare = board[row][col];
                            MsgPos msg = new MsgPos(myMark, row*3+col);
                            msg.envia(output);
                            System.out.println(msg);
                        }
                    }
                    catch(Exception ie) 
                    {
                        ie.printStackTrace(); System.exit(1);
                    }
                }
            }
        }
    } /*
    public static void main(String[] args)
    {      
        new TicTacToeClientProtocolo();
    } */
}

class Square extends JLabel 
{
    char mark=' ';
    public Square() 
    {
        javax.swing.border.Border border = BorderFactory.createLoweredBevelBorder();
        setText(" ");
        setBorder(border);
        setAlignmentX(Component.CENTER_ALIGNMENT);
        setPreferredSize(new Dimension(30, 30));
    }
    public void setMark( char c ) 
    {
        mark = c;
        setText("   "+mark);
    }
}

Player.java

import java.net.*;
import java.io.*;

public class Player extends Thread 
{
    TicTacToeServerProtocolo control;
    Socket connection;
    ObjectInputStream input;    //por no protocolo as msgs serem da classe Object
    ObjectOutputStream output;
    int number;
    char mark;

    public Player(Socket s, TicTacToeServerProtocolo t, int num ) 
    {
        connection = s;
        control = t;
        number = num;
        mark = ( num == 0 ? 'X' : 'O' );

        try
        {
            input   = new ObjectInputStream( connection.getInputStream() );
            output  = new ObjectOutputStream( connection.getOutputStream() );
        }
        catch (IOException e) 
        {
            e.printStackTrace();
            System.exit(1);
        }
    }

    public void run() 
    {
        try 
        {
            while( !control.getGameOver() ) 
            {
                processaMsg(Protocolo.recebe(input));
            }
            connection.close();
        }
        catch( Exception e ) 
        {
            e.printStackTrace();
            System.exit(1);
        }
    }

    public void processaMsg(Protocolo msg) throws Exception
    {
        if(msg instanceof MsgIdt)
            processaMsgIdt((MsgIdt)msg);
            else if(msg instanceof MsgVez)
                processaMsgVez((MsgVez)msg);
                else if(msg instanceof MsgPos)
                    processaMsgPos((MsgPos)msg);
                    else if(msg instanceof MsgFim)
                        processaMsgFim((MsgFim)msg);         
    }

    public void processaMsgIdt(MsgIdt msg) throws Exception
    {
        control.display( msg.toString() );
        control.display( "Player " + (number == 0 ? 'X' : 'O') + " connected");

        MsgIdt idt = new MsgIdt(mark, "Resposta");
        idt.envia(output);
        System.out.println("processaMsgIdt: "+idt);
    }

    public void processaMsgVez(MsgVez msg)  throws Exception
    {
        control.display( msg.toString() );
    }

    public void processaMsgPos(MsgPos msg) throws Exception
    {
        control.display( msg.toString() );
        int location = msg.getPos();

        if( control.validMove( location, number ) ) 
        {
            MsgPos ans = new MsgPos(mark, location, "OK");
            ans.envia(output);
            System.out.println("processaMsgPos: "+ans);
            if (control.getWinner() != ' ') control.setRes();
        }
        else {
            MsgPos ans = new MsgPos(mark, location, "NOK");
            System.out.println("processaMsgPos: "+ans.toString());
            msg.envia(output);
            System.out.println("processaMsgPos: "+ans);
        }
    }

    public void processaMsgFim(MsgFim msg)  throws Exception //pedido do cliente para se desligar
    {   
        control.display( msg.toString() );
        control.setGameOver( true ); 
        MsgFim fim = new MsgFim(mark, "OK");
        fim.envia(output);
        System.out.println("processaMsgFim: "+fim);
    }

    public void otherPlayerMoved( int loc ) 
    {
        try
        {
            MsgPos msg = new MsgPos((mark == 'X' ? '0' : 'X'), loc, "OK");
            msg.envia(output);
            System.out.println(msg);
        }
        catch( Exception e ) 
        {
            e.printStackTrace();
        }
    }

    public void setTurn(String status) throws Exception
    {
        MsgVez vez = new MsgVez(mark, status);
        vez.envia(output);
        System.out.println("processaMsgVez: "+vez);
    }

    public void setRes(char winner) throws Exception
    {
        MsgRes res = new MsgRes(mark, ""+winner);
        res.envia(output);
        System.out.println("processaMsgRes: "+res);
    }

}

Protocol.java

import java.awt.*;
import java.net.*;
import java.io.*;

public class Protocolo implements Serializable
{
    Object arg1 = null;
    Object arg2 = null;
    String estado = null;

    public void envia(ObjectOutputStream out) throws Exception
    {
        out.writeObject(this);
    }

    public static Protocolo recebe(ObjectInputStream in) throws Exception
    {
        return (Protocolo)in.readObject();
    }
}

class MsgIdt extends Protocolo
{
    public MsgIdt() //C->S
    {
        estado=new String("Pedido"); 
    }

    public MsgIdt(char Marca, String Resposta) //S->C
    {
        arg1 = new Character(Marca);
        estado = new String(Resposta);
    }

    public char getMarca() {
        return ((Character)arg1).charValue();
    }

    public String getEstado() {
        return estado;
    }    

    public String toString() {
        if (arg1 == null) return "MsgIdt("+getEstado()+")";
        return "MsgIdt("+getMarca()+", "+getEstado()+")";
    }
}

class MsgVez extends Protocolo //S->C
{
    public MsgVez(char Marca, String Resposta)
    {
        arg1=new Character(Marca);
        estado=new String(Resposta);
    }

     public char getMarca() {
        return ((Character)arg1).charValue();
     }

    public String getEstado() {
        return estado;
    }    

    public String toString() {
        return "MsgVez("+getMarca()+", "+getEstado()+")";
    }

}

class MsgPos extends Protocolo
{
    public MsgPos(char Marca, int Pos) //C->S
    {
        arg1=new Character(Marca);
        arg2=new Integer(Pos);
        estado="Pedido";
    }

    public MsgPos(char Marca, int Pos, String Resposta) //S->C
    {
        arg1=new Character(Marca);
        arg2=new Integer(Pos);
        estado=new String("");
        estado=new String(Resposta);
    }

    public int getPos() {
        return ((Integer)arg2).intValue();
    }

     public char getMarca() {
        return ((Character)arg1).charValue();
     }

    public String getEstado() {
        return estado;
    }    

    public String toString() {
        return "MsgPos("+getMarca()+", "+getPos()+", "+getEstado()+")";
    }

}

class MsgRes extends Protocolo
{
    public MsgRes(char Marca, String Resposta) // C -> S
    {
        arg1=new Character(Marca);
        estado=new String(Resposta);
    }

     public char getMarca() {
        return ((Character)arg1).charValue();
     }

    public String getEstado() {
        return estado;
    }    

    public String toString() {
        return "MsgRes("+getMarca()+", "+getEstado()+")";
    }
}


class MsgFim extends Protocolo
{
    public MsgFim(char Marca) // C -> S
    {
        arg1=new Character(Marca);
        estado="Pedido";
    }

    public MsgFim(char Marca, String Resposta) // C -> S
    {
        arg1=new Character(Marca);
        estado=new String(Resposta);
    }

     public char getMarca() {
        return ((Character)arg1).charValue();
     }

    public String getEstado() {
        return estado;
    }    

    public String toString() {
        return "MsgFim("+getMarca()+", "+getEstado()+")";
    }
}

TicTacToeClientProtocol.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
    <HEAD>
    <TITLE>TicTacToe Client (Protocolo) </TITLE>
    </HEAD>

    <BODY>
        <CENTER>
            <APPLET CODE="TicTacToeClientProtocolo.class" WIDTH="200" HEIGHT="240">
            </APPLET>
        </CENTER>
    </BODY>
</HTML>
    
asked by anonymous 29.05.2015 / 12:56

0 answers