def __init__(self): """States the variables we will use""" self.lives = 4 self.console = Console() self.jumper = Jumper() self.word = Word()
def _addRandomWord(self): if 'randomPlayers' not in self._roundSettings or not self._roundSettings[ 'randomPlayers']: return if 'randomWordsLimit' not in self._roundSettings or not self._roundSettings[ 'randomWordsLimit']: return randomPlayersProcessed = 0 for randomPlayer in self._RANDOM_PLAYER: if randomPlayersProcessed >= self._roundSettings['randomPlayers']: break if not Player.get(telegram_id=randomPlayer['id']): Player.add(telegram_id=randomPlayer['id'], name=randomPlayer['first_name']) randomPlayersProcessed += 1 if Word.getListByRoundId(telegram_id=randomPlayer['id'], **self._gameState['query']): continue randomWordsCount = 0 wordsAdded = 0 while wordsAdded <= self._roundSettings['randomWordsLimit']: if randomWordsCount > 20: break randomWordsCount += 1 word = self._getRandom( "ushakov", wordMinLength=self._roundSettings['minWordsPerPlayer']) if not word: continue Word.add(word=word, player_id=Player.getId(randomPlayer), wordsLimit=self._roundSettings['randomWordsLimit'], wordMinLength=self._roundSettings['minWordLength'], **self._gameState['query']) wordsAdded += 1
def __init__(self): """Attributesof of the class""" """Objects of the class""" self.strikes = 0 # Strikes start at 0 self.jumper = Jumper() # Call the Jumper Class self.word = Word() # Call the Word Class self.output = Output() # Call the Output Class self.keep_playing = True # Keep playing while true self.guess = "" # Empty string to hold user letter input
def _make_words(self): """ This function makes word actors with random words pulled from the txt file. """ for i in range(random.randint(1, 2)): word = Word(self._get_random_word()) self._current_words.append(word) self._text_words.append(word.get_text())
def __init__(self): """The class constructor. Args: self (Director): an instance of Director. """ self.console = Console() self.parachuter = Parachuter() self.keep_playing = True self.word = Word()
def __init__(self): """ This method will inizialied the two list the one for the gues and the one with the word """ self.word = Word() self.random_word = [] self.guessed_letters = [] self.tries = 0 self.random_word = self.word.get_word() self.word_completion = "_" * len(self.random_word) self.play = True
def __init__(self): """The class constructor. Args: self (Director): an instance of Director. """ self.console = Console() self.jumper = Jumper() self.keep_playing = True self.word = Word() self.current_guess = ""
def __init__(self): """The class constructor. Args: self (Director): an instance of Director. """ self.console = Console() self.word = Word() #generate the word here. correctWord is generated on Word init self.jumper = Jumper(self.word.correctWord) #needs the correct word to generate length of underscore array self.keep_playing = True
def __init__(self, input_service, output_service): """The class constructor. Args: self (Director): an instance of Director. """ self._buffer = Buffer() self._input_service = input_service self._keep_playing = True self._output_service = output_service self._score = Score() self._word = Word()
def __init__(self): # Making an instance of each object. Ones commented out were not # available at the time. self.word = Word() # self.console = Console() # self.logic = Logic() # Game will continue unless endgame senario is reached. self.keep_playing = True # Used to check for when the user makes a bad guess. self.total_wrongs = 0
def _setup(self): # TODO create 5 words and add them to the list for i in range(5): text = "test" w = Word(text) self._words.append(w)
def getWordsListByAuthor(round_id): plainWorldsList = Word.getListByRoundId(round_id, fullAccess=True) parsedWordsList = {} for row in plainWorldsList: if row['telegram_id'] not in parsedWordsList: parsedWordsList[row['telegram_id']] = [row['name'], []] parsedWordsList[row['telegram_id']][1].append(row['word']) return parsedWordsList
class Director: """Director class engine of the program""" def __init__(self): """States the variables we will use""" self.lives = 4 self.console = Console() self.jumper = Jumper() self.word = Word() def start_game(self): """Starts the game""" self.console.write("Hello welcome to Jumper") # Get a word self.word.get_word() while self.lives >= 0: # Display word result = self.word.print_word() if result: self.console.write( "Congratulations you guessed the word correctly") break # Display the Jumper self.console.write(self.jumper.get_parachute(self.lives)) # Check if you lose if not self.lives: self.console.write("You killed him") break # Ask for a Guess guess = self.console.read("Guess a letter [a-z]: ") # Filters input result = self.word.check_guess(guess) if not result: continue # Saves guess and updates life result = self.word.save_guess(guess) if not result: self.lives -= 1
class Director: # Method initializer for the Director class def __init__(self): """Attributesof of the class""" """Objects of the class""" self.strikes = 0 # Strikes start at 0 self.jumper = Jumper() # Call the Jumper Class self.word = Word() # Call the Word Class self.output = Output() # Call the Output Class self.keep_playing = True # Keep playing while true self.guess = "" # Empty string to hold user letter input def start_game(self): """Start the game and keep playing until game ends or user ends it""" while self.keep_playing: # Calls print_blanks method from Output Class self.output.print_blanks(self.word) # Calls print_jumper method from Jumper Class self.output.print_jumper(self.strikes, self.jumper) self.get_letter() # Calls get_letter method # Get a strike if letter is not in the word if not self.word.check_letter(self.guess): # Abstraction: Pop removes an object from the list parachute and returns it self.jumper.parachute.pop(0) self.strikes += 1 # Add one to strike if self.strikes >= 4: # Check if strikes reaches the maximum self.output.print_blanks(self.word) self.output.print_jumper(self.strikes, self.jumper) self.output.print_loss() self.keep_playing = False # Change keep.playing to false = finished the game else: # If the guess letter matches a letter in the word # Call replace_blank method from Word Class self.word.replace_blank(self.guess) if self.word.check_blanks( ) == False: # Call check_blanks funtion to see if it is true or false self.output.print_blanks(self.word) self.output.print_win() # Call print_win from Output Class self.keep_playing = False # Change keep playing to false to end game def get_letter(self): self.guess = input("Guess a letter [a-z]: ") # Get a letter from user
def get(groupByGame=True, log_id=None, **params): groupsLog = DB.getList( """ SELECT log.*, round.number round_number, groups.number group_number, game.createDate game_createDate, round.createDate round_createDate, word.word winnerWord, player.name winnerPlayer_name FROM log JOIN round ON (round.id = log.round_id) JOIN game ON (game.id = log.game_id) JOIN groups ON (groups.id = log.group_id) JOIN word ON (word.id = log.winnerWord_id) JOIN player ON (player.id = log.winnerPlayer_id) WHERE log.game_id = %(game_id)s """ + ((" AND id=%d" % log_id) if log_id else ""), params) if not groupByGame: return groupsLog gamesLog = OrderedDict() for groupLog in groupsLog: if groupLog['game_id'] not in gamesLog: gamesLog[groupLog['game_id']] = dict( createDate=groupLog['game_createDate'].strftime( '%Y-%m-%d %H:%M:%S'), rounds=OrderedDict()) if groupLog['round_id'] not in gamesLog[ groupLog['game_id']]['rounds']: gamesLog[groupLog['game_id']]['rounds'][ groupLog['round_id']] = dict( createDate=groupLog['round_createDate'].strftime( '%Y-%m-%d %H:%M:%S'), number=groupLog['round_number'], groups=OrderedDict()) Word.getListByGroupNumber(round_id=groupLog['round_id'], groupNumber=groupLog['group_number']) groupLog['number'] = groupLog['group_number'] groupLog['data'] = json.loads(groupLog['data'], object_hook=OrderedDict) gamesLog[groupLog['game_id']]['rounds'][groupLog['round_id']][ 'groups'][groupLog['group_id']] = groupLog return gamesLog
def __init__(self): """"Class Constructor: will inizialite a list and get the word to be guess""" self.keep_playing = True self.guess = Guess() self.console = Console() self.word = Word() # This will draw the parachuse just one time self.tries = 0 self.user_letter = ""
def setPlayerState(self, update): self._refreshGameState(checkGameStatus=True) if self._gameState['roundStatus'] != Round.STATUS_PREPARATION: return "Поздняк метаться. Раунд уже запущен. Молись!" player_id = Player.getId(update.message.chat) playerWords = Word.getListByRoundId(player_id=player_id, **self._gameState['query']) if len(playerWords) < self._roundSettings['minWordsPerPlayer']: return "Надо предложить побольше словцов, чтобы быть готовым. Осталось предложить: %d/%d" % ( len(playerWords), self._roundSettings['minWordsPerPlayer']) return "Ты больше не готов к игре в этом раунде, трусиха" if not Player.setState(player_id=player_id, round_id=self._gameState['round_id']) else \ "Ты изготовился к игре. Удач!"
def _isPlayerCanVote(self, player_id, weight, word_id, word): groupNumber, groupWords = Group.getGroupByWord( word_id=word_id, **self._gameState['query']) votes, spentWeight = Vote.getPlayerWeightPerRoundByWord( player_id=player_id, **self._gameState['query']) if weight > self._roundSettings['maxWeightPerWord']: return False, "Нельзя наваливать так много баллов одному словцу (%d/%d)." % ( weight, self._roundSettings['maxWeightPerWord']) if word_id not in votes and (spentWeight + weight > self._roundSettings['maxWeightPerRound']): return False, """ Я не могу навалить %d баллов словцу <b>%s</b>. Ты уже потратил %d/%d на всякий мусор. """ % (weight, word, spentWeight, self._roundSettings['maxWeightPerRound']) if spentWeight >= self._roundSettings['maxWeightPerRound']: if word_id not in votes: return False, """ Опомнись! Ты уже потратил все свои баллы (%d/%d), чтобы голосовать за слово <b>%s</b>. """ % (spentWeight, self._roundSettings['maxWeightPerRound'], word) for existedVote in votes.values(): respentWeight = spentWeight - (existedVote['weight'] - weight) if existedVote['word_id'] == word_id and weight > existedVote[ 'weight'] and respentWeight > self._roundSettings[ 'maxWeightPerRound']: return False, """ Да не хватит тебе баллов, что бы повысить вес этого жалкого словца на столько (%d/%d) """ % (respentWeight, self._roundSettings['maxWeightPerRound']) if groupNumber == -1: return False, "Что-то не то. Слово <b>%s</b> найдено сразу в двух группах. Как же так-то?" % word if not groupNumber: return False, "Не могу найти группу, к которой принадлежит словоцо <b>%s</b>. Буду думать..." % word if weight > 0 and \ Word.isWordBelongToPlayer(player_id=player_id, word=word, **self._gameState['query']) and \ [word for word in groupWords if not Word.isWordBelongToPlayer(player_id=player_id, word=word, **self._gameState['query'])]: return False, """ Ты совесть-то поимей, подлец. Нельзя голосовать за свои словцы (в том числе и за <b>%s</b>), если на выбор есть словцы других игроков """ % word return True, None
def __init__(self, input_ser, output_ser): """The class constructor. Args: self (Director): an instance of Director. """ self._input_service = input_ser self._output_service = output_ser self._keep_playing = True self._player = Player() self._words = [] self._score = Score() for item in range(5): self._words.append(Word())
def getPlayerWordsByRound(self, round_id=None, fullAccess=False): """ :param round_id: int :param fullAccess: bool if True access to to all words otherwise your own :return: list of founded words """ self._refreshGameState() o = dict(game_id=self._gameState['query']['game_id'], player_id=self._playerState['id'], fullAccess=fullAccess, round_id=round_id if round_id else self._gameState['query']['round_id']) return Word.getListByRoundId(**o)
def addWord(self, update): """ Adds word into current round of the game :param update: dict with update info :return: str text response """ self._refreshGameState(checkGameStatus=True) if self._gameState['roundStatus'] != Round.STATUS_PREPARATION: return "Слишком поздно вертеть задом. Раунд уже началася. Дождись окончания раунда" return Word.add(word=update.message.text, player_id=self._playerState['id'], wordsLimit=self._roundSettings['minWordsPerPlayer'], wordMinLength=self._roundSettings['minWordLength'], **self._gameState['query'])[1]
def __init__(self, input_service, output_service): """The class constructor. Args: self (Director): an instance of Director. """ self._word = Word() self._input_service = input_service self._keep_playing = True self._output_service = output_service self._score = Score() self._speed = Speed() self._guess = Guess() self._actor = Actor() self.correct = 0
def __init__(self, input_service, output_service): """The class constructor. Args: self (Director): an instance of Director. """ self._input_service = input_service self._output_service = output_service self._buffer = Buffer() self._word = Word('test') self._current_words = [] self._text_words = [] self._inputted_letter = '' self._score = Score() self._keep_playing = True
def __init__(self, input_service, output_service): """The class constructor. Args: self (Director): an instance of Director. """ self.words = [] for x in range(5): #Generates 5 word actors newWord = Word() self.words.append(newWord) self._input_service = input_service self._keep_playing = True self._output_service = output_service self._score = Score() self._userinput = UserInput() self._timer = Timer()
def _getRandom(self, dictionaryName, wordMinLength=5, checkExistence=True): attemptsLimit = 10 attempt = 1 params = dict(wordMinLength=wordMinLength) if checkExistence: params['series_id'] = self._seriesState['id'] params['checkExistence'] = True else: params['series_id'] = None params['checkExistence'] = False while attempt <= attemptsLimit: attempt += 1 word = random.choice( list(open(self._DICTIONARIES[dictionaryName], encoding="utf-8"))) if Word.isWordValid(word=word, **params)[0]: return word return None
def updateWord(self, update, oldWord, newWord): """ Update player word :param update: dict with update info :param oldWord: :param newWord: :return: str with text response """ self._refreshGameState(checkGameStatus=True) player_id = Player.getId(update.message.chat) if self._gameState['roundStatus'] == Round.STATUS_IN_PROGRESS: return "Ахаха. Раунд-то уже начался. Поздно теперь крутить себе соски. Надейся на лучшее!" if Player.getState(player_id=player_id, **self._gameState['query']): return "Ты не можешь обновить своё убогое словцо, если ты уже приготовился играть, вонючка!" return Word.update(oldWord=oldWord, newWord=newWord, player_id=player_id, wordMinLength=self._roundSettings['minWordLength'], **self._gameState['query'])
def vote(self, update, weightPlain): self._refreshGameState(checkGameStatus=True) player_id = Player.getId(update.message.chat) if self._gameState['roundStatus'] == Round.STATUS_PREPARATION: return "Ещё слишком рано голосовать за словцы! Игра ещё не начата!" if self._gameState['roundStatus'] == Round.STATUS_ENDED: return "Уже поздновато отдавать свой никчёмный голос. Раунд завернёш. Жди начала следующего!" if not re.match(r"^(?:[А-яё]+[\s]*[\d]*[\s]*)+$", weightPlain): return "Ну ё-моё, передай мне свои баллы в правильном формате: \"Словцо 4 Словцо 5\"" weightParsed = re.findall(r"(?P<word>[А-яё]+)[\s]*(?P<weight>[\d]+)", weightPlain) responses = [] weightPlanned = sum([int(weight) for word, weight in weightParsed]) if weightPlanned > self._roundSettings['maxWeightPerRound']: return "Ты распределил слишком много баллов, дурашка (%d/%d)." % ( weightPlanned, self._roundSettings['maxWeightPerRound']) for word, weight in weightParsed: weight = int(weight) word_id = Word.getIdByName(word=word, **self._gameState['query']) if not word_id: return "Охохо! Нет такого словца в этой игре. Совсем. Проголосуй за правильное" voteStatus, response = self._isPlayerCanVote(player_id=player_id, weight=weight, word_id=word_id, word=word) if response: responses.append(response) if not voteStatus: continue Vote.set(word_id=word_id, weight=weight, player_id=player_id, **self._gameState['query']) responses.append( "Ура! Я успешно записал %d баллов словцу <b>%s</b>." % (weight, word)) return "\n".join(responses) + ( "\nТы просадил <b>%d</b>/%d" % (Vote.getPlayerSumOfWeightPerRound(player_id=player_id, **self._gameState['query']), self._roundSettings['maxWeightPerRound']))
def getCandidates(self, update): self._refreshGameState(checkGameStatus=True) self._addRandomWord() fullInfoWordsList = Word.getListByRoundId(fullAccess=True, **self._gameState['query']) wordsByPlayer = dict() randomPlayersList = [] for wordInfo in fullInfoWordsList: if wordInfo['telegram_id'] in self._RANDOM_PLAYER_IDS and wordInfo[ 'telegram_id'] not in randomPlayersList: randomPlayersList.append(wordInfo['telegram_id']) if wordInfo['player_id'] not in wordsByPlayer: wordsByPlayer[wordInfo['player_id']] = dict( words=[], isReady=Player.getState( player_id=wordInfo['player_id'], round_id=self._gameState['round_id']), name=wordInfo['name'], telegram_id=wordInfo['telegram_id'], player_id=wordInfo['player_id'], ) wordsByPlayer[wordInfo['player_id']]['words'].append( (wordInfo['id'], wordInfo['word'], wordInfo['player_id'])) unreadyPlayers = [ p['name'] for p in wordsByPlayer.values() if not p['isReady'] and p['telegram_id'] not in self._RANDOM_PLAYER_IDS ] if len(wordsByPlayer ) < self._roundSettings['minPlayers'] + len(randomPlayersList): return "Что-то маловато народца набралось для игры (%d/%d). Зови друзей" % ( len(wordsByPlayer) - len(randomPlayersList), self._roundSettings['minPlayers']) if len(wordsByPlayer ) > self._roundSettings['maxPlayers'] - len(randomPlayersList): return "Ого сколько вас набежало. Слишком много вас, а я один (%d/%d). Пошли вон!" % ( len(wordsByPlayer) + len(randomPlayersList), self._roundSettings['maxPlayers']) if unreadyPlayers: return "Слишком много тормозов в игре. Я не могу показать тебе словцы, пока все не будут готовы. Список тормозов:\n%s" % " ".join( unreadyPlayers) if self._gameState['roundStatus'] == Round.STATUS_PREPARATION: Round.updateRoundStatus(round_id=self._gameState['round_id'], status=Round.STATUS_IN_PROGRESS) wordsList = self._splitWordsIntoGroups([ word for wordsInfo in wordsByPlayer.values() for word in wordsInfo['words'] ]) return """ Вот список всех словцов. Кроме того я добавил в него несколько случайных (а может и нет). Хехе. Добавь вместо ноликов свои баллы. <b>%s</b> Суммарное максимальное количество баллов: %d Суммарное минимальное количество баллов: %d Максимальное количество баллов на слово: %d """ % ("\n".join([ "Группа %d: %s" % (i, " 0 ".join(w)) for i, w in wordsList.items() ]) + " 0", self._roundSettings['maxWeightPerRound'], self._roundSettings['minWeightPerRound'], self._roundSettings['maxWeightPerWord'])
def getPlayerWordsByGame(self, fullAccess=False): self._refreshGameState(checkGameStatus=True) return Word.getListByGameId(player_id=self._playerState['id'], fullAccess=fullAccess, **self._gameState['query'])
class Director: """A code template for a person who directs the game. The responsibility of this class of objects is to control the sequence of play. Stereotype: Controller Attributes: console (Console): An instance of the class of objects known as Console. keep_playing (boolean): Whether or not the game can continue. player (Player): An instance of the class of objects known as Player. word (Word): An instance of the class of objects known as Word. letter(Letter): """ def __init__(self): """The class constructor. Args: self (Director): an instance of Director. """ self.console = Console() self.player = Player() self.keep_playing = True self.word = Word() self.letter = "" def start_game(self): """Starts the game loop to control the sequence of play. Args: self (Director): an instance of Director. """ self.word.get_word() self.word.list_word() while self.keep_playing: self.get_inputs() self.do_updates() self.do_outputs() def get_inputs(self): """Gets the inputs at the beginning of each round of play. In this case, that means moving the hunter to a new location. Args: self (Director): An instance of Director. """ letter = self.player.get_letter() self.letter def do_updates(self): """Updates the important game information for each round of play. In this case, that means the rabbit watches the hunter. Args: self (Director): An instance of Director. """ self.console.check_letter(self.letter) def do_outputs(self): """Outputs the important game information for each round of play. In this case, that means the rabbit provides a hint. Args: self (Director): An instance of Director. """ self.word.secretWord self.console.create_parachute