SHARE
TWEET

Untitled

a guest May 22nd, 2017 110 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream> // cout
  2. #include <stdlib.h> // exit
  3. #include <string.h> // bzero
  4. #include <unistd.h> // close
  5. #include <stdlib.h>
  6. #include <time.h>
  7. #include <set> // library to use sets
  8. #include <sstream>
  9. #include "pthread.h"
  10. #include <sys/types.h>
  11. #include <sys/socket.h>
  12. #include <netinet/in.h>
  13. #include <map>
  14. #include <postgresql/libpq-fe.h>
  15. #include <algorithm>
  16. #include <cstdlib>
  17. #include <arpa/inet.h>
  18.  
  19. using namespace std;
  20.  
  21. map<string, int> sockets;
  22. map<int, string> usernames;
  23. map<string,int>::iterator it;
  24. map<string, int> game;
  25. map<string,int> players;
  26. map<int,string> maximum;
  27. map<string, int> turn;
  28. map<string,int> word;
  29. map<string,int> find_word;
  30. map<string,int> trys;
  31. set<int> client_id;
  32. set<int> started;
  33. set<int>::iterator it1;
  34.  
  35. pthread_mutex_t mutex, mutex1;
  36. PGconn* conn = NULL; // The database connection
  37.  
  38. bool shut_d = false;
  39.  
  40. // initializes the database connection
  41. void initDB()
  42. {
  43.   conn = PQconnectdb("host='dbm.fe.up.pt' user='sinf17a42' password='aah.hangman' dbname='sinf17a42' port='5432'");
  44.  
  45.   if (!conn)
  46.   {
  47.     cout << "Failed to connect to the database" << endl;
  48.     exit(-1);
  49.   }
  50.  
  51.   if (PQstatus(conn) != CONNECTION_OK)
  52.   {
  53.     cout << "Failed to connect to the database" << endl;
  54.     exit(-1);
  55.   }
  56. }
  57.  
  58. // execute a query
  59. PGresult* executeSQL(string sql)
  60. {
  61.   PGresult* res = PQexec(conn, sql.c_str());
  62.   if (!(PQresultStatus(res) == PGRES_COMMAND_OK || PQresultStatus(res) == PGRES_TUPLES_OK)){
  63.     cout << "Failed to execute the command: " << sql << endl;
  64.     cout << PQresultErrorMessage(res) << '\n';
  65.     return NULL;
  66.   }
  67.  
  68.   return res;
  69. }
  70.  
  71. // close the database connection when the server stops
  72. void closeDB(){
  73.   PQfinish(conn);
  74. }
  75.  
  76. string int_to_string(int i){
  77.     std::stringstream ss;
  78.     ss << i;
  79.     std::string str = ss.str();
  80.     return str;
  81. }  
  82.  
  83. int string_to_int(string s){
  84.   int i;
  85.   istringstream iss(s);
  86.   iss >> i;
  87.   return i;
  88. }
  89.  
  90. bool writeline(int socketfd, int originfd, string line, int option){ //option 0 - "client X said...." , option 1 - write a line in a single client
  91.     string tosend;
  92.     if(!option){       
  93.         tosend = "Client " + int_to_string(originfd) + " said: " + line + "\n";
  94.         write(socketfd, tosend.c_str(), tosend.size());
  95.     }
  96.     else if(option)
  97.         write(socketfd, line.c_str(), line.size());
  98.     return true;
  99. }
  100.  
  101. bool readline(int socketfd, string &line) {
  102.   int n;
  103.   /* buffer with 1025 positions so we have space
  104.      for the string ending \0 character*/
  105.   char buffer[1025];
  106.  
  107.   /* initialized the string */
  108.   line = "";
  109.  
  110.   /* While we don't reach the end of the string
  111.      keep reading */
  112.   while (line.find('\n') == string::npos) {
  113.     // n haracters were read. if == 0 we reached the end of the string
  114.     n = read(socketfd, buffer, 1024);
  115.     if (n == 0) return false;
  116.     buffer[n] = 0; // put a \0 in the end of the buffer
  117.     line += buffer; // add the read text to the string
  118.   }
  119.  
  120.   // Remove the \r\n
  121.   line.erase(line.end() - 1);
  122.   line.erase(line.end() - 1);
  123.   return true;  
  124. }
  125.  
  126. string time_date(int socketfd){
  127.     time_t seconds = time(NULL);
  128.    
  129.     struct tm * timeinfo = localtime(&seconds);
  130.    
  131.     ostringstream oss_date,oss_hours;
  132.     oss_date << (timeinfo->tm_year + 1900) << "-" << (timeinfo->tm_mon + 1) << "-" << timeinfo->tm_mday << endl;
  133.     oss_hours << timeinfo->tm_hour << ":" << timeinfo->tm_min << ":" << timeinfo->tm_sec << endl;
  134.     string date1 = oss_date.str();
  135.     string date2 = oss_hours.str();
  136.     string date = date1 + date2;
  137.    
  138.     return date;
  139. }
  140.  
  141. void broadcast(int originfd, string line, int option){ 
  142.     for(it1 = client_id.begin(); it1 != client_id.end(); it1++){
  143.         int socketfd = *it1;
  144.         if(socketfd != originfd)
  145.             writeline(socketfd, originfd, line, option);
  146.     }
  147. }
  148.  
  149. bool private_chat(int socketfd, int originfd, string line){
  150.     string tosend;
  151.     int n=0;
  152.     PGresult* res = executeSQL("SELECT * FROM hangman.users WHERE users.username = ('" + line + "')");
  153.     for (int row = 0; row < PQntuples(res); row++){
  154.         if(sizeof(PQgetvalue(res, row, 4)) != 0 && usernames.find(socketfd) != usernames.end()){
  155.             n++;
  156.             tosend = "message: ";
  157.             writeline(originfd,originfd,tosend,1);
  158.             readline(originfd, line);
  159.             line = "User " + usernames[originfd] + " send you this private message: " + line + "\n";
  160.             writeline(socketfd, socketfd, line, 1);
  161.             break;
  162.         }
  163.         if(sizeof(PQgetvalue(res, row, 4)) != 0 && usernames.find(socketfd) == usernames.end()){
  164.             tosend = "User not connected.\n";
  165.             writeline(originfd,originfd,tosend,1);
  166.             return false;
  167.         }
  168.     }
  169.     if(!n){
  170.         tosend = "(?)Invalid username. Try again.\n";
  171.         writeline(originfd,originfd,tosend,1);
  172.         return false;
  173.     }
  174.     return false;
  175. }
  176.  
  177. bool client_logout(int socketfd){
  178.     string tosend;
  179.     if(usernames.find(socketfd) == usernames.end()){
  180.         tosend = "(?)Error doing logout!\n";
  181.         writeline(socketfd,socketfd,tosend,1);
  182.         return false;
  183.     }
  184.     if(players.count(usernames[socketfd])){
  185.         tosend = "(?)End your game first.\n";
  186.         writeline(socketfd,socketfd,tosend,1);
  187.         return false;
  188.     }  
  189.     if(usernames.find(socketfd) != usernames.end()){
  190.         sockets.erase(usernames[socketfd]);
  191.         usernames.erase(socketfd);
  192.         tosend = ">> Successful logout!\n";
  193.         writeline(socketfd,socketfd,tosend,1);
  194.         return true;
  195.     }
  196.     return false;
  197. }
  198.  
  199. bool sign_in(int socketfd){
  200.     int n = 0;
  201.     string tosend, tosend_user, tosend_pass;
  202.     if(usernames.find(socketfd) != usernames.end()){
  203.         tosend = "(?)You already have sign in.\n";
  204.         writeline(socketfd,socketfd,tosend,1);
  205.         return false;
  206.     }
  207.    
  208.     tosend = ">> Username: ";
  209.     writeline(socketfd,socketfd,tosend,1);
  210.     readline(socketfd,tosend_user);
  211.     if(sockets.find(tosend_user) != sockets.end()){
  212.         tosend = "(?)Access denied. You already have sign in other socket.\n";
  213.         writeline(socketfd,socketfd,tosend,1);
  214.         return false;
  215.     }
  216.    
  217.     PGresult* res = executeSQL("SELECT * FROM hangman.users WHERE users.username = ('" + tosend_user + "')");
  218.     for (int row = 0; row < PQntuples(res); row++){
  219.         if(sizeof(PQgetvalue(res, row, 4)) != 0){
  220.             n++;
  221.             break;
  222.         }      
  223.     }
  224.        
  225.     if(!n){
  226.         tosend = "(?)Invalid username. Try again!\n";
  227.         writeline(socketfd,socketfd,tosend,1);
  228.         return false;
  229.     }
  230.     n = 0;
  231.     tosend = ">> Password: ";
  232.     writeline(socketfd,socketfd,tosend,1);
  233.     readline(socketfd,tosend_pass);
  234.     PGresult* res1 = executeSQL("SELECT * FROM hangman.users WHERE users.password = ('" + tosend_pass + "')");  
  235.     for (int row = 0; row < PQntuples(res1); row++){
  236.         if(sizeof(PQgetvalue(res1, row, 5)) != 0){
  237.             n++;
  238.             tosend = "Successful login \n";
  239.             writeline(socketfd,socketfd,tosend,1);
  240.             sockets[tosend_user] = socketfd;
  241.             usernames[socketfd] = tosend_user;
  242.             return true;
  243.         }  
  244.     }
  245.     if(!n){
  246.         tosend = "(?)Invalid password. Try again!\n";
  247.         writeline(socketfd,socketfd,tosend,1);
  248.         return false;
  249.     }
  250.     return false;
  251. }
  252.  
  253. bool ver_admin(int socketfd){
  254.     PGresult* res = executeSQL("SELECT username FROM hangman.users WHERE admin = 'true'");
  255.     for (int row = 0; row < PQntuples(res); row++){
  256.         if(PQgetvalue(res,row,0) == usernames[socketfd])
  257.             return true;
  258.     }
  259.     return false;
  260. }      
  261.  
  262. bool insert_into_users(int socketfd, int i){
  263.     string userinfo[i], tosend;
  264.     tosend = "First name: ";
  265.     writeline(socketfd,socketfd,tosend,1);
  266.     readline(socketfd,userinfo[0]);
  267.     tosend = "Last name: ";
  268.     writeline(socketfd,socketfd,tosend,1);
  269.     readline(socketfd,userinfo[1]);
  270.     tosend = "Usernaname: ";
  271.     writeline(socketfd,socketfd,tosend,1);
  272.     readline(socketfd,userinfo[2]);
  273.     tosend = "Password: ";
  274.     writeline(socketfd,socketfd,tosend,1);
  275.     readline(socketfd,userinfo[3]);
  276.     userinfo[4] = "true";
  277.     PGresult* res = executeSQL("SELECT * FROM hangman.users WHERE users.username = ('" + userinfo[2] + "')");
  278.     if(PQntuples(res) != 0){
  279.         string tosend = "Username already exists. Try again\n";
  280.         writeline(socketfd,socketfd,tosend,1); 
  281.         return false;
  282.     }
  283.     PGresult* id = executeSQL("SELECT * FROM hangman.users");
  284.     executeSQL("INSERT INTO hangman.users VALUES ('" + int_to_string(PQntuples(id) + 1) + "', '" + userinfo[0] + "', '" + userinfo[1] + "', '" + userinfo[2] + "', '" + userinfo[3] + "', '" + userinfo[4] + "', '0')");   
  285.     tosend = "Done!\n";
  286.     writeline(socketfd,socketfd,tosend,1);
  287.     return true;   
  288. }
  289.  
  290. bool insert_into_categorys(int socketfd){
  291.     string catinfo, tosend;
  292.     tosend = ">> Category: ";
  293.     writeline(socketfd,socketfd,tosend,1);
  294.     readline(socketfd,catinfo);
  295.     PGresult* res = executeSQL("SELECT * FROM hangman.category WHERE category.name = ('" + catinfo + "')");
  296.     if(PQntuples(res) != 0){
  297.         string tosend = "Category already exists. Try again\n";
  298.         writeline(socketfd,socketfd,tosend,1); 
  299.         return false;
  300.     }
  301.     PGresult* id = executeSQL("SELECT * FROM hangman.category");
  302.     executeSQL("INSERT INTO hangman.category VALUES ('" + int_to_string(PQntuples(id) + 1) + "', '" + catinfo + "')");
  303.     tosend = ">> Done!\n";
  304.     writeline(socketfd,socketfd,tosend,1);
  305.     return true;
  306. }
  307.  
  308. bool insert_into_words(int socketfd){
  309.     int n = 0;
  310.     string wordinfo, catinfo, tosend;
  311.     tosend = ">> Word: ";
  312.     writeline(socketfd,socketfd,tosend,1);
  313.     readline(socketfd,wordinfo);
  314.     tosend = ">> Category: ";
  315.     writeline(socketfd,socketfd,tosend,1);
  316.     readline(socketfd,catinfo);
  317.     PGresult* res = executeSQL("SELECT * FROM hangman.word WHERE word.name = ('" + wordinfo + "')");
  318.     PGresult* result = executeSQL("SELECT * FROM hangman.category WHERE category.name = ('" + catinfo + "')");
  319.     if(PQntuples(res) != 0){
  320.         tosend = "Word already exists. Try again\n";
  321.         writeline(socketfd,socketfd,tosend,1); 
  322.         return false;
  323.     }
  324.     if(!PQntuples(result)){
  325.         tosend = "Insert a valid category. If you want to create a new one write \\category. \n";
  326.         writeline(socketfd,socketfd,tosend,1); 
  327.         return false;
  328.     }
  329.     PGresult* res1 = executeSQL("SELECT * FROM hangman.category"); 
  330.     for(int row = 0; row < PQntuples(res1) ; row++){
  331.         if(PQgetvalue(res1,row,1) != catinfo)
  332.             n++;
  333.         else
  334.             break;
  335.     }  
  336.     PGresult* id = executeSQL("SELECT * FROM hangman.word");
  337.     executeSQL("INSERT INTO hangman.word VALUES ('" + int_to_string(PQntuples(id) + 1) + "', '" + wordinfo + "', '" + int_to_string(n+1) + "')");
  338.     tosend = ">> Done!\n";
  339.     writeline(socketfd,socketfd,tosend,1);
  340.     return true;               
  341. }
  342.  
  343. bool info_user(int socketfd,int originfd,string line){
  344.     string tosend, c_w;
  345.     int n = 0;
  346.     PGresult* res = executeSQL("SELECT score FROM hangman.users WHERE users.username = ('" + line + "')");
  347.     for (int row = 0; row < PQntuples(res); row++){
  348.         if(sizeof(PQgetvalue(res, row, 4)) != 0){
  349.             n++;
  350.             c_w = PQgetvalue(res,0,0);
  351.             tosend = ">> User " + line + " have " + c_w + " wins.\n";
  352.             writeline(originfd,originfd,tosend,1);
  353.             break;
  354.         }      
  355.     }
  356.     if(!n){
  357.         tosend = "(?)Invalid username. Try again.\n";
  358.         writeline(originfd,originfd,tosend,1);
  359.         return false;
  360.     }
  361.     return true;
  362. }
  363.  
  364. bool online_users(int socketfd){
  365.     string tosend;
  366.     int n = 0;
  367.     if (sockets.find(usernames[socketfd]) != sockets.end()){
  368.         tosend = "-> Users online:";
  369.         writeline(socketfd,socketfd,tosend,1);
  370.         for(it = sockets.begin(); it != sockets.end(); it++)
  371.             cout << ".........." <<it->first << '-' << (int&)it->second;
  372.         for(it = sockets.begin(); it != sockets.end(); it++){
  373.             if(n == 0){
  374.                 tosend = ">> " + it->first + "\n";
  375.                 writeline(socketfd,socketfd,tosend,1);
  376.             }
  377.             else if (n != 0){
  378.                 tosend = ">> " + it->first + "\n";
  379.                 writeline(socketfd,socketfd,tosend,1);
  380.             }  
  381.             n++;
  382.         }
  383.         if(!n){
  384.             tosend = " ---None---. \n";
  385.             writeline(socketfd,socketfd,tosend,1);
  386.             return false;
  387.         }
  388.         return true;
  389.     }  
  390.     else{
  391.         tosend = "(?)Error. Need to login first.\n";
  392.         writeline(socketfd,socketfd,tosend,1);
  393.         return false;
  394.     }  
  395. }  
  396.  
  397. bool client_off(int socketfd){
  398.     players.erase(usernames[socketfd]);
  399.     turn.erase(usernames[socketfd]);
  400.     sockets.erase(usernames[socketfd]);
  401.     usernames.erase(socketfd);
  402.     close(socketfd);   
  403.     return true;
  404. }      
  405.  
  406. bool stdwn(){
  407.     for(it1 = client_id.begin(); it1 != client_id.end(); it1++){
  408.         int socketfd = *it1;
  409.         close(socketfd);
  410.     }
  411.     shut_d = true;
  412.     return true;
  413. }  
  414.  
  415. int new_game(int socketfd){
  416.     int c, nr_trys = 7;
  417.     int n = 0;
  418.     string tosend, word1, under_ = "", category;
  419.     if(usernames.find(socketfd) == usernames.end()){
  420.         tosend = "(?)You have to login first.\n";
  421.         writeline(socketfd,socketfd,tosend,1);
  422.         return 0;
  423.     }
  424.     if(players.count(usernames[socketfd])){
  425.         tosend = "(?)End your game first.\n";
  426.         writeline(socketfd,socketfd,tosend,1);
  427.         return 0;
  428.     }  
  429.     string cat = "", max, wordid;
  430.     tosend = ">> Number max of players: ";
  431.     writeline(socketfd, socketfd, tosend, 1);
  432.     readline(socketfd,max);
  433.     tosend = ">> Choose the category (optional): ";
  434.     writeline(socketfd, socketfd, tosend, 1);
  435.     readline(socketfd,cat);
  436.  
  437.     PGresult* res3 = executeSQL("SELECT * FROM hangman.word");     
  438.        
  439.     if(cat == ""){
  440.         PGresult* res = executeSQL("SELECT * FROM hangman.word ORDER BY random() LIMIT 1");
  441.         word1 = PQgetvalue(res,0,1);
  442.         for(int row1 = 0; row1 < PQntuples(res3) ; row1++){
  443.             if(PQgetvalue(res3,row1,1) == word1){
  444.                 category = PQgetvalue(res3,row1,2);
  445.                 wordid = PQgetvalue(res3,row1,0);
  446.                 break;
  447.             }  
  448.         }
  449.         c = 0;
  450.     }
  451.     else{
  452.         PGresult* res1 = executeSQL("SELECT * FROM hangman.category WHERE category.name = ('" + cat + "')");
  453.         if(PQntuples(res1) == 0){
  454.             string tosend = "Category doesn't exists. Try again.\n";
  455.             writeline(socketfd,socketfd,tosend,1); 
  456.             return 0;
  457.         }
  458.         PGresult* res2 = executeSQL("SELECT * FROM hangman.category");         
  459.         for(int row = 0; row < PQntuples(res2) ; row++){
  460.             if(PQgetvalue(res2,row,1) != cat)
  461.                 n++;
  462.             else
  463.                 break;
  464.         }  
  465.         category = int_to_string(n+1);
  466.         PGresult* result = executeSQL("SELECT * FROM hangman.word WHERE word.idcat = " + category + " ORDER BY random() LIMIT 1");
  467.         word1 = PQgetvalue(result,0,1);
  468.         for(int row =0; row < PQntuples(result) ; row++){
  469.             if(PQgetvalue(result,row,1) == word1){
  470.                 wordid = PQgetvalue(result,row,0);
  471.                 break;
  472.             }
  473.         }      
  474.         c = 1; 
  475.     }  
  476.  
  477.     for(size_t i = 0; i < word1.size(); ++i)
  478.         under_ = under_ + '_';
  479.    
  480.     cout << word1 << endl;
  481.    
  482.     int i_max = string_to_int(max);
  483.     PGresult* id = executeSQL("SELECT * FROM hangman.game");
  484.    
  485.     tosend = ">> Modes -> hard - H / easy - E: ";
  486.     writeline(socketfd,socketfd,tosend,1);
  487.     readline(socketfd,tosend); 
  488.     if(!tosend.find("H"))
  489.         trys[int_to_string(PQntuples(id) + 1)] = nr_trys;  
  490.     else
  491.         trys[int_to_string(PQntuples(id) + 1)] = 1000;
  492.    
  493.     cout << under_ << " " << word1 << endl;
  494.    
  495.     game[int_to_string(PQntuples(id) + 1)] = string_to_int(max) - 1;
  496.     maximum[i_max] = int_to_string(PQntuples(id) + 1);
  497.     players[usernames[socketfd]] = PQntuples(id) + 1;
  498.     word[word1] = PQntuples(id) + 1;
  499.     find_word[under_] = PQntuples(id) + 1;
  500.    
  501.     string begin = time_date(socketfd);
  502.     executeSQL("INSERT INTO hangman.game VALUES ('" + int_to_string(PQntuples(id) + 1) + "', 'NULL','" + usernames[socketfd] + "','" + begin + "','" + " NULL','" + category + "','" + wordid + "')"); 
  503.        
  504.     tosend = ">> Game with id " + int_to_string(PQntuples(id) + 1) + " created! Waiting for players.\n";
  505.     writeline(socketfd,socketfd,tosend,1);
  506.     if(c)
  507.         tosend = ">> Created a new game for " + max + " players in the " + cat + " category with id " + int_to_string(PQntuples(id) + 1) + "\n";
  508.     else
  509.         tosend = ">> Created a new game for " + max + " players with id " + int_to_string(PQntuples(id) + 1) + "\n";
  510.     cout << tosend << endl;
  511.     broadcast(socketfd,tosend, 1);
  512.     return (PQntuples(id) + 1);
  513. }
  514.  
  515. bool join_game(int socketfd, int id){
  516.     string tosend;
  517.     if(players.count(usernames[socketfd])){
  518.         tosend = "(?)You cannot join another game.\n";
  519.         writeline(socketfd,socketfd,tosend,1);
  520.         return false;
  521.     }  
  522.     if(!game.count(int_to_string(id))){
  523.         tosend = "(?)Game doesn't exists.\n";
  524.         writeline(socketfd,socketfd,tosend,1);
  525.         return false;
  526.     }  
  527.     it = game.find(int_to_string(id));
  528.     if((int&)it->second == 0){
  529.         tosend = "(?)Game is full!\n";
  530.         writeline(socketfd,socketfd,tosend,1);
  531.         return false;
  532.     }
  533.     else{
  534.         players[usernames[socketfd]] = id;
  535.         int max = (int&)it->second - 1;
  536.         game[int_to_string(id)] = max;
  537.         if (max != 0){
  538.             tosend = ">> " + int_to_string(max) + " players left to close the game with id " + int_to_string(id) + ".\n";
  539.             broadcast(socketfd,tosend,1);
  540.             writeline(socketfd,socketfd,tosend,1);
  541.         }
  542.         else if(max == 0){
  543.             tosend = ">> The game with id is " + int_to_string(id) + " is close. The game is ready to start.\n";
  544.             cout << ">> The game with id is " << id << " is close. The game is already to start." << endl;
  545.             broadcast(socketfd,tosend,1);
  546.             writeline(socketfd,socketfd,tosend,1);
  547.         }      
  548.         tosend = ">> Successful join! Please, wait for the game.\n";
  549.         writeline(socketfd,socketfd,tosend,1);
  550.         return true;
  551.     }      
  552. }
  553.  
  554. bool end_game(int id_game){
  555.     for(it = game.begin(); it != game.end(); it++){
  556.         if(string_to_int(it->first) == id_game){
  557.             game.erase(it->first);
  558.             maximum.erase(it->second);
  559.         }  
  560.     }
  561.     for(it = word.begin(); it != word.end(); it++){
  562.         if(it->second == id_game)
  563.             word.erase(it->first);
  564.     }
  565.     for(it = find_word.begin(); it != find_word.end(); it++){
  566.         if(it->second == id_game)
  567.             find_word.erase(it->first);
  568.     }      
  569.     for(it = turn.begin(); it != turn.end(); it++){
  570.         if(players[it->first] == id_game){
  571.             turn.erase(it->first);
  572.             players.erase(it->first);
  573.         }  
  574.     }
  575.     return true;
  576. }
  577.  
  578. int test_guess(int socketfd, string line){
  579.     string tosend;
  580.     int id_game = players[usernames[socketfd]], n = 0, num;
  581.     it = trys.find(int_to_string(id_game));
  582.     num = it->second;
  583.     trys[int_to_string(id_game)] = num - 1;
  584.     if(!num)
  585.         return 3;
  586.        
  587.     string wrd, unk_wrd;
  588.     for(it = word.begin(); it != word.end(); it++){
  589.         if(it->second == id_game)
  590.             wrd = it->first;
  591.     }
  592.     for(it = find_word.begin(); it != find_word.end(); it++){
  593.         if(it->second == id_game){
  594.             unk_wrd = it->first;
  595.             break;
  596.         }  
  597.     }
  598.     string new_wrd = unk_wrd;
  599.     find_word.erase(unk_wrd);
  600.     it = find_word.find(unk_wrd);
  601.     if(line.size() == sizeof(char)){
  602.         char letter = line[0];
  603.         for(size_t i = 0; i < wrd.size(); i++){
  604.             if(letter == wrd[i] && unk_wrd[i] == 95){
  605.                 new_wrd[i] = letter;
  606.                 n++;
  607.             }      
  608.         }
  609.         find_word[new_wrd] = id_game;
  610.         if(new_wrd == wrd)
  611.             return 2;      
  612.         else if(n != 0){
  613.             tosend = ">> Good. Letter " + line + " exists. Continue.\n";
  614.             writeline(socketfd,socketfd,tosend,1);
  615.             return 1;
  616.         }
  617.         else{
  618.             tosend = ">> Wrong. Letter " + line + " doesn't exist.\n";
  619.             writeline(socketfd,socketfd,tosend,1);
  620.             return 0;
  621.         }      
  622.     }  
  623.     else{
  624.         if(line == wrd){
  625.             find_word[line] = id_game;         
  626.             return 2;
  627.         }
  628.         else{
  629.             tosend = ">> Wrong. Word " + line + " doesn't match.\n";
  630.             writeline(socketfd,socketfd,tosend,1);
  631.             find_word[unk_wrd] = id_game;
  632.             return 0;  
  633.         }  
  634.     }
  635.     return 0;  
  636.  
  637. }  
  638.  
  639. bool start_game(int id, int socketfd){
  640.     string tosend;
  641.     if(!game.count(int_to_string(id))){
  642.         tosend = "(?)Game doesn't exists.\n";
  643.         writeline(socketfd,socketfd,tosend,1);
  644.         return false;
  645.     }
  646.     if(started.count(id)){
  647.         tosend = ">> Game has already started!\n";
  648.         writeline(socketfd,socketfd,tosend,1);
  649.         return false;
  650.     }
  651.     if(!players.count(usernames[socketfd])){   
  652.         tosend = "(?)You don't belong to that game. Try to join first!\n";
  653.         writeline(socketfd,socketfd,tosend,1);
  654.         return false;
  655.     }
  656.     it = players.find(usernames[socketfd]);
  657.     if(it->first == usernames[socketfd] && it->second != id){
  658.         tosend = "(?)You don't belong to that game. Try to join first!\n";
  659.         writeline(socketfd,socketfd,tosend,1);
  660.         return false;
  661.     }  
  662.     tosend = ">> Game has started. Good luck!\n";
  663.     for(it = players.begin(); it != players.end(); it++){
  664.         if(it->first == usernames[socketfd] && (int&)it->second == id){
  665.             turn[it->first] = 1;
  666.             writeline(sockets[it->first],sockets[it->first],tosend,1);
  667.         }
  668.         else if(it->first != usernames[socketfd] && (int&)it->second == id){
  669.             turn[it->first] = 0;
  670.             writeline(sockets[it->first],sockets[it->first],tosend,1);
  671.         }
  672.     }
  673.    
  674.     started.insert(id);
  675.     tosend = ">> Player " + usernames[socketfd] + " to guess.\n";
  676.     for(it = players.begin(); it != players.end(); it++){
  677.         if(it->second == id && it->first != usernames[socketfd])
  678.             writeline(sockets[it->first],sockets[it->first],tosend,1); 
  679.     }
  680.     tosend = ">> It's your turn.\n";
  681.     writeline(socketfd,socketfd,tosend,1);
  682.     for(it = find_word.begin(); it != find_word.end(); it++){
  683.         if(it->second == id){
  684.             tosend = "word: " + it->first + "\n";
  685.             writeline(socketfd,socketfd,tosend,1);
  686.             break; 
  687.         }  
  688.     }
  689.     return true;
  690. }
  691.  
  692. bool update_db(int socketfd, int id_game){
  693.     string score;
  694.     executeSQL("UPDATE hangman.game SET winner = '" + usernames[socketfd] + "' WHERE idgame = "  + int_to_string(id_game));
  695.     string end = time_date(socketfd);
  696.     executeSQL("UPDATE hangman.game SET end_hours = '" + end + "' WHERE idgame = "  + int_to_string(id_game)); 
  697.     PGresult* res = executeSQL("SELECT username, score FROM hangman.users");           
  698.     for(int row = 0; row < PQntuples(res); row++){
  699.         if(PQgetvalue(res, row, 0) == usernames[socketfd]){
  700.             int aux = string_to_int(PQgetvalue(res,row,1)) + 1;
  701.             score = int_to_string(aux);
  702.             break;
  703.         }
  704.     }
  705.     executeSQL("UPDATE hangman.users SET score = " + score + " WHERE username = '" + usernames[socketfd] + "'");
  706.     return true;
  707. }
  708.  
  709. bool turns(int socketfd){
  710.     int b;
  711.     string tosend, save;
  712.     int id_game = players[usernames[socketfd]], n = 0;
  713.     for(it = turn.begin(); it != turn.end(); it++){
  714.         if(it->first == usernames[socketfd])
  715.             n++;
  716.         if(it->first == usernames[socketfd] && it->second == 0){
  717.             tosend = ">> Wait for your turn.\n";
  718.             writeline(socketfd,socketfd,tosend,1);
  719.             return false;
  720.         }
  721.         else if(it->first == usernames[socketfd] && it->second == 1)
  722.             break; 
  723.     }  
  724.     if(!n){
  725.         tosend = "(?)You aren't playing.\n";
  726.         writeline(socketfd,socketfd,tosend,1);
  727.         return false;
  728.     }
  729.     tosend = "letter/word: ";
  730.     writeline(socketfd,socketfd,tosend,1);
  731.     readline(socketfd,tosend);
  732.     b = test_guess(socketfd,tosend);
  733.     if(b == 3){
  734.         tosend = "(!)Number of tries exceeded. Try again latter!\n";
  735.         for(it = players.begin(); it != players.end(); it++){
  736.             if(it->second == id_game)
  737.                 writeline(sockets[it->first],sockets[it->first],tosend,1);
  738.         }
  739.         end_game(id_game); 
  740.         return false;
  741.     }
  742.     for(it = players.begin(); it != players.end(); it++){
  743.         if(it->first != usernames[socketfd] && it->second == id_game){
  744.             string tosend_guess = ">> "+ usernames[socketfd] + " guessed **" + tosend + "**\n";
  745.             writeline(sockets[it->first],sockets[it->first],tosend_guess,1);
  746.         }
  747.     }
  748.     it = find_word.find(usernames[socketfd]);
  749.     string wrd;
  750.     for(it = find_word.begin(); it != find_word.end(); it++){
  751.         if(it->second == id_game)
  752.             wrd = it->first;
  753.     }
  754.     it = players.find(usernames[socketfd]);
  755.     if(b == 2){
  756.         tosend = ">> You won! Congratilations!!!\n";
  757.         writeline(socketfd,socketfd,tosend,1);
  758.         for(it = players.begin(); it != players.end(); it++){
  759.             if(it->first != usernames[socketfd] && it->second == id_game){
  760.                 tosend = ">> Player " + usernames[socketfd] + " won! The word was: " + wrd + "\n";
  761.                 writeline(sockets[it->first],sockets[it->first],tosend,1);
  762.             }
  763.         }  
  764.         end_game(id_game);
  765.         update_db(socketfd,id_game);
  766.         return true;
  767.     }
  768.     else if(b == 0){
  769.         turn[it->first] = 0;
  770.         while(1){
  771.             if(it == players.end())
  772.                 it = players.begin();
  773.             else
  774.                 it++;
  775.             if(it->second == id_game){ 
  776.                 turn[it->first] = 1;
  777.                 it->first;
  778.                 save = it->first;          
  779.                 break;
  780.             }
  781.         }
  782.     }
  783.     else if(b == 1)
  784.         save = it->first;
  785.    
  786.     for(it = find_word.begin(); it != find_word.end(); it++){
  787.         if(it->second == id_game){
  788.             tosend = "-> word: " + it->first + "\n";
  789.             writeline(socketfd,socketfd,tosend,1);
  790.             break; 
  791.         }  
  792.     }  
  793.     tosend = ">> It's your turn.\n";
  794.     writeline(sockets[save],sockets[save],tosend,1);
  795.     for(it = find_word.begin(); it != find_word.end(); it++){
  796.         if(it->second == id_game){
  797.             tosend = "-> word: " + it->first + "\n";
  798.             writeline(sockets[save],sockets[save],tosend,1);
  799.             break; 
  800.         }  
  801.     }
  802.     for(it = players.begin(); it != players.end(); it++){
  803.         if(it->first != save && it->second == id_game){
  804.             tosend = ">> Player " + save + " to guess. \n";
  805.             writeline(sockets[it->first],sockets[it->first],tosend,1);
  806.         }
  807.     }  
  808.     return true;           
  809. }  
  810.    
  811. bool commands(int originfd, string line){
  812.     string tosend, max, cat;
  813.     writeline(originfd, originfd, tosend, 1);
  814.    
  815.     if(!line.find("\\help")){
  816.         tosend = "escrever ajudas \n";
  817.         writeline(originfd, originfd, tosend, 1);
  818.     }
  819.     else if(!line.find("\\login"))
  820.         sign_in(originfd);
  821.     else if(!line.find("\\register"))
  822.         insert_into_users(originfd,6); 
  823.     else if(!line.find("\\users_on"))
  824.         online_users(originfd);
  825.     else if(!line.find("\\logout"))
  826.         client_logout(originfd);
  827.     else if(!line.find("\\chat")){
  828.         if (usernames.find(originfd) != usernames.end()){
  829.             tosend = ">> What username that you want to chat?\n";
  830.             writeline(originfd,originfd,tosend,1);
  831.             readline(originfd, line);
  832.             private_chat(sockets[line],originfd,line);
  833.         }  
  834.         else{
  835.             tosend = "(?)To chat you have to login. \n";
  836.             writeline(originfd,originfd,tosend,1);
  837.         }  
  838.     }
  839.     else if(!line.find("\\category")){
  840.         if (usernames.find(originfd) == usernames.end()){
  841.             tosend = "(?)Try again. Need to login first.\n";
  842.             writeline(originfd, originfd, tosend, 1);
  843.         }
  844.         else if(ver_admin(originfd) == false){
  845.             tosend = "(?)Only administrators can add categorys.\n";
  846.             writeline(originfd, originfd, tosend, 1);
  847.         }
  848.         else
  849.             insert_into_categorys(originfd);
  850.     }
  851.     else if(!line.find("\\word")){
  852.         if(usernames.find(originfd) == usernames.end()){
  853.             tosend = "(?)Try again. Need to login first.\n";
  854.             writeline(originfd,originfd,tosend,1);
  855.         }
  856.         else if(ver_admin(originfd) == false){
  857.             tosend = "(?)Only administrators can add words.\n";
  858.             writeline(originfd, originfd, tosend, 1);
  859.         }      
  860.         else
  861.             insert_into_words(originfd);
  862.     }  
  863.     else if(!line.find("\\new")){
  864.         if(usernames.find(originfd) == usernames.end()){
  865.             tosend = "(?)Try again. Need to login first.\n";
  866.             writeline(originfd,originfd,tosend,1);
  867.         }
  868.         else
  869.             new_game(originfd);
  870.     }
  871.     else if(!line.find("\\join")){
  872.         if(usernames.find(originfd) == usernames.end()){
  873.             tosend = "(?)Try again. Need do login first\n";
  874.             writeline(originfd,originfd,tosend,1);
  875.         }  
  876.         else{
  877.             tosend = ">> What is the ID of the game? ";
  878.             writeline(originfd,originfd,tosend,1);
  879.             readline(originfd,tosend);
  880.             if(started.count(string_to_int(tosend))){
  881.                 tosend = "(?)Game has already started!\n";
  882.                 writeline(originfd,originfd,tosend,1);
  883.                 return false;
  884.             }  
  885.             else   
  886.                 join_game(originfd,string_to_int(tosend));
  887.         }  
  888.     }
  889.     else if(!line.find("\\start")){
  890.         if (usernames.find(originfd) != usernames.end()){
  891.             tosend = "-> Id of the game: ";
  892.             writeline(originfd,originfd,tosend,1);
  893.             readline(originfd,tosend);
  894.             int id = string_to_int(tosend);
  895.             start_game(id,originfd);
  896.         }
  897.         else{
  898.             tosend = "(?)Error. Need to login first.\n";
  899.             writeline(originfd,originfd,tosend,1);
  900.         }
  901.     }  
  902.     else if(!line.find("\\guess")){
  903.         if (usernames.find(originfd) != usernames.end())
  904.             turns(originfd);
  905.         else{
  906.             tosend = "(?)Error. Need to login first.\n";
  907.             writeline(originfd,originfd,tosend,1);
  908.         }
  909.     }
  910.     else if(!line.find("\\info_user")){
  911.         if (usernames.find(originfd) != usernames.end()){
  912.             tosend = "-> What username that you want to know informations?\n";
  913.             writeline(originfd,originfd,tosend,1);
  914.             readline(originfd, line);
  915.             info_user(sockets[line],originfd,line);
  916.         }
  917.         else{
  918.             tosend = "(?)Error. Need to login first.\n";
  919.             writeline(originfd,originfd,tosend,1);
  920.         }
  921.     }
  922.     else if(!line.find("\\exit")){
  923.         client_off(originfd);  
  924.         cout << ">> Client " << originfd << " disconnects.\n";
  925.     }
  926.     else if(!line.find("\\shutdown"))
  927.         if (usernames.find(originfd) != usernames.end() && ver_admin(originfd) == true)
  928.             stdwn();
  929.         else if(usernames.find(originfd) != usernames.end() && ver_admin(originfd) == false){
  930.             tosend = "(?)Error. Only administrators can shutdown.\n";
  931.             writeline(originfd,originfd,tosend,1);
  932.         }
  933.         else{
  934.             tosend = "(?)Error. Need do login first.\n";
  935.             writeline(originfd,originfd,tosend,1);
  936.         }
  937.     else{
  938.         cout << ">> Socket " << originfd << " said: " << line << endl;
  939.         broadcast(originfd,line,0);
  940.     }      
  941.     return true;   
  942. }
  943.    
  944. // handles one client
  945. void* client(void* args){
  946.     int sockfd = *(int*)args;
  947.     string line, tosend;
  948.  
  949.     pthread_mutex_lock(&mutex);
  950.     client_id.insert(sockfd);
  951.     pthread_mutex_unlock(&mutex);
  952.  
  953.     cout << "Reading from socket " << sockfd << endl;
  954.     tosend = "To see the commands write 'info'.\n";
  955.     writeline(sockfd, sockfd, tosend, 1);
  956.    
  957.     while (readline(sockfd, line)){
  958.         if(!line.find("info")){
  959.             tosend = "for HELP - \\help\nto login - \\login\nto sign up - \\register\nto se online users - \\users_on\nto do logout - \\logout\nto send a message to a client - \\chat\nto add a new category - \\category\nto add a new word - \\word (don't forget to choose the category)\nto creat a new game - \\new\nto join to a created game - \\join\nto start a new game - \\start\nto play - \\guess\nto know nr of wins of a player - \\info_user\nto disconnect - \\exit\nto shutdown the server and all the clients - \\shutdown (only administrators)\n";
  960.             writeline(sockfd, sockfd, tosend, 1);
  961.         }      
  962.         else
  963.             commands(sockfd,line);
  964.         if(shut_d == true)
  965.             exit(-1);  
  966.     }
  967.  
  968.     cout << "Closing socket " << sockfd << endl;
  969.  
  970.     client_id.erase(sockfd);
  971.    
  972.     close(sockfd);
  973.     return 0;
  974. }
  975.  
  976. int main()
  977. {
  978.     initDB();
  979.            
  980.     /* Data structures */
  981.     int sockfd, newsockfd, port = 2002;
  982.     socklen_t client_addr_length;
  983.     struct sockaddr_in serv_addr, cli_addr;
  984.  
  985.     /* Initialize the socket
  986.      AF_INET - We are using IP
  987.      SOCK_STREAM - We are using TCP
  988.      sockfd - id of the main server socket
  989.      If it returns < 0 an error occurred */
  990.     sockfd = socket(AF_INET, SOCK_STREAM, 0);
  991.     if (sockfd < 0) {
  992.      cout << "Error creating socket" << endl;
  993.      exit(-1);
  994.     }
  995.  
  996.  
  997.     /* Create the data structure that stores the server address
  998.      bzero - cleans the structure
  999.      AF_INET - IP address
  1000.      INADDR_ANY - Accept request from any IP address */
  1001.     bzero((char *) &serv_addr, sizeof(serv_addr));
  1002.     serv_addr.sin_family = AF_INET;
  1003.     serv_addr.sin_addr.s_addr = INADDR_ANY;
  1004.     serv_addr.sin_port = htons(port);
  1005.    
  1006.     sockfd = socket(AF_INET , SOCK_STREAM , 0);
  1007.     struct sockaddr_in server;
  1008.     server.sin_addr.s_addr = inet_addr("127.0.0.1");
  1009.     server.sin_family = AF_INET;
  1010.     server.sin_port = htons(port);
  1011.     int res = connect(sockfd , (struct sockaddr *)&server , sizeof(server));
  1012.  
  1013.     int yes=1;
  1014.     if (setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof yes) == -1) {
  1015.         perror("setsockopt");
  1016.         exit(1);
  1017.     }
  1018.    
  1019.     /* Bind the socket. The socket is now active but we
  1020.      are still not receiving any connections
  1021.      If it returns < 0 an error occurred */
  1022.     res = bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));
  1023.     if (res < 0) {
  1024.      cout << "Error binding to socket" << endl;
  1025.      exit(-1);
  1026.     }
  1027.  
  1028.     /* Start listening to connections. We want to have
  1029.      at most 5 pending connections until we accept them */
  1030.     listen(sockfd, 5);
  1031.  
  1032.     while (true){
  1033.         /* Accept a new connection. The client address is stored as:
  1034.            cli_addr - client address
  1035.            newsockfd - socket id for this client */
  1036.         client_addr_length = sizeof(cli_addr);
  1037.         if(shut_d == true)
  1038.             break;
  1039.         else
  1040.             newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &client_addr_length);
  1041.        
  1042.         /* Create a thread to handle this client */
  1043.         pthread_t thread1;
  1044.         pthread_mutex_init(&mutex,NULL);
  1045.         pthread_create(&thread1, NULL, client, &newsockfd);
  1046.         pthread_mutex_destroy(&mutex);
  1047.     }
  1048.  
  1049.     /* Close the server socket */
  1050.     close(sockfd);
  1051.     closeDB();
  1052.  
  1053.     return 0;
  1054. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top