Repository navigation
Expand file tree
/
Copy pathhand_cricket.py
More file actions
620 lines (552 loc) · 28.8 KB
/
Copy pathhand_cricket.py
File metadata and controls
620 lines (552 loc) · 28.8 KB
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
import sqlite3 as sqltor # importing required libraries
import random
import datetime
import pytz
import pandas as pd
import time
pd.options.mode.chained_assignment = None
def player_bats():
global player_4s
global player_6s
global player_bb
global comp_score
player_sum = 0
player_4s = 0
player_6s = 0
time.sleep(0.5)
print("You\'re batting!")
print("")
while True:
player_hit = input("Enter your number from 1 to 6: ")
player_hit_list = ["1", "2", "3", "4", "5", "6"]
while player_hit not in player_hit_list:
time.sleep(0.5)
print("Only throw a number from 1 to 6.")
print("")
time.sleep(0.5)
player_hit = input("Please enter your number: ")
player_hit = int(player_hit)
comp_bowl = random.randint(1, 6)
print("The computer threw", comp_bowl)
print("")
if player_hit == comp_bowl:
print("")
time.sleep(0.5)
print("You\'re out! You scored", player_sum, "runs.")
print("")
break
else:
player_sum += player_hit
if player_hit == 4:
player_4s += 1
elif player_hit == 6:
player_6s += 1
if player_bb == 2 and player_sum > comp_score:
print("You've won the game!")
break
return player_sum
def player_bowls():
global player_bb
global player_score
comp_sum = 0
print("You\'re bowling")
while True:
player_bowl = input("Enter your number from 1 to 6: ")
player_bowl_list = ["1", "2", "3", "4", "5", "6"]
while player_bowl not in player_bowl_list:
time.sleep(0.5)
print("Only throw a number from 1 to 6.")
print("")
time.sleep(0.5)
player_bowl = input("Please enter your number: ")
player_bowl = int(player_bowl)
comp_hit = random.randint(1, 6)
print("")
time.sleep(0.5)
print("The computer hit", comp_hit)
if player_bowl == comp_hit:
print("")
time.sleep(0.5)
print("You bowled the computer! It scored", comp_sum, "runs.")
break
else:
comp_sum += comp_hit
if player_bb == 1 and comp_sum > player_score:
print("")
time.sleep(0.5)
print("You've lost the game!")
break
return comp_sum
while True: # Keep the program running
print("""
=======================================
!!!!!!!!WELCOME TO HAND CRICKET!!!!!!!!
=======================================
""")
mycon = sqltor.connect('cs_proj.db') # Connecting to Database
cursor = mycon.cursor() # Creating cursor to execute queries
cursor.execute(
"create table if not exists user_data(user_name varchar(50), user_id varchar(50), password varchar(50), age int)") # create table user_data if it does not ex
cursor.execute(
"create table if not exists game_data(user_name varchar(50), date_played date, time_played time, toss_decision varchar(50), user_total_runs varchar(50), user_4s varchar(50), user_6s varchar(50), match_result varchar(100))")
cursor.execute("create table if not exists leaderboard(trial int)") # Create leaderboard table
while True:
time.sleep(0.5)
print("""
=====================
1. SIGN IN (LOGIN)
2. SIGN UP (REGISTER)
3. QUIT
=====================
""")
time.sleep(0.5)
user_choice = input("ENTER YOUR CHOICE: ") # Choice to login in or register
user_choice_list = ["1", "2", "3"]
while user_choice not in user_choice_list:
time.sleep(0.5)
print("Please enter a number from 1 to 3 only.")
print("")
time.sleep(0.5)
user_choice = input("Please enter your number: ")
cursor.execute("select user_name from user_data")
db_user_list = cursor.fetchall()
user_list = [] # Getting a list of all the usernames already in the database.
for i in db_user_list:
user_list.append(i[0])
if user_choice == '2': # REGISTER
time.sleep(0.5)
print("""
=======================================
!!!!!!!!PLEASE REGISTER YOURSELF!!!!!!!
=======================================
""")
while True:
time.sleep(0.5)
user_name = input("ENTER YOUR PREFERRED USERNAME: ")
# retrieve a list of all usernames already in database
if user_name in user_list: # Checking if name already in database.
print("USERNAME ALREADY USED. ENTER A DIFFERENT USERNAME")
print("")
else:
print("")
break
user_id = random.randint(10000, 99999) # Assigning a random user id
time.sleep(0.5)
print("YOUR USER ID IS", user_id)
time.sleep(0.5)
print("THERE IS NO NEED TO REMEMBER THE USER ID")
print("")
time.sleep(0.5)
user_passwd = input("ENTER YOUR PASSWORD: ")
print("")
time.sleep(0.5)
confirm_passwd = input("PLEASE RE-ENTER PASSWORD TO CONFIRM: ")
while user_passwd != confirm_passwd: # Checking if pass and confirm pass are same
print("PASSWORD DOES NOT MATCH! PLEASE ENTER AGAIN.")
print("")
time.sleep(0.5)
confirm_passwd = input("PLEASE RE-ENTER PASSWORD TO CONFIRM: ")
print("")
time.sleep(0.5)
user_age = int(input("ENTER YOUR AGE: "))
print("")
time.sleep(0.5)
print("PLEASE ENSURE THAT YOU REMEMBER YOUR USER ID AND PASSWORD!")
time.sleep(1)
# inserting the registration details into the database.
cursor.execute(
"insert into user_data values('" + user_name + "', " + str(user_id) + ", '" + user_passwd + "', " + str(
user_age) + ")")
cursor.execute("COMMIT")
print("""
=======================================
!!!!!!!!REGISTERED SUCCESSFULLY!!!!!!!!
=======================================
""")
continue
elif user_choice == '1': # lOG IN
print("")
time.sleep(0.5)
print("""
=======================================
!!!!!!!!!!ENTER LOGIN DETAILS!!!!!!!!!!
=======================================
Enter 'back' to go back at any point.
""")
print("")
time.sleep(0.5)
user_name = input("ENTER YOUR USERNAME: ")
if user_name == 'back':
continue
while user_name not in user_list: # Check if user in database.
time.sleep(0.5)
print("USER NOT FOUND. PLEASE ENTER USERNAME AGAIN.")
print("")
user_name = input("ENTER YOUR USERNAME: ")
if user_name == 'back':
break
if user_name == 'back':
continue
cursor.execute("select user_id from user_data where user_name = '" + user_name + "'")
db_user_id = cursor.fetchone()
db_user_id = db_user_id[0]
print("")
time.sleep(0.5)
user_passwd = input("PLEASE ENTER YOUR PASSWORD: ")
if user_passwd == 'back':
continue
cursor.execute("select password from user_data where user_name = '" + user_name + "'")
db_user_passwd = cursor.fetchone()
db_user_passwd = db_user_passwd[0]
passcheck = 0
while db_user_passwd != user_passwd: # Check if entered password matches the one in the database.
passcheck += 1
if passcheck >= 3:
print("")
time.sleep(0.5)
print("YOU HAVE ENTERED THE INCORRECT PASSWORD THRICE IN A ROW. PLEASE TRY SIGNING IN AGAIN.")
time.sleep(0.5)
break
time.sleep(0.5)
print("WRONG PASSWORD! PLEASE RE-ENTER")
print("")
time.sleep(0.5)
user_passwd = input("PLEASE ENTER YOUR PASSWORD: ")
if user_passwd == 'back':
break
if passcheck >= 3 or user_passwd == 'back':
continue
print("")
time.sleep(0.5)
print("""
=======================================
!!!!!!!!!LOGGED IN SUCCESSFULLY!!!!!!!!
=======================================
""")
while True:
time.sleep(0.5)
print("""
========================
1. Play Game...........1
2. View Your History...2
3. View Leaderboard....3
4. Logout..............4
======================== \n""")
user_choice_1 = input("ENTER YOUR CHOICE: ")
user_choice_1_list = ["1", "2", "3", "4"]
while user_choice_1 not in user_choice_1_list:
time.sleep(0.5)
print("Please enter a number from 1 to 4 only.")
print("")
time.sleep(0.5)
user_choice_1 = input("Please enter your number: ")
if user_choice_1 == '1':
while True:
gamestartdate = str(datetime.date.today())
gamestarttime = str(datetime.datetime.now().strftime("%H:%M:%S"))
print("")
time.sleep(0.5)
showrules = input("Do you wish to see the game rules? (y/n)...: ")
while showrules != 'y' and showrules != 'n':
print("Please enter y or n only")
print("")
time.sleep(0.5)
showrules = input("Do you wish to see the game rules? (y/n)...: ")
if showrules == 'y':
# display all the rules
print("""Here are the rules of the game!:
1) You\'ll be playing hand cricket against a computer.
2) We need to decide who\'ll bat and who'll bowl!
3) We\'ll do this using the \'odd-eve\' method.
4) First, you\'ll pick either \'odd\' or \'eve\'.
5) Then you\'ll choose a number between 1 and 6.
5) Then, the computer will roll a random number between 1 and 6.
6) If the sum of the two numbers matches your selection of odd or even,
you\'ll pick whether you want to bat or bowl.
7) If it doesn\'t match, the computer will randomly select to bat or bowl.
8) RULES FOR WHEN YOU\'RE BATTING:
a) You and the computer will pick a number between 1 and 6.
b) If the numbers are different, your number will be added to your total.
c) If the numbers are the same, you\'ll receive a \'wicket\'.
It means that your player is out.
d) Once all your players are out, the inning ends.
e) If you batted first, it becomes your turn to bowl,
and the computer\'s turn to bat.
f) If you batted last, the game ends.
9) RULES FOR WHEN YOU\'RE BOWLING:
a) You and the computer will pick a number between 1 and 6.
b) If the numbers are different, the computer\'s number will be added to its total.
c) If the numbers are the same, the computer\'ll receive a \'wicket\'.
It means that its player is out.
d) Once all its players are out, the inning ends.
e) If you bowled first, it becomes your turn to bat,
and the computer\'s turn to bowl.
f) If you bowled last, the game ends.
10)If you scored more runs than the computer in your inning, you win!
""")
# odd-eve
print("")
time.sleep(0.5)
player_oe = input("Choose Odd or Even (o/e): ")
while player_oe.lower() != 'o' and player_oe.lower() != 'e':
print("Please enter a valid option.")
print("")
time.sleep(0.5)
player_oe = input("Choose Odd or Even (o/e): ")
player_oe = player_oe.lower()
comp_toss = random.randint(1, 6)
print("")
time.sleep(0.5)
player_toss = input("Enter your number between 1 and 6: ")
while True:
if not player_toss.isnumeric():
player_toss = input("Please enter a number between 1 and 6:")
elif int(player_toss) not in range(1, 7):
player_toss = input("Please enter a number between 1 and 6:")
else:
break
player_toss = int(player_toss)
print("The computer chose", comp_toss)
toss_sum = comp_toss + player_toss
sum_oe = ''
pbat_bowl = ''
if toss_sum % 2 == 0:
sum_oe = 'e'
else:
sum_oe = 'o'
if player_oe == sum_oe:
toss_decision = "You won the odd-eve! :D"
print("")
time.sleep(0.5)
print(toss_decision)
print("")
time.sleep(0.5)
pbat_bowl = input("Would you like to bat or bowl? (1/2): ")
else:
toss_decision = "You lost the odd-eve :("
print("")
time.sleep(0.5)
print(toss_decision)
comp_bb = random.randint(1, 2)
if comp_bb == 1:
pbat_bowl = '1'
else:
pbat_bowl = '2'
player_bb = int(pbat_bowl)
if player_bb == 1:
player_score = player_bats()
print("")
time.sleep(0.5)
print('Now it\'s the computer\'s turn to bat.')
comp_score = player_bowls()
elif player_bb == 2:
comp_score = player_bowls()
print("")
time.sleep(0.5)
print('Now it\'s your turn to bat.')
player_score = player_bats()
win_margin = player_score - comp_score
if win_margin > 0:
match_result = "Congratulations! You won by " + str(win_margin) + " runs. :D"
print("")
time.sleep(0.5)
print(match_result)
elif win_margin == 0:
match_result = "It's a tie`!`"
print("")
time.sleep(0.5)
print(match_result)
elif player_bb == 2:
match_result = "Too bad, you lost by " + str(win_margin)[1:] + " runs :("
print("")
time.sleep(0.5)
print(match_result)
else:
match_result = "Too bad, you lost :("
print("")
time.sleep(0.5)
print(match_result)
gameenddate = str(datetime.date.today())
gameendtime = str(datetime.datetime.now().strftime("%H:%M:%S"))
db_user_id = str(db_user_id)
player_score = str(player_score)
player_4s = str(player_4s)
player_6s = str(player_6s)
cursor.execute(
"insert into game_data values('" + user_name + "', '" + gamestartdate + "', '" + gamestarttime + "', '" + toss_decision + "', '" + player_score + "', '" + player_4s + "', '" + player_6s + "', '" + match_result + "')")
cursor.execute("COMMIT")
while True:
again = input("Would you like to play again? (y/n): ")
if again.lower() != 'y' and again.lower() != 'n':
print("Please enter a valid option.")
else:
break
if again.lower() == 'y':
continue
elif again.lower() == 'n':
break
elif user_choice_1 == '2':
print("")
time.sleep(0.5)
print("SHOWING YOUR GAMING HISTORY...")
print("")
time.sleep(1)
print("LOADING...")
print("")
time.sleep(1)
user_games_data = cursor.execute("select*from game_data where user_name = '" + user_name + "'")
data = cursor.fetchall()
import pandas as pd
pd_data = []
pd_data_lst = []
for i in range(len(data)):
pd_data_lst = []
for j in range(len(data[i])):
pd_data_lst.append(data[i][j])
pd_data.append(pd_data_lst)
columns_sql = ['User_Name', 'Date_Played', 'Time_Played', 'Toss_Decision', 'User_Total_Runs', 'User_4s',
'User_6s', 'Match_Result']
df = pd.DataFrame(data=pd_data, columns=columns_sql)
df['Time_Played'] = df['Time_Played'].astype(str)
for i in range(len(df['Time_Played'])):
time_played = str(df['Time_Played'][i])
time_played = time_played.lstrip("0 days ")
df['Time_Played'][i] = time_played
print("=========================================================================================================================================")
print_stats_statement = "PLAYER '"+user_name+"' GAMING HISTORY"
print(print_stats_statement.center(140))
print("=========================================================================================================================================")
print(df.to_string(index=False))
print("=========================================================================================================================================")
print("")
time.sleep(1)
elif user_choice_1 == '3':
print("")
time.sleep(0.5)
print("SHOWING THE LEADERBOARDS...")
print("")
time.sleep(1)
print("LOADING...")
print("")
time.sleep(1)
cursor.execute(
"alter table game_data modify column user_total_runs int, modify column user_4s int, modify column user_6s int")
most_4s_db_1m = cursor.execute("select user_name, user_4s from game_data order by user_4s desc")
most_4s_1m = cursor.fetchall()
most_4s_value_1m = most_4s_1m[0][1]
most_4s_user_name_1m = []
if most_4s_value_1m == 0:
most_4s_user_name_1m = 'None'
else:
for i in most_4s_1m:
if i[1] == most_4s_value_1m:
most_4s_user_name_1m.append(i[0])
most_6s_db_1m = cursor.execute("select user_name, user_6s from game_data order by user_6s desc")
most_6s_1m = cursor.fetchall()
most_6s_value_1m = most_6s_1m[0][1]
most_6s_user_name_1m = []
if most_6s_value_1m == 0:
most_6s_user_name_1m = 'None'
else:
for i in most_6s_1m:
if i[1] == most_6s_value_1m:
most_6s_user_name_1m.append(i[0])
most_runs_db_1m = cursor.execute(
"select user_name, user_total_runs from game_data order by user_total_runs desc")
most_runs_1m = cursor.fetchall()
most_runs_value_1m = most_runs_1m[0][1]
most_runs_user_name_1m = []
if most_runs_value_1m == 0:
most_runs_user_name_1m = 'None'
else:
for i in most_runs_1m:
if i[1] == most_runs_value_1m:
most_runs_user_name_1m.append(i[0])
most_games_db = cursor.execute(
"select user_name, count(user_name) as count from game_data group by user_name order by count desc")
most_games = cursor.fetchall()
most_games_value = most_games[0][1]
most_games_user_name = []
if most_games_value == 0:
most_games_user_name_1m = 'None'
else:
for i in most_games:
if i[1] == most_games_value:
most_games_user_name.append(i[0])
leading_run_scorer_db = cursor.execute(
"select user_name, sum(user_total_runs) as total_runs from game_data group by user_name order by total_runs desc")
leading_run_scorer = cursor.fetchall()
leading_run_scorer_value = leading_run_scorer[0][1]
leading_run_scorer_user_name = []
if leading_run_scorer_value == 0:
leading_run_scorer_user_name = 'None'
else:
for i in leading_run_scorer:
if i[1] == leading_run_scorer_value:
leading_run_scorer_user_name.append(i[0])
leading_6s_db = cursor.execute(
"select user_name, sum(user_6s) as total_6s from game_data group by user_name order by total_6s desc")
leading_6s = cursor.fetchall()
leading_6s_value = leading_6s[0][1]
leading_6s_user_name = []
if leading_6s_value == 0:
leading_6s_user_name = 'None'
else:
for i in leading_6s:
if i[1] == leading_6s_value:
leading_6s_user_name.append(i[0])
leading_4s_db = cursor.execute(
"select user_name, sum(user_4s) as total_4s from game_data group by user_name order by total_4s desc")
leading_4s = cursor.fetchall()
leading_4s_value = leading_4s[0][1]
leading_4s_user_name = []
if leading_4s_value == 0:
leading_4s_user_name = 'None'
else:
for i in leading_4s:
if i[1] == leading_4s_value:
leading_4s_user_name.append(i[0])
leaderboard_index = ['Most Games Played', 'Leading Run Scorer', 'Most Runs Single Match',
'Highest 4s Single Match', 'Highest 6s Single Match', 'Highest 4s Career',
'Highest 6s Career', ]
leaderboard_user_name = [most_games_user_name, leading_run_scorer_user_name, most_runs_user_name_1m,
most_4s_user_name_1m, most_6s_user_name_1m, leading_4s_user_name,
leading_6s_user_name]
leaderboard_values = [most_games_value, leading_run_scorer_value, most_runs_value_1m,
most_4s_value_1m, most_6s_value_1m, leading_4s_value, leading_6s_value]
leaderboard_table = pd.DataFrame(
data={'Category': leaderboard_index, 'User_name': leaderboard_user_name,
'Values': leaderboard_values})
time.sleep(0.5)
print("===================================================")
print(" LEADERBOARD ")
print("===================================================")
print(leaderboard_table.to_string(index=False))
print("===================================================")
print("")
time.sleep(1)
continue
elif user_choice_1 == '4':
print("")
time.sleep(0.5)
print("YOU ARE NOW BEING LOGGED OUT.")
print("")
time.sleep(1)
print("YOU HAVE BEEN LOGGED OUT")
break
else:
time.sleep(0.5)
print("Please enter a valid option.")
elif user_choice == '3':
break
else:
print("")
time.sleep(0.5)
print("PLEASE ENTER A VALID OPTION.")
if user_choice == '3':
print("")
time.sleep(1)
print("THANKS FOR PLAYING! WE HOPE YOU HAD A FUN TIME :)")
cursor.close()
mycon.close()
break