Who's undercover __socket?

Source: Internet
Author: User
Tags addall getmessage prepare create database

who is the undercover game believe that everyone has played or seen, written in the game is nothing more than the socket message, sent to send, the main message is the time to send the logic to be able to become a fun little game:




Login interface (database to store undercover number, points)

Start the game:
Server generates current speaker serial number (random number)

message{
int type;
String name;//Sender's undercover number
//map<int,string> map;//prep person serial number and undercover number
int id;//current Speaker serial number (Prep)
int maxnum;// Maximum number of persons to prepare
String message;//General Chat message list
total;//Total number of rooms list
prepare;//Current prepare Person ID lists (civilian deaths update)
int Undercover //Lying base
list id_list;//has spokesman
List vote;//Maximum number of speakers ID list
int id_vote;//cast
String word;//undercover word
Map said_map;//words and IDs
}

Type
0:-request to enter the room, Maxnum

1: Server sent into the room message, total,message

2:-Send the chat message and receive the speech Word message, Id,name,message (the server receives the automatic forwarding

to the client)

3:-request to prepare the game, name

4: The server sends ready messages, Prepare,maxnum

5: The server sends the currently randomly obtained spokesperson's personal information to the client, map

6: The server sends a request to vote message,

7:-send a poll message, id_

7: The server sends the message after the speech, the judge, messages
Server sent found/not found undercover (deaths) message

8:-send a poll result message to the server to judge, Id_vote

9: The server sends a vote to determine the result message (including penalties),
Find Undercover (clients will be ready to clear the number of people after receipt, restart to prepare the game)
No undercover found (send Message 4, assign the vote to prepare)

10: The client receives the speech message (the operation completes on the client)

11: The server sends the initial ID to the client, and the Prepare_list

12: The server sends the game end message, prepares the number to clear zero

13: The server sends undercover words, the client pops up the display Word window

14:--client owners have finished speaking

15: Send points to increase success message

16: Send a bystander message

Note: There is no type of write message in various types of use, please write code to pay attention to the use of
Server End:

SQL class: Store user basic information (undercover name, points), pairs of words ResultSet sqlquery (String sql);//Search undercover and undercover name void Sqlupdate (String sql);//Register User server class:
Service End-process management client; void StartServer ();//thread management, providing socket to each client thread void Sendmsgtoall (msg); Statistical poll results Map<int,int> Map;//id and Votes Serverthread class: Receive message void sendmsg (msg);//To be supplied to the server class using//
Provides various IO stream objects to the message processing class Judge, Judge class: (Judge the user deaths, judge the civilian and the undercover wins)//voterule invokes Judge (msg); Return 0 (civilian win), return-1 (same number of votes), return undercover number (undercover win), return civilian number (civilian deaths)//Return-2 (No vote, game over) int GetResult (List vote,list prepare,int

Undercover);

Startgamerule class: How to start the game//Receive Message 3 o'clock Serverthread call Startgamerule (socket Socket,serverthread in the various need to use the flow);

Normaloperationrule class: How the Normal game//Received message 2 o'clock Serverthread call Normaloperationrule (socket Socket,serverthread in the various need to use the flow);

Punishrule class: How to punish the failed party//judge class call Punishrule (the various streams provided in the Socket Socket,judge);

Voterule class: After voting processing rule/Receive Message 9 O'Clock Serverthread call Voterule (socket Socket,serverthread in the various need to use the flow); Message class: (the user enters the room news, enters the game message, prompts a user to send the description statement message, the user sends the description statement outdated message, the user votes the message, the voting outdated message, the voting result class, the user deaths message, the game end message, the punishment message)

Client side:

Clientloginframe class: (Login, register)
//Call Clientmianframe class
 Setroom class:  Room Settings Interface
//Call mainframe   
 mainframe class:     Game Main Interface
MainFrame (Socket Socket,clientthread CT);
 Clientthread class:       client thread
//Send/Receive Message
 Vote class:             voting interface, how users vote, get the voting result
int vote ();

Database design

Create database undercover character set UTF8;

CREATE TABLE user (
    ID int (5),
    name varchar (a),
    score int (6)
);
Insert into user values (1, ' Yang Bijia ');
Update user set Name= ' Yang Bijia ' where id=1;
   Delete from user where id=7;
select * from user;

CREATE TABLE words (
    ID int (5),
    name1 varchar (),
    name2 varchar ()
);
select * from words;


insert into words values (5, ' eyebrows ', ' eyelashes '), (2, ' flirting ', ' flirt '), (3, ' bathtub ', ' fish
Jar '), (4, ' electric car ', ' motorcycle trailer ');
insert into words values (1, ' Winter melon ', ' watermelon Peel '), (6, ' broom ', ' mop '), (7, ' Tasty
cola ', ' Pepsi '), (8, ' phone ', ' mobile ');
insert into words values (9, ' movies ', ' TV dramas '), (10, ' Roses ', ' Rose '), (11, ' Bao
an ', ' Bodyguard '), (12, ' Dong Yong ', ' Xu Xian '); insert into words values ( 13, ' orange ', ' orange ',
(14, ' policeman ', ' catch Fast '), (15, ' writer ', ' screenwriter '), (16, ' pillow ', ' tuck ');
insert into words values (17, ' classmate ', ' Deskmate '), (18, ' head teacher ', ' Counselor '), (19, ' small
cage bag ', ' dumpling soup ');
insert into words values (20, ' bag of Blue Sky ', ' Detective Dee '), (21, ' Condor's Companion ', ' Tianlong eight
'), (22, ' Ten-side ambush ', ' embattled ');
insert into words values (23, ' Big White Rabbit ', ' Golden Monkey '), (24, ' Donnie ', ' Jet Li ');

Server processing messages

public class Serverthread extends Thread {socket socket;
    Server ser;
    InputStream is;
    OutputStream OS;
    ObjectInputStream Ois;
    ObjectOutputStream Oos;
    String s;

    int id;
        Public Serverthread (socket socket, server server) {this.socket = socket;

        This.ser = server;
            try {os = Socket.getoutputstream ();
            is = Socket.getinputstream (); SYSTEM.OUT.PRINTLN ("Build the input/output stream ...")
            ");
            Oos = new ObjectOutputStream (OS);
            OIS = new ObjectInputStream (IS); SYSTEM.OUT.PRINTLN ("Build the object stream ...")
        ");
        catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();
    } this.start (); @Override public void Run () {a try {while (true) {The message message = (Mess
                Age) Ois.readobject (); System.out.println ("received message" + message.gettype () + ", message.getname () ="+ message.getname ());

                    Login message if (message.gettype () = = 7) {String name = Message.getname ();
                    SqlConnection conn = new SqlConnection ();

                    String sql = "SELECT * from user";
                        try {ResultSet rs1 = conn.sqlquery (sql);
                        Boolean flag = false;
                            while (Rs1.next ()) {int id = rs1.getint ("id");
                            String names = rs1.getstring ("name");
                            int score = Rs1.getint ("score");
                                if (Names.equals (Message.getname ())) {s = name; System.out.println ("Undercover number:" + name +) login successful.
                                Integral: "+ score);
                      Ser.sendmsgtoall (New message (7, NULL, 1, score,                  NULL, NULL, NULL, ser.maxnum, NULL, NULL, 0, NULL, NULL);
                                System.out.println ("7 messages have been sent to the client");
                                Flag = true;
                            Break } if (!flag) {System.out.println ("Undercover number:" + N Ame + "Login failed.
                            "); Ser.sendmsgtoall (New message (7, NULL, 2, 0, NULL, NULL, NULL, 0, NULL, NULL, 0, NULL,
                            NULL));
                        System.out.println ("7 messages have been sent to the client");
                    } conn.closeconn (); catch (Exception e) {//TODO auto-generated catch block E.printstacktra
                    CE ();
                    }//Register message if (message.gettype () = = 12) {String name = Message.getname ();
                    SqlConnection conn = new SqlConnection ();
                        try {String SQL1 = ' Select id from user ';
                        ResultSet rs = conn.sqlquery (SQL1);
                        int len = 1;
                        while (Rs.next ()) {len++;
                        int score = 200;
                        String sql = "INSERT into user values (' + len +" ', ' "+ name +" ', ' + score + "]);
                        int i = conn.sqlupdate (sql); if (i = = 1) {System.out.println ("Undercover number: + Name +") registered successfully.
                            ");  Ser.sendmsgtoall (New Message (a), NULL, 1, 0, NULL, NULL, NULL, 0, NULL, NULL, 0, NULL,
                        NULL)); else {System.out.println (undercover: + name +) registration failed.
    ");                        Ser.sendmsgtoall (New Message (A, NULL, 2, 0, NULL, NULL, NULL,
                        0, NULL, NULL, 0, NULL, NULL);
                    } conn.closeconn (); catch (Exception e) {//TODO auto-generated catch block E.printstacktra
                    CE ();
                    }//Request to enter room if (message.gettype () = = 0) {//Bystander message
                    System.out.println ("Enter the room when ser.flag=" + Ser.flag); Ser.sendmsgtoall (New message (), NULL, Ser.flag, 0, NULL, NULL, NULL, 0, NULL, NULL, 0, NULL,
                    NULL));
                    System.out.println (Message.getname () + "request to enter the room");
                    List total_copylist = new arraylist<string> ();
                    Total_copylist.addall (ser.total);
                Total_copylist.add (Message.getname ());    Ser.total = total_copylist;
                    Send integral scoreoperation so = new Scoreoperation (Ser);
                    for (int i = 0; i < ser.total.size (); i++) {int score = So.queryscore (s);  Ser.sendmsgtoall (New Message (), Message.getname (), score, 0, NULL, NULL, NULL, 0, NULL, NULL,
                    0, NULL, NULL));
                        } if (ser.total.size () = = 1) {ser.maxnum = Message.getmaxnum ();
                                Ser.sendmsgtoall (New Message (1, "Judge", 0, message. Getmaxnum (), Message.getname () + "Enter the room, you are the first person", Ser.total, ser.prepare, 0, NULL,
                    NULL, ser.play, NULL, NULL));
                        else {System.out.println ("request to enter the room, ser.maxnum=" + ser.maxnum); Ser.sendmsgtoalL (New Message (1, "Judge", 0, Ser.maxnum, message.getname () + "Enter the room", Ser.total,
                    Ser.prepare, 0, NULL, NULL, ser.play, NULL, NULL); }//Chat message if (message.gettype () = = 2) {if (mess
                                Age.getid () = = 0) ser.sendmsgtoall (New Message (2, Message.getname (), 0,
                    0, Message.getmessage (), NULL, NULL, 0, NULL, NULL, 0, NULL, NULL); else Ser.sendmsgtoall (New message (2, message.getname (), mess

                Age.getid (), 0, message.getmessage (), NULL, NULL, 0, NULL, NULL, 0, NULL, NULL);
                            //Request to prepare the game if (message.gettype () = = 3) {System.out . Println ("================== preparation ====================");
                    ser.temp++;
                    List prepare_copylist = new arraylist<string> ();
                    Prepare_copylist.addall (Ser.prepare);
                    Prepare_copylist.add (ser.temp);
                    Ser.prepare = prepare_copylist;
                    Ser.play = Ser.prepare.size (); for (int i = 0; i < ser.prepare.size (); i++) System.out.println ("ser.prepare=" + ser.prepare.ge
                    T (i));
                    Ser.map.put (Ser.temp, Message.getname ());
                            Send ID to client and prepare person Ser.sendmsgtoall (new message (one, NULL, 0, 0, NULL, NULL,
                    Ser.prepare, 0, NULL, NULL, ser.play, NULL, NULL); Ser.sendmsgtoall (New Message (2, Message.getname (), 0, 0, "I'm Ready", NULL, NULL, 0, NULL, NULL, 0
                    , NULL, NULL)); SYSTEM.OUT.PRINTLN ("Send prepare message, ser.temp=" + ser.temp

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.