Skip to content

Commit 5051e95

Browse files
committed
Merge pull request #57 from d-Rickyy-b/dev
Add new features and fixes
2 parents 886b974 + ca0e8d8 commit 5051e95

File tree

11 files changed

+1003
-870
lines changed

11 files changed

+1003
-870
lines changed

README.md

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@
44

55
This is the code for my Telegram Bot with which you can play the game Black Jack. You can find it here: https://telegram.me/BlackJackBot
66

7-
The main file, which needs to be executed is "main.py".
8-
You need to put your API-Token in the right place.
7+
The main file, which needs to be executed is 'main.py'.
8+
You need to put your API-Token in the right place in the main file.
99

1010
## Other Software
1111

@@ -15,10 +15,4 @@ The bot uses the [python-telegram-bot](https://python-telegram-bot.org/) framewo
1515

1616
## Database
1717

18-
The bot uses a SQLite database. The database file is in the "database" directory. It is called 'users.db'.
19-
20-
To set up the database, you need two tables:
21-
22-
1) ```CREATE TABLE 'admins' ('userID' INTEGER NOT NULL, 'first_name' TEXT, 'username' TEXT, PRIMARY KEY('userID'));```
23-
24-
2) ```CREATE TABLE 'users' ('userID' INTEGER NOT NULL, 'languageID' TEXT, 'first_name' TEXT, 'last_name' TEXT, 'username' TEXT, 'gamesPlayed' INTEGER, 'gamesWon' INTEGER, 'gamesTie' INTEGER, 'lastPlayed' INTEGER, PRIMARY KEY('userID'));```
18+
The bot uses a SQLite database. The database file is in the "database" directory. It is called 'users.db'. The database gets auto-generated, if it doesn't exist. Make sure the program has write access to the database directory.

database/db_wrapper.py

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,14 +17,15 @@ def __init__(self):
1717
print("File '" + database_path + "' does not exist! Trying to create one.")
1818
try:
1919
self.create_database(database_path)
20-
except:
20+
except Exception:
2121
print("An error has occurred while creating the database!")
2222

2323
self.connection = sqlite3.connect(database_path)
2424
self.connection.text_factory = lambda x: str(x, 'utf-8', "ignore")
2525
self.cursor = self.connection.cursor()
2626

27-
def create_database(self, database_path: str) -> None:
27+
@staticmethod
28+
def create_database(database_path: str) -> None:
2829
# Create database file and add admin and users table to the database
2930
open(database_path, 'a').close()
3031

@@ -62,16 +63,20 @@ def get_user(self, user_id: int) -> tuple:
6263
return ()
6364

6465
def get_recent_players(self):
65-
oneDayInSecs = 60 * 60 * 24
66-
currentTime = int(time())
67-
self.cursor.execute("SELECT userID FROM users WHERE lastPlayed>=?;", [currentTime - oneDayInSecs])
66+
one_day_in_secs = 60 * 60 * 24
67+
current_time = int(time())
68+
self.cursor.execute("SELECT userID FROM users WHERE lastPlayed>=?;", [current_time - one_day_in_secs])
6869

6970
return self.cursor.fetchall()
7071

7172
def get_played_games(self, user_id: int) -> int:
7273
self.cursor.execute("SELECT gamesPlayed FROM users WHERE userID=?;", [str(user_id)])
7374

7475
result = self.cursor.fetchone()
76+
77+
if not result:
78+
return 0
79+
7580
if len(result) > 0:
7681
return int(result[0])
7782
else:
Lines changed: 146 additions & 130 deletions
Large diffs are not rendered by default.

game/card.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# -*- coding: utf-8 -*-
2+
3+
4+
class Card(object):
5+
symbols = ["♥", "♦", "♣", "♠"]
6+
value_int = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
7+
8+
@property
9+
def symbol(self):
10+
return self.symbols[self.card_id // 13]
11+
12+
@property
13+
def value(self):
14+
return self.value_int[self.card_id % 13]
15+
16+
@property
17+
def face(self):
18+
return self.value_str[self.card_id % 13]
19+
20+
def __str__(self):
21+
return "|{} {}|".format(self.symbol, self.face)
22+
23+
def __init__(self, card_id: int, value_str: list) -> None:
24+
self.card_id = card_id
25+
self.value_str = value_str

game/deck.py

Lines changed: 12 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,28 @@
11
# -*- coding: utf-8 -*-
22

3+
from random import shuffle
4+
5+
from game.card import Card
36
from lang.language import translate
47

58
__author__ = 'Rico'
69

710

811
class CardDeck(object):
9-
symbols = ["♥", "♦", "♣", "♠"]
10-
valueInt = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
11-
1212
def create_deck(self) -> list:
13-
from random import shuffle
14-
deck = list(range(1, 52))
15-
shuffle(deck)
16-
return deck[:]
13+
deck = []
1714

18-
def pick_one_card(self) -> int:
19-
card = self.deck[0]
20-
self.deck.pop(0)
21-
return card
15+
for card_id in range(1, 52):
16+
deck.append(Card(card_id, self.value_str))
2217

23-
def get_card_name(self, card: int) -> str:
24-
symbol = self.symbols[card // 13]
25-
value = self.value_str[card % 13]
26-
card_name = "|" + symbol + " " + value + "|"
27-
return card_name
18+
shuffle(deck)
19+
return deck[:]
2820

29-
def get_card_value(self, card: int) -> int:
30-
return self.valueInt[card % 13]
21+
def pick_one_card(self) -> Card:
22+
return self.deck.pop(0)
3123

3224
def __init__(self, lang_id: str) -> None:
33-
self.deck = self.create_deck()
25+
self.lang_id = lang_id
3426
self.value_str = [translate("ace", lang_id), "2", "3", "4", "5", "6", "7", "8", "9", "10",
3527
translate("jack", lang_id), translate("queen", lang_id), translate("king", lang_id)]
28+
self.deck = self.create_deck()

game/player.py

Lines changed: 24 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,51 +1,50 @@
11
# -*- coding: utf-8 -*-
22

3+
from game.card import Card
4+
35
__author__ = 'Rico'
46

57

68
class Player(object):
7-
def give_card(self, card, value):
9+
def give_card(self, card: Card):
810
self.cards.append(card)
911

10-
if value == 1 and self.cardvalue <= 10:
11-
value = 11
12+
if card.value == 11 and self.__cardvalue <= 10:
1213
self.give_ace()
14+
elif card.value == 11 and (self.__cardvalue + 11) > 21:
15+
self.__cardvalue += 1
16+
return
1317

14-
self.cardvalue += value
15-
self.number_of_cards += 1
18+
self.__cardvalue += card.value
1619

1720
def give_ace(self):
1821
self.has_ace = True
1922

2023
def remove_ace(self):
2124
self.has_ace = False
22-
self.cardvalue -= 10
23-
24-
def has21(self):
25-
return self.cardvalue == 21
26-
27-
def has_busted(self):
28-
return self.cardvalue > 21
25+
self.__cardvalue -= 10
2926

3027
def has_cards(self):
3128
return len(self.cards) > 0
3229

3330
def get_cards_string(self):
3431
cards_string = ""
3532
for i, card in enumerate(self.cards):
36-
cards_string += self.deck.get_card_name(card)
33+
cards_string += str(card)
3734
if i + 1 < len(self.cards):
3835
cards_string += ", "
3936
return cards_string
4037

4138
def get_number_of_cards(self):
42-
return self.number_of_cards
39+
return len(self.cards)
4340

44-
def get_first_name(self):
45-
return self.first_name
41+
@property
42+
def cardvalue(self):
43+
return self.__cardvalue
4644

47-
def get_cardvalue(self):
48-
return self.cardvalue
45+
@property
46+
def first_name(self):
47+
return self.__first_name
4948

5049
@property
5150
def user_id(self):
@@ -55,16 +54,15 @@ def user_id(self):
5554
def join_id(self):
5655
return self.__join_id
5756

58-
def get_lang_id(self):
59-
return self.lang_id
57+
@property
58+
def lang_id(self):
59+
return self.__lang_id
6060

61-
def __init__(self, user_id, first_name, deck, join_id, lang_id="en"):
61+
def __init__(self, user_id, first_name, join_id, lang_id="en"):
6262
self.__user_id = user_id
63-
self.first_name = first_name
63+
self.__first_name = first_name
6464
self.__join_id = join_id
65-
self.lang_id = lang_id
66-
self.deck = deck
67-
self.number_of_cards = 0
68-
self.cardvalue = 0
65+
self.__lang_id = lang_id
66+
self.__cardvalue = 0
6967
self.has_ace = False
7068
self.cards = []

gamehandler.py

Lines changed: 69 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -2,71 +2,88 @@
22

33
import random
44
import string
5+
from typing import Optional
6+
7+
from game.blackJackGame import BlackJackGame
58

69
__author__ = 'Rico'
710

811

9-
# game_handler handles the blackJack-game-objects. When a new object is created, it is saved in "GameList"
10-
# get_index_by_chatid returns the index of a running game in the list
12+
# game_handler handles the blackJack-game-objects. When a new game is created, it is saved in the "game_list"
1113
class GameHandler(object):
12-
GameList = [] # List, where the running Games are stored in
13-
14-
def gl_create(self):
15-
self.GameList = []
16-
17-
def gl_remove(self, chat_id):
18-
index = self.get_index_by_chatid(chat_id)
19-
if index is None:
20-
return
21-
if not index < 0:
22-
self.GameList.pop(index)
23-
24-
def add_game(self, blackjackgame):
25-
self.GameList.append(blackjackgame)
26-
27-
def get_index_by_chatid(self, chat_id):
28-
for index, game in enumerate(self.GameList):
29-
if game.chat_id == chat_id:
30-
return index
31-
else:
32-
for player in game.players:
33-
if player.user_id == chat_id:
34-
return index
35-
36-
return None
37-
38-
def get_game_by_chatid(self, chat_id):
39-
index = self.get_index_by_chatid(chat_id)
40-
if index is None:
14+
class __GameHandler(object):
15+
def __init__(self):
16+
self.game_list = [] # List, where the running Games are stored in
17+
pass
18+
19+
def gl_create(self) -> None:
20+
self.game_list = []
21+
22+
def gl_remove(self, chat_id: int) -> None:
23+
index = self.get_index_by_chatid(chat_id)
24+
if index is None:
25+
return
26+
if not index < 0:
27+
self.game_list.pop(index)
28+
29+
def get_index_by_chatid(self, chat_id: int) -> Optional[int]:
30+
for index, game in enumerate(self.game_list):
31+
if game.chat_id == chat_id:
32+
return index
33+
else:
34+
for player in game.players:
35+
if player.user_id == chat_id:
36+
return index
37+
4138
return None
42-
return self.GameList[index]
4339

44-
def get_game_by_index(self, index):
45-
return self.GameList[index]
40+
def add_game(self, blackjackgame: BlackJackGame) -> None:
41+
self.game_list.append(blackjackgame)
4642

47-
def get_game_by_id(self, game_id):
48-
if game_id is None:
49-
return None
50-
for game in self.GameList:
51-
if game.get_game_id() == game_id:
52-
return game
53-
return None
43+
def get_game_by_chatid(self, chat_id: int) -> Optional[BlackJackGame]:
44+
index = self.get_index_by_chatid(chat_id)
45+
if index is None:
46+
return None
47+
return self.game_list[index]
5448

55-
def generate_id(self):
56-
game_id = ''.join(random.choice(string.digits + string.ascii_letters) for _ in range(8))
49+
def get_game_by_index(self, index: int) -> BlackJackGame:
50+
return self.game_list[index]
51+
52+
def get_game_by_id(self, game_id: int) -> Optional[BlackJackGame]:
53+
if game_id is None:
54+
return None
55+
for game in self.game_list:
56+
if game.game_id == game_id:
57+
return game
58+
return None
5759

58-
while self.id_already_existing(game_id):
59-
print("ID already existing: " + str(game_id))
60+
def generate_id(self) -> str:
61+
"""Generates a random ID for a game"""
6062
game_id = ''.join(random.choice(string.digits + string.ascii_letters) for _ in range(8))
6163

62-
return game_id
64+
while self.id_already_existing(game_id):
65+
print("ID already existing: " + str(game_id))
66+
game_id = ''.join(random.choice(string.digits + string.ascii_letters) for _ in range(8))
6367

64-
def id_already_existing(self, game_id):
65-
for game in self.GameList:
66-
if game.get_game_id() == game_id:
67-
return True
68+
return game_id
6869

69-
return False
70+
def id_already_existing(self, game_id: str) -> bool:
71+
"""Checks if an ID is already existing in the list of games"""
72+
for game in self.game_list:
73+
if game.game_id == game_id:
74+
return True
75+
76+
return False
77+
78+
instance = None
7079

7180
def __init__(self):
72-
self.GameList = []
81+
if not GameHandler.instance:
82+
GameHandler.instance = GameHandler.__GameHandler()
83+
84+
@staticmethod
85+
def get_instance() -> __GameHandler:
86+
if not GameHandler.instance:
87+
GameHandler.instance = GameHandler.__GameHandler()
88+
89+
return GameHandler.instance

lang/language.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,22 @@
1414

1515
# translate returns the translation for a specific string
1616
def translate(string: str, language: str) -> str:
17+
"""Returns the translation in a specific language for a specific string"""
1718
if language in translations and string in translations[language]:
1819
return translations[language][string]
1920
elif language == "br":
2021
return translations["pt_BR"][string]
2122
elif "en" in translations and string in translations["en"]:
2223
return translations["en"][string]
2324
return string
25+
26+
27+
def translate_all(string: str) -> set:
28+
"""Returns all the translations of a specific string"""
29+
strings = []
30+
lang_list = ["de", "en", "nl", "eo", "br", "es", "ru", "fa"]
31+
32+
for lang in lang_list:
33+
strings.append(translate(string, lang))
34+
35+
return set(strings)

0 commit comments

Comments
 (0)