1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
|
/*
* CSci4061 S2007 Assignment 5
* name: John Saxton
* section: 003
* id: 3221718
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <strings.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <regex.h>
#include <math.h>
#include <float.h>
#include "linkedlist.h"
#include "itemlinkedlist.h"
#define TITLE_SIZE 700
#define IDEAL_PRICE 2.00
int main(int argc, char **argv) {
fd_set sockets;
int sock, portnum, reuseaddr, n, highest_socket;
struct sockaddr_in serv_addr;
struct node *temp;
struct timeval timeOfLastUpdate, currentTime;
long usecdiff;
float secdiff;
reuseaddr = 1;
if (argc < 2) {
fprintf(stderr, "Syntax: %s portnum\n", argv[0]);
exit(1);
}
portnum = atoi(argv[1]);
DLLinitialize(&playerList);
initialize_items();
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) {
fprintf(stderr, "Error opening socket, exiting...\n");
exit(1);
}
highest_socket = sock;
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(reuseaddr));
setnonblocking(sock);
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portnum);
setnonblocking(sock);
if (bind(sock, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
fprintf(stderr, "Failed to bind, exiting...\n");
exit(1);
}
listen(sock,42);
//Initialize time
gettimeofday(&timeOfLastUpdate, NULL);
while(1) {
FD_ZERO(&sockets);
FD_SET(sock, &sockets);
//for each player, add their socket to the sockets set
temp = playerList.head;
highest_socket = sock;
while(temp != NULL && playerList.length > 0) {
FD_SET(temp->value->sock, &sockets);
if (temp->value->sock > highest_socket) {
highest_socket = temp->value->sock;
}
temp = temp->next;
}
n = select(highest_socket+1, &sockets, NULL, NULL, NULL);
if(n < 0) {
perror("Select failed");
fprintf(stderr, "Exiting...\n");
exit(1);
}
//We need to update the users warez, conduct transactions, etc.
gettimeofday(¤tTime, NULL);
usecdiff = 1000000*(currentTime.tv_sec - timeOfLastUpdate.tv_sec) + currentTime.tv_usec - timeOfLastUpdate.tv_usec;
secdiff = usecdiff/1000000.0;
updateUsers(secdiff);
timeOfLastUpdate = currentTime;
if(FD_ISSET(sock, &sockets)) {
//we have a new user
newUser(sock);
}
temp = playerList.head;
while(temp != NULL && playerList.length > 0) {
if(FD_ISSET(temp->value->sock, &sockets)) {
dataHandler(temp->value);
}
temp = temp->next;
}
}
return 0;
}
/****************************************************************************
* void setnonblocking(int sock)
* This function ensures our socket is non blocking. Based upon code found
* at http://www.lowtek.com/sockets/select.html
****************************************************************************/
void setnonblocking(int sock) {
int opts = fcntl(sock,F_GETFL);
if (opts < 0) {
perror("fcntl(F_GETFL)");
exit(1);
}
opts = (opts | O_NONBLOCK);
if (fcntl(sock,F_SETFL,opts) < 0) {
perror("fcntl(F_SETFL)");
exit(1);
}
return;
}
/****************************************************************************
* void dataHandler(struct player* activePlayer)
* This function is called whenever a socket needs to be serviced. It's
* primary responsibility is to parse the command and call the appropriate
* function(s).
****************************************************************************/
void dataHandler(struct player* activePlayer) {
char buffer[1023];
char param1[1023];
char temp[1023];
int sock = activePlayer->sock;
read(sock,buffer,1023);
strip_nl_chars(buffer);
if(activePlayer->current_state == START) {
activePlayer->current_state = NO_NICK;
print(activePlayer->sock, "Please enter a nickname between 3 and 20 characters.\n");
}
else if(activePlayer->current_state == NO_NICK) {
if(strlen(buffer) > 20) {
print(activePlayer->sock, "Sorry, all nicknames must be less than 20 characters.\n");
}
else if(strlen(buffer) < 3) {
print(activePlayer->sock, "Sorry, all nicknames must be at least 3 characters.\n");
}
else if(nick_exists(buffer)) {
//Prompt them to change their nick
sprintf(temp, "Sorry, the nick %s is taken. Please try a different nick.\n", buffer);
print(activePlayer->sock, temp);
}
else {
strcpy(activePlayer->nick, buffer);
sprintf(temp, "Welcome, %s!\n", buffer);
print(activePlayer->sock, temp);
print_instructions(activePlayer->sock);
activePlayer->current_state = PLAYING;
}
}
else if(activePlayer->current_state == PLAYING) {
if(strlen(buffer) == 0);
else if(strcmp("help", buffer) == 0) {
list_commands(activePlayer->sock);
}
else if(sscanf(buffer, "help %s", param1) > 0) {
command_detail(activePlayer->sock, param1);
}
else if(match(buffer, "^buy ") == 1) {
buy(activePlayer, buffer);
}
else if(match(buffer, "^shout ") == 1) {
shout(activePlayer->id, buffer);
}
else if(match(buffer, "^set price ") == 1) {
setprice(activePlayer, buffer);
}
else if(match(buffer, "^whisper ") == 1) {
whisper(activePlayer->id, buffer);
}
else if(strcmp("show items", buffer) == 0) {
display_store(activePlayer->sock);
}
else if(strcmp("show inventory", buffer) == 0) {
viewInventory(activePlayer);
}
else if(strcmp("show status", buffer) == 0) {
viewStatus(activePlayer);
}
else if(strcmp("hongkong", buffer) == 0) {
cheat(activePlayer);
}
else if(strcmp("exit", buffer) == 0) {
end_session(activePlayer);
}
else {
sprintf(temp, "Unknown Command: %s.\n", buffer);
print(activePlayer->sock, temp);
}
}
return;
}
/****************************************************************************
* void print(int sock, char* msg)
* This is a wrapper function for write(). It basically eliminiates the need
* to handle the third parameter.
****************************************************************************/
void print(int sock, char* msg) {
write(sock, msg, strlen(msg));
return;
}
/****************************************************************************
* void newUser(int sock)
* If a new user connects to the server, this function is called. It accepts
* the socket, creates and initializes a new player structure, and prints
* a nice introductory message with the name and title of the game.
****************************************************************************/
void newUser(int sock) {
int newsocket;
struct player* newPlayer;
//Accept the new socket
if((newsocket = accept(sock, NULL, NULL)) < 0) {
fprintf(stderr, "Failed to accept, exiting...\n");
exit(1);
}
setnonblocking(newsocket);
//Let's create a new player structure
newPlayer = malloc(sizeof(struct player));
newPlayer->id = nextid;
newPlayer->sock = newsocket;
newPlayer->current_state = START;
newPlayer->cash = 85.00;
newPlayer->cheated = 0;
newPlayer->total_sales = 0;
newPlayer->price = 1.65;
(newPlayer->inventory).cdburners = 0;
(newPlayer->inventory).cds = 0;
(newPlayer->inventory).hdspace = 20*1024; //20GB
(newPlayer->inventory).connection_type = dialup;
(newPlayer->inventory).numtitles = 5;
(newPlayer->inventory).download_queue = 0;
(newPlayer->inventory).hdspace -= (newPlayer->inventory).numtitles*TITLE_SIZE;
nextid++;
//Let's put the player structure in our LL
DLLappend(&playerList, newPlayer);
//and let's send them a nice introductory message
print(newsocket, " W A R E Z D 0 0 D\n");
print(newsocket, " A John Saxton Production\n");
print(newsocket, " Press enter to start....\n");
}
/****************************************************************************
* int nick_exists(char *name)
* This function returns 1 if a user is already using the nick *name, 0
* otherwise.
****************************************************************************/
int nick_exists(char *name) {
struct node *temp = playerList.head;
while(temp != NULL && playerList.length > 0) {
if (strcmp(temp->value->nick, name) == 0) {
return 1;
}
temp = temp->next;
}
return 0;
}
/****************************************************************************
* void strip_nl_chars(char *str)
* This function removes all newline and return characters from a string.
* Useful for handling input buffers.
****************************************************************************/
void strip_nl_chars(char *str) {
int index1, index2;
index1 = index2 = 0;
while(str[index2] != '\0') {
if(str[index1] != '\n' && str[index1] != '\r') {
str[index1] = str[index2];
index1++;
}
index2++;
}
str[index1] = '\0';
}
/****************************************************************************
* void print_instructions(int sock)
* This simply prints out a basic introduction to the game. If the user needs
* more help, they can type help.
****************************************************************************/
void print_instructions(int sock) {
print(sock, "Welcome to Warezd00d!!!\n\n");
print(sock, "You are a new student at foobar high school. Disgusted with the state of The\n");
print(sock, "Scene at FBHS, you decide to take it upon yourself to provide quality warez\n");
print(sock, "releases to your fellow classmates. This is no easy task. In order to succeed,\n");
print(sock, "you will need to provide a wide variety of quality releases to your classmates\n");
print(sock, "with minimal turnaround time. Furthermore, it goes without saying that you\n");
print(sock, "must avoid the authorities at all costs. You start out with nothing but your\n");
print(sock, "parents' computer and $85 in birthday money. Press \"help\" to see a list\n");
print(sock, "of commands or \"help command\" to get help for a specific command.\n");
}
/****************************************************************************
* void list_commands(int sock)
* This function is called whenever a user types help followed by no
* parameters. It lists all the commands the user can use along with basic
* syntax. A user can get more info about a command by typing help command.
****************************************************************************/
void list_commands(int sock) {
print(sock, "Commands:\n");
print(sock, "help\n");
print(sock, "help <command>\n");
print(sock, "buy <item number> <qty>\n");
print(sock, "set price <price>\n");
print(sock, "show items\n");
print(sock, "show inventory\n");
print(sock, "show status\n");
print(sock, "shout <msg>\n");
print(sock, "whisper <username> <msg>\n");
print(sock, "exit\n");
}
/****************************************************************************
* void command_detail(int sock, char *command)
* If a user types help command, this function is called. It gives a more
* in depth explanation of what each command does.
****************************************************************************/
void command_detail(int sock, char *command) {
char temp[500];
if(strcmp("help", command) == 0) {
print(sock, "\nhelp\n");
print(sock, "When called with no parameters, help lists all available commands. When\n");
print(sock, "called with a parameter, it gives a detailed description of the given command.\n");
}
else if(strcmp("shout", command) == 0) {
print(sock, "\nshout <message>\n");
print(sock, "Shout will send a message to every user on the server.\n");
}
else if(strcmp("whisper", command) == 0) {
print(sock, "\nwhisper <user> <message>\n");
print(sock, "Whisper will send a message to an individual user.\n");
}
else if(strcmp("exit", command) == 0) {
print(sock, "\nexit\n");
print(sock, "Exit will end your telnet session.\n");
}
else if(strcmp("buy", command) == 0) {
print(sock, "\nbuy <item number> <qty>\n");
print(sock, "Entering this command will purchase an item. You must enter both an item\n");
print(sock, "number and a quantity. To get a list of items, type \"show items\".\n");
}
else if(strcmp("show", command) == 0) {
print(sock, "\nshow <argument>\n");
print(sock, "-\"show items\" will show all items you can purchase\n");
print(sock, "-\"show inventory\" will show all items in your inventory\n");
print(sock, "-\"show status\" will show information regarding your status.\n");
}
else if(strcmp("set", command) == 0) {
print(sock, "\nset price <price>\n");
print(sock, "set price\" will set the price you charge for your warez.\n");
print(sock, "<price> must be formatted as x.yz, eg: set price 2.11\n");
}
else {
sprintf(temp, "Unknown command: %s\n", command);
print(sock, temp);
}
}
/****************************************************************************
* void shout(int uid, char *buffer)
* This function sends a message to every user on the server except the user
* with id uid.
****************************************************************************/
void shout(int uid, char *buffer) {
struct player* sender;
struct node* temp;
char temp_str[1100];
char message[1100];
int i;
sender = DLLgetplayer_byID(&playerList, uid);
if(strlen(buffer) <= 5) {
print(sender->sock, "Syntax: shout <message>\n");
return;
}
for(i=6;buffer[i-1] != '\0';i++) {
temp_str[i-6] = buffer[i];
}
sprintf(message, "Message from %s: %s\n", sender->nick, temp_str);
temp = playerList.head;
while(temp != NULL && playerList.length > 0) {
if(temp->value->id != uid) {
print(temp->value->sock, message);
}
temp = temp->next;
}
sprintf(message, "Message sent: %s\n", temp_str);
print(sender->sock, message);
}
/****************************************************************************
* void whisper(int uid, char *buffer)
* This function sends a private message from one user to another.
****************************************************************************/
void whisper(int uid, char *buffer) {
struct player *sender, *recipient;
char temp_str[1100];
char message[1100];
char nick[21];
int i, offset;
sender = DLLgetplayer_byID(&playerList, uid);
if(sscanf(buffer, "whisper %s %s", nick, temp_str) < 2) {
print(sender->sock, "Syntax: whisper <recipient> <message>\n");
return;
}
if(strcmp(nick, sender->nick) == 0) {
print(sender->sock, "You cannot send a message to yourself.\n");
return;
}
else if(nick_exists(nick)) {
recipient = DLLgetplayer_byNick(&playerList, nick);
}
else {
sprintf(temp_str, "The nickname %s doesn't exist. Message not sent.\n", nick);
print(sender->sock, temp_str);
return;
}
offset = 9+strlen(nick);
for(i=offset;buffer[i-1] != '\0';i++) {
temp_str[i-offset] = buffer[i];
}
sprintf(message, "Message from %s: %s\n", sender->nick, temp_str);
print(recipient->sock, message);
sprintf(message, "Message sent: %s\n", temp_str);
print(sender->sock, message);
}
/****************************************************************************
* int match(const char *string, char *pattern)
* This function allows me to do string matching using regular expressions.
* Taken from http://www.osix.net/modules/article/?id=349
****************************************************************************/
int match(const char *string, char *pattern) {
int status;
regex_t re;
if(regcomp(&re, pattern, REG_EXTENDED|REG_NOSUB) != 0) {
return 0;
}
status = regexec(&re, string, (size_t)0, NULL, 0);
regfree(&re);
if(status != 0) {
return 0;
}
return 1;
}
/****************************************************************************
* void end_session(struct player* activePlayer)
* If a user disconnects from the server, this function is called. It
* basically just deletes their player structure.
****************************************************************************/
void end_session(struct player* activePlayer) {
print(activePlayer->sock, "Thank you for playing warezd00d!\n");
//Close their socket
close(activePlayer->sock);
//Remove them from the player list
DLLdelete_byID(&playerList, activePlayer->id);
return;
}
/****************************************************************************
* void display_store(int sock)
* This function lists every item a user can purchase. It also lists the
* corresponding prices.
****************************************************************************/
void display_store(int sock) {
char temp[500];
struct inode* tempNode = itemList.head;
print(sock, "\n\nItem #)\tDescription (Price):\n");
while(tempNode != NULL) {
sprintf(temp, "%i)\t%s ($%.2f)\n", tempNode->value->id, tempNode->value->name, tempNode->value->price);
print(sock, temp);
tempNode = tempNode->next;
}
print(sock, "\n");
}
/****************************************************************************
* void initialize_items()
* This function populates a linked list that contains each item in the game.
****************************************************************************/
void initialize_items() {
int id;
int numitems = 8;
struct item* items[numitems];
//Let's initialize the download speeds first (in MB/real second)
download_speeds[dialup] = 6.0;
download_speeds[DSL] = 20.0;
download_speeds[cable] = 50.0;
//Let's initialize our items
for(id = 0;id<numitems;id++) {
items[id] = malloc(sizeof(struct item));
(items[id])->id = id;
}
//Item 1: CD Burner
(items[0])->price = 30.00;
strcpy((items[0])->name, "CD Burner");
//Item 2: 40GB Hard Drive
(items[1])->price = 40.00;
strcpy((items[1])->name, "40GB Hard Drive");
//Item 3: 500GB Hard Drive
(items[2])->price = 200.00;
strcpy((items[2])->name, "500GB Hard Drive");
//Item 4: DSL Connection
(items[3])->price = 40.00;
strcpy((items[3])->name, "DSL Internet Connection");
//Item 4: Cable Internet Connection
(items[4])->price = 75.00;
strcpy((items[4])->name, "Cable Internet Connection");
//Item 5: 10 Pack Blank CDs
(items[5])->price = 5.00;
strcpy((items[5])->name, "10 Pack Blank CDs");
//Item 6: 50 Pack Blank CDs
(items[6])->price = 15.00;
strcpy((items[6])->name, "50 Pack Blank CDs");
//Item 7: 100 Pack Blank CDs
(items[7])->price = 25.00;
strcpy((items[7])->name, "100 Pack Blank CDs");
iLLinitialize(&itemList);
//Let's add each item to the linked list
for(id=0;id<numitems;id++) {
iLLappend(&itemList, items[id]);
}
}
/****************************************************************************
* void buy(struct player* buyer, char* buffer)
* If a user types buy x y, this function is called. It does basic error
* checking, then adds y copies of item x into the user's inventory.
****************************************************************************/
void buy(struct player* buyer, char* buffer) {
struct item *ourItem;
char tempstr[100];
int qty, itemID;
if(sscanf(buffer, "buy %i %i", &itemID, &qty) != 2) {
print(buyer->sock, "Syntax: buy <item number> <qty>\n");
return;
}
if(qty <= 0) {
print(buyer->sock, "You must enter a quantity greater than zero.\n");
return;
}
//Let's get the item object
ourItem = iLLgetitem_byID(&itemList, itemID);
if(ourItem == NULL) {
sprintf(tempstr, "No item with the ID %i exists.\n", itemID);
print(buyer->sock, tempstr);
return;
}
if(buyer->cash < (ourItem->price)*qty) {
print(buyer->sock, "You cannot afford that.\n");
return;
}
if(strcmp(ourItem->name, "CD Burner") == 0) {
(buyer->inventory).cdburners += qty;
}
else if(strcmp(ourItem->name, "40GB Hard Drive") == 0) {
(buyer->inventory).hdspace += 40*1024*qty;
}
else if(strcmp(ourItem->name, "500GB Hard Drive") == 0) {
(buyer->inventory).hdspace += 500*1024*qty;
}
else if(strcmp(ourItem->name, "DSL Internet Connection") == 0) {
if((buyer->inventory).connection_type > DSL) {
print(buyer->sock, "You already have a better connection...\n");
return;
}
if((buyer->inventory).connection_type == DSL) {
print(buyer->sock, "You already have a DSL connection...\n");
return;
}
if(qty > 1) {
print(buyer->sock, "You can only purchase one DSL internet connection.\n");
return;
}
(buyer->inventory).connection_type = DSL;
}
else if(strcmp(ourItem->name, "Cable Internet Connection") == 0) {
if((buyer->inventory).connection_type == cable) {
print(buyer->sock, "You already have a cable connection...\n");
return;
}
if(qty > 1) {
print(buyer->sock, "You can only purchase one cable internet connection.\n");
return;
}
(buyer->inventory).connection_type = cable;
}
else if(strcmp(ourItem->name, "10 Pack Blank CDs") == 0) {
(buyer->inventory).cds += 10*qty;
}
else if(strcmp(ourItem->name, "50 Pack Blank CDs") == 0) {
(buyer->inventory).cds += 50*qty;
}
else if(strcmp(ourItem->name, "100 Pack Blank CDs") == 0) {
(buyer->inventory).cds += 100*qty;
}
//Subtract the cash from the user's account
(buyer->cash) -= (ourItem->price)*qty;
//print an informative message
sprintf(tempstr, "Purchased %i \"%s\"\n", qty, ourItem->name);
print(buyer->sock, tempstr);
}
/****************************************************************************
* void viewInventory(struct player* buyer)
* This function allows a user to view all the items in their inventory.
****************************************************************************/
void viewInventory(struct player* buyer) {
char tempstr[100];
print(buyer->sock, "\nInventory:\n");
sprintf(tempstr, "Cash: $%.2f\n", buyer->cash);
print(buyer->sock, tempstr);
sprintf(tempstr, "Number of titles: %i\n", (buyer->inventory).numtitles);
print(buyer->sock, tempstr);
if((buyer->inventory).connection_type == dialup) {
print(buyer->sock, "Connection type: dialup\n");
}
else if((buyer->inventory).connection_type == DSL) {
print(buyer->sock, "Connection type: DSL\n");
}
else if((buyer->inventory).connection_type == cable) {
print(buyer->sock, "Connection type: cable\n");
}
sprintf(tempstr, "CD Burners: %i\n", (buyer->inventory).cdburners);
print(buyer->sock, tempstr);
sprintf(tempstr, "Blank CDs: %i\n", (buyer->inventory).cds);
print(buyer->sock, tempstr);
sprintf(tempstr, "Free Hard Drive Space: %.2f GB\n", (buyer->inventory).hdspace/1024.0);
print(buyer->sock, tempstr);
}
/****************************************************************************
* void viewStatus(struct player* buyer)
* This function allows a user to view status information.
****************************************************************************/
void viewStatus(struct player* buyer) {
char tempstr[100];
print(buyer->sock, "\nStatus:\n");
sprintf(tempstr, "Cash: $%.2f\n", buyer->cash);
print(buyer->sock, tempstr);
sprintf(tempstr, "Number of titles: %i\n", (buyer->inventory).numtitles);
print(buyer->sock, tempstr);
sprintf(tempstr, "Total Sales: %i\n", buyer->total_sales);
print(buyer->sock, tempstr);
sprintf(tempstr, "Percentage of next download completed: %.2f\045\n", 100*(buyer->inventory).download_queue / TITLE_SIZE);
print(buyer->sock, tempstr);
sprintf(tempstr, "Current Rate: $%.2f/copy\n", buyer->price);
print(buyer->sock, tempstr);
sprintf(tempstr, "Blank CDs: %i\n", (buyer->inventory).cds);
print(buyer->sock, tempstr);
sprintf(tempstr, "Free Hard Drive Space: %.2f GB\n", (buyer->inventory).hdspace/1024.0);
print(buyer->sock, tempstr);
}
/****************************************************************************
* void updateUsers(float secDiff)
* In order to simulate real-time downloads without threads or extra
* processes, I call this function every time a client queries the server.
* It uses timestamps to update the progress of new downloads and new sales.
* It also determines whether or not a user gets "busted".
****************************************************************************/
void updateUsers(float secDiff) {
struct node *temp;
int newTitles, num_seconds, random_number, i;
float expulsion_probability, random_probability;
temp = playerList.head;
while(temp != NULL) {
//The first thing we want to do is update the users' downloads
(temp->value->inventory).download_queue += download_speeds[(temp->value->inventory).connection_type]*secDiff;
newTitles = ((temp->value->inventory).download_queue)/TITLE_SIZE;
if(newTitles*TITLE_SIZE > (temp->value->inventory).hdspace) {
//Let's determine how many titles we can fit on the hard disk
newTitles = (temp->value->inventory).hdspace/TITLE_SIZE;
}
(temp->value->inventory).numtitles += newTitles;
(temp->value->inventory).download_queue -= (float)newTitles*TITLE_SIZE;
(temp->value->inventory).hdspace -= newTitles*TITLE_SIZE;
//Let's determine how many sales occurred
//The probability of a sale occurring in any given second is:
//(ln(titles)+ln(23*cd_burners + 5))/50
//This should always be less than 1. If it isn't, it's not a big deal,
//as it simply means that one will conduct a transaction every second.
num_seconds = floor(secDiff);
for(i=0;i<num_seconds;i++) {
saleStuff(temp->value, 1.0);
}
saleStuff(temp->value, secDiff-num_seconds);
//Now we want to determine whether or not the user will be expelled
if(temp->value->total_sales > 100) {
expulsion_probability = expf(temp->value->total_sales / 50000) - 1;
random_number = rand();
random_probability = (float)random_number/RAND_MAX;
if(expulsion_probability > random_probability) {
print(temp->value->sock, "BUSTED!\n");
print(temp->value->sock, "Principal n00b caught you selling warez!\n");
print(temp->value->sock, "Game over.\n");
end_session(temp->value);
}
}
temp = temp->next;
}
}
/****************************************************************************
* void updateUsers(float secDiff)
* This function determines whether or not a sale occurred in a given period
* of time. If a sale does occur, basic error checking is done and
* appropriate action is taken.
****************************************************************************/
void saleStuff(struct player* seller, float secs) {
int random_number;
float sale_probability, random_probability;
sale_probability = secs*(logf((seller->inventory).numtitles) + logf(23*(seller->inventory).cdburners + 5))/(50.0);
sale_probability *= IDEAL_PRICE/seller->price;
random_number = rand();
random_probability = (float)random_number/RAND_MAX;
if(sale_probability > random_probability) {
//a sale occurred!
//does the user have a blank CD?
if((seller->inventory).cds > 0 && (seller->inventory).cdburners > 0) {
//remove a CD from the user's inventory, deposit cash in their account,
//and increment the total number of sales
(seller->inventory).cds--;
seller->cash += seller->price;
seller->total_sales++;
return;
}
if((seller->inventory).cds == 0 && (seller->inventory).cdburners == 0) {
print(seller->sock, "You do not have any CD burners or blank CDs! Lost sale!\n");
}
else if((seller->inventory).cds == 0) {
print(seller->sock, "You are out of CDs! Lost sale!\n");
}
else if((seller->inventory).cdburners == 0) {
print(seller->sock, "You do not have a CD Burner! Lost sale!\n");
}
}
}
/****************************************************************************
* void cheat(struct player* cheater)
* Some players may find out that there is a cheat code called "hongkong". If
* a user enters this cheat code, they get 50 free software titles!
* Furthermore, since these titles are on disk, they take up no hard drive
* space! However, if a user pushes his/her luck and enter the cheat code
* twice, they get arrested and lose the game.
****************************************************************************/
void cheat(struct player* cheater) {
if(cheater->cheated == 0) {
(cheater->inventory).numtitles += 50;
cheater->cheated = 1;
}
else {
print(cheater->sock, "BUSTED!\nYou've been arrested for smuggling pirated software.\nGame over.\n");
end_session(cheater);
}
}
/****************************************************************************
* void setprice(struct player* user, buffer)
* This function allows a user to set the price of their software. If one
* lowers the price of their software, they will make more sales, but at
* a lower profit.
****************************************************************************/
void setprice(struct player* user, char *buffer) {
float price;
char temp[255];
if(sscanf(buffer, "set price %f", &price) == 1) {
if(price <= 0) {
print(user->sock, "You must enter a positive price.\n");
return;
}
user->price = price;
}
sprintf(temp, "You will now sell your warez at the price of $%.2f/copy.\n", price);
print(user->sock, temp);
}
|