Rooster Game / Old Game with Application Level Protocol

Asked

Viewed 959 times

1

General Information

I’m using the Notepad++.

I intend to have the program of Tic-tac-toe fully operational.

Replicating the problem

First execution 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. IE, with these commands above opens a new window of the name server "Tic Tac Toe Server" With the message "Tictactoeserver is running."

Then I open a new window Command Prompt (Command Prompt), for the client. I enter the folder containing all the code (the 5 programs: client, server, player, protocol and client.html)

Sequentially, type on command line: appletviewer TicTacToeClientProtocolo.html.

Opens new client window, with graphical interface of 3x3 rooster game. The following message is then returned: "Started applet".

When I right-click on one of the Rooster Game squares, the message appears "Wait for your turn" which means "Wait for your shift". If you select another box, a new message will appear to say again, "Wait for your turn".

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)

Which corresponds to the following line:

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

So something I’m doing wrong; I also don’t know how to activate 'X' and 'O', in the squares, I don’t know if it’s by mouse button, if by keyboard.

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

You might have to include localhost but I’m not getting it either, so it’s for applications and not applet.


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();
    }
}

Tictactoeclientprotocol.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);
    }
}

Java player.

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);
    }

}

Java protocol.

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>
  • 4

    For those who don’t know, in Portugal, "Tic-tac-toe" refers to what is known as "Tic-tac-toe" in Brazil. E "Tictactoe" is the English name of the same game. Maybe it helps someone to help. But it will certainly increase your vocabulary! P

No answers

Browser other questions tagged

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