· 6 years ago · Jun 24, 2019, 09:04 AM
1from random import shuffle
2import os
3import cymysql
4from getpass import getpass
5import sys
6import re
7from bcrypt import hashpw, gensalt
8
9
10def shuffled_shoe():
11 shoe = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'A', 'J', 'Q', 'K']*4
12 shuffle(shoe)
13 return shoe
14
15
16def deal_card(shoe, person, number):
17 for _ in range(number):
18 person.append(shoe.pop())
19
20
21def deal_hand(shoe, player, dealer):
22 for _ in range(2):
23 deal_card(shoe, player, 1)
24 deal_card(shoe, dealer, 1)
25
26
27def score(person):
28 non_aces = (c for c in person if c != 'A')
29 aces = (c for c in person if c == 'A')
30 total = 0
31 for card in non_aces:
32 if card in 'JQK':
33 total += 10
34 else:
35 total += int(card)
36 for card in aces:
37 if total <= 10:
38 total += 11
39 else:
40 total += 1
41 return total
42
43
44def set_money(money, money_bet, win, push):
45 if win:
46 money += money_bet * 2
47 elif push:
48 money += money_bet
49 return money
50
51
52def clear_console():
53 os.system('cls' if os.name == 'nt' else 'clear')
54
55
56def display_info(still_playing, player, dealer, money, money_bet, player_stands):
57 win = False
58 push = False
59 clear_console()
60 print(f'Money: ${money}')
61 print(f'Money bet: ${money_bet}')
62 print('Your cards: [{}] ({})'.format(']['.join(player), score(player)))
63 if player_stands:
64 print('Dealer cards: [{}] ({})'.format(']['.join(dealer), score(dealer)))
65 else:
66 print('Dealer cards: [{}][?]'.format(dealer[0]))
67 first_hand = len(dealer) == 2
68 if score(player) == 21:
69 print('Blackjack! You won')
70 still_playing = False
71 win = True
72 elif first_hand and score(dealer) == 21:
73 print('Dealer got a blackjack. You lost!')
74 still_playing = False
75 elif score(player) > 21:
76 print('Busted! You lost!')
77 still_playing = False
78 if player_stands:
79 if score(dealer) > 21:
80 print('Dealer busted! You won')
81 win = True
82 elif score(player) > score(dealer):
83 print('You beat the dealer! You won!')
84 win = True
85 elif score(player) < score(dealer):
86 print('Dealer has beaten you. You lost!')
87 else:
88 print('Push. Nobody wins or losses.')
89 push = True
90 still_playing = False
91 money = set_money(money, money_bet, win, push)
92 return still_playing, money
93
94
95def hit_or_stand():
96 while True:
97 print('What do you choose?')
98 print('[1] - Hit')
99 print('[2] - Stand')
100 ans = input('> ')
101 if ans in '12':
102 return ans
103
104
105def bet(money):
106 clear_console()
107 print(f'Money: ${money}')
108 print('How much money do you want to bet?')
109 while True:
110 money_bet = int(input('> '))
111 if money_bet <= money and not money_bet <= 0:
112 money -= money_bet
113 return money, money_bet
114 print('Please enter a valid bet.')
115
116
117def player_play(shoe, player, dealer, money, money_bet, player_plays, player_stands):
118 while not player_stands:
119 if hit_or_stand() == '2':
120 player_stands = True
121 player_plays = False
122 elif not player_stands:
123 deal_card(shoe, player, 1)
124 display_info(True, player, dealer, money, money_bet, player_stands)
125 if score(player) >= 21:
126 player_plays = False
127 break
128 return player_plays, player_stands
129
130
131def dealer_play(shoe, dealer, dealer_minimum_score):
132 while score(dealer) <= dealer_minimum_score:
133 deal_card(shoe, dealer, 1)
134 return False
135
136
137def check_money(money):
138 if money == 0:
139 print('nUnfortunately you do not have any money.')
140 sys.exit()
141
142
143def update_db_money(cur, money, email):
144 cur.execute('UPDATE `users` SET `money`=%s WHERE `email`=%s', (money, email))
145
146
147def play_again(money):
148 check_money(money)
149 while True:
150 print('nDo you want to play again? [Y]es/[N]o')
151 ans = input('> ').lower()
152 if ans == 'y':
153 return True
154 elif ans == 'n':
155 return False
156
157
158def get_user_info():
159 while True:
160 email = input('Email address (max. 255 chars.): ')
161 password = getpass('Password (max. 255 chars.): ').encode('utf-8')
162 hashed_pw = hashpw(password, gensalt())
163 if len(email) < 255 and len(password) < 255:
164 if re.match(r'[^@]+@[^@]+.[^@]+', email):
165 return email, password, hashed_pw
166 print('Please enter a valid email address.')
167
168
169def register(cur, email, hashed_pw):
170 cur.execute('INSERT INTO `users` (`Email`, `Password`) VALUES (%s, %s)', (email, hashed_pw))
171
172
173def login(cur, email, password, hashed_pw):
174 cur.execute('SELECT * FROM `users` WHERE `Email`=%s LIMIT 1', (email,))
175 correct_credentials = cur.fetchone()
176 correct_hash = correct_credentials[2].encode('utf-8')
177 if hashpw(password, correct_hash) == correct_hash:
178 print('You have succesfully logged-in!')
179 else:
180 print('You failed logging-in!')
181 sys.exit()
182
183
184def check_account(cur, email):
185 cur.execute('SELECT * FROM `users` WHERE `Email`=%s LIMIT 1', (email,))
186 return bool(cur.fetchone())
187
188
189def display_top(cur):
190 cur.execute('SELECT * FROM `users` ORDER BY `money` DESC')
191 top = cur.fetchall()
192 places = range(1, len(top)+1)
193 for (a, b, c, d), i in zip(top, places):
194 print(f'{i}. {b} - ${d}')
195
196
197def start():
198 print('nWhat do you want to do?n1 - Start playingn2 - Display the top')
199 ans = input('> ')
200 if ans == '1':
201 return True
202 elif ans == '2':
203 return False
204
205
206def db_conn():
207 conn = cymysql.connect(
208 host='127.0.0.1',
209 user='root',
210 passwd='',
211 db='database'
212 )
213 with conn:
214 cur = conn.cursor()
215 email, password, hashed_pw = get_user_info()
216 checked = check_account(cur, email)
217 if checked:
218 login(cur, email, password, hashed_pw)
219 else:
220 register(cur, email, hashed_pw)
221 print('You have succesfully registered and recieved $1000 as a gift!')
222 cur.execute('SELECT `money` FROM `users` WHERE `email`=%s', (email,))
223 money_tuple = cur.fetchone()
224 money = money_tuple[0]
225 check_money(money)
226 return cur, money, email
227
228
229def main():
230 cur, money, email = db_conn()
231 keeps_playing = start()
232 if not keeps_playing:
233 display_top(cur)
234 while keeps_playing:
235 shoe = shuffled_shoe()
236 player = []
237 dealer = []
238 still_playing = True
239 player_plays = True
240 player_stands = False
241 money, money_bet = bet(money)
242 deal_hand(shoe, player, dealer)
243 still_playing, money = display_info(still_playing, player, dealer, money, money_bet, player_stands)
244 while still_playing:
245 while player_plays:
246 player_plays, player_stands = player_play(shoe, player, dealer, money, money_bet, player_plays, player_stands)
247 still_playing = dealer_play(shoe, dealer, 17)
248 still_playing, money = display_info(still_playing, player, dealer, money, money_bet, player_stands)
249 update_db_money(cur, money, email)
250 keeps_playing = play_again(money)
251 cur.close()
252
253
254if __name__ == '__main__':
255 main()
256
257SET NAMES utf8;
258SET time_zone = '+00:00';
259SET foreign_key_checks = 0;
260SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO';
261
262DROP TABLE IF EXISTS `users`;
263CREATE TABLE `users` (
264 `id` int(11) NOT NULL AUTO_INCREMENT,
265 `email` varchar(255) COLLATE utf8_bin NOT NULL,
266 `password` varchar(255) COLLATE utf8_bin NOT NULL,
267 `money` int(11) NOT NULL DEFAULT '1000',
268 PRIMARY KEY (`id`)
269) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin;