def make_move(self, request): """Make a move. Returns current game state""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if not game: raise endpoints.NotFoundException('Game not found') if game.gameOver: raise endpoints.NotFoundException('Game is over') player = Player.get_player_by_name(request.name) # check if player has next move if player.key != game.nextMove: raise endpoints.BadRequestException('It is not your turn') # check if input for move numeric if request.move.isnumeric() == False: raise endpoints.BadRequestException( 'Please input a number for move') move = int(float(request.move)) # check if input for move within 9 if move in range(9): if game.board[move] != '': raise endpoints.BadRequestException( 'The block has been filled') # x is true when is player one's turn; false when player two's turn x = True if player.key == game.playerOne else False game.board[move] = 'X' if x else 'O' game.nextMove = game.playerTwo if x else game.playerOne # check if there is a winner winner = check_winner(game.board) if winner: game.endGame(player.key) winner = game.winner.get().name else: if check_full(game.board): # tie game.endGame() winner = 'None' game.history.append(('X' if x else 'O', 'Move: ' + str(move), 'Played by: ' + request.name, 'Next Move: ' + game.nextMove.get().name, 'Game Over: ' + str(game.gameOver), 'Tie: ' + str(game.tie), 'Winner: ' + winner, )) game.put() else: raise endpoints.BadRequestException( 'Input for move can only be 0~8') return game.copy_game_to_form()
def make_move(self, request): """Makes a move. Returns a game state with message""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if not game: raise endpoints.NotFoundException('Game not found') if game.game_over: return game.to_form('Game already over!') # prevent a user from playing twice in a row user = User.get_current_user(request.user_name) if user.key != game.nextMove: raise endpoints.BadRequestException('It\'s not your turn!') x = True if user.key == game.player_x else False # Make a move, and verify if the move is a valid move move = request.move size = game.boardSize * game.boardSize - 1 if move < 0 or move > size: raise endpoints.BadRequestException('Bad Move!') if game.board[move] != '': raise endpoints.BadRequestException('Invalid Move') # Make a move, and send the move to game history game.board[move] = 'X' if x else 'O' game.game_history.append(('X' if x else 'O', move)) game.nextMove = game.player_o if x else game.player_x #Check if there is a winner in the game and end the game winner = check_winner(game.board, game.boardSize) if winner: game.end_game(user.key) else: #If no winner, game ends in a draw if check_full(game.board): game.end_game() else: # Send email reminder to player if game still in progress taskqueue.add(url='/tasks/send_move_email', params={ 'user_key': game.nextMove.urlsafe(), 'game_key': game.key.urlsafe() }) game.put() # Upde the Memcache if the game is over if game.game_over: taskqueue.add(url='/task/cache_games_finished') return game.to_form()
def make_move(self, request): """Makes a move. Returns a game state with message""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if not game: raise endpoints.NotFoundException('Game not found') if game.game_over: raise endpoints.NotFoundException('Game already over') user = User.get_user_by_name(request.user_name) if user.key != game.next_move: raise endpoints.BadRequestException('It\'s not your turn!') # Just a dummy signifier, what type of symbol is going down x = True if user.key == game.user_x else False move = request.move # Verify move is valid size = game.board_size * game.board_size - 1 if move < 0 or move > size: raise endpoints.BadRequestException('Invalid move! Must be between' '0 and %s ' % size) if game.board[move] != '': raise endpoints.BadRequestException('Invalid move!') game.board[move] = 'X' if x else 'O' # Append a move to the history game.history.append(('X' if x else 'O', move)) game.next_move = game.user_o if x else game.user_x # Check if there's a winner winner = check_winner(game.board, game.board_size) # If there's winner end game if winner: game.end_game(user.key) else: # If there's no winner and game board is full end game with tie if check_full(game.board): # Game tied game.end_game() else: # If game is still ongoing, send remainder email to player taskqueue.add(url='/tasks/send_move_email', params={'user_key': game.next_move.urlsafe(), 'game_key': game.key.urlsafe()}) game.put() # If game is over, update memcache if game.game_over: taskqueue.add(url='/tasks/update_finished_games') return game.to_form()
def make_move(self, request): """Makes a move. Returns a game state with message""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if not game: raise endpoints.NotFoundException('Game not found') if game.game_over: return game.to_form('Game already over!') # prevent a user from playing twice in a row user = User.get_current_user(request.user_name) if user.key != game.nextMove: raise endpoints.BadRequestException('It\'s not your turn!') x = True if user.key == game.player_x else False # Make a move, and verify if the move is a valid move move = request.move size = game.boardSize * game.boardSize - 1 if move < 0 or move > size: raise endpoints.BadRequestException('Bad Move!') if game.board[move] != '': raise endpoints.BadRequestException('Invalid Move') # Make a move, and send the move to game history game.board[move] = 'X' if x else 'O' game.game_history.append(('X' if x else 'O', move)) game.nextMove = game.player_o if x else game.player_x #Check if there is a winner in the game and end the game winner = check_winner(game.board, game.boardSize) if winner: game.end_game(user.key) else: #If no winner, game ends in a draw if check_full(game.board): game.end_game() else: # Send email reminder to player if game still in progress taskqueue.add(url='/tasks/send_move_email', params={'user_key': game.nextMove.urlsafe(), 'game_key': game.key.urlsafe()}) game.put() # Upde the Memcache if the game is over if game.game_over: taskqueue.add(url='/task/cache_games_finished') return game.to_form()
def decrypt(text, key): ''' Function -- decrypt decrypts cipher text by replacing letters in the text with letters in the alphabet based on key index paramters: text -- cipher text string key -- plain text string of len 26 returns decrypted plain text version of the cipher text ''' # check validity of the inputs if key == '' or text == '': raise ValueError('both text and key values must be given') if not isinstance(key, str): raise TypeError('key must be a string') if not isinstance(text, str): raise TypeError('text must be a string') try: text = utils.strip(text) text = utils.process_text(text) text = utils.latin_caps(text) key = utils.strip(key) key = utils.process_text(key) key = utils.latin_caps(key) except ValueError: raise ValueError('text and key must only contain valid letters') if not utils.check_full(key): raise ValueError('key must contain only each letter of alphabet once') # alphabet and cipher alphabet_str = string.ascii_uppercase alphabet = list(alphabet_str) plain = '' # iterate through text and replace letter by key index for letter in text: if letter in alphabet: plain = plain + alphabet[key.index(letter)] else: raise ValueError('text and key must only contain valid letters') return plain
def make_move(self, request): """Makes a move. Returns a game state with message""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if not game: raise endpoints.NotFoundException("Game not found") if game.game_over: raise endpoints.NotFoundException("Game already over") user = User.query(User.name == request.user_name).get() if user.key != game.next_move: raise endpoints.BadRequestException("It's not your turn!") # Just a dummy signifier, what type of symbol is going down x = True if user.key == game.user_x else False move = request.move # Verify move is valid if move < 0 or move > 8: raise endpoints.BadRequestException("Invalid move! Must be between" "0 and 8") if game.board[move] != "": raise endpoints.BadRequestException("Invalid move!") game.board[move] = "X" if x else "O" # Append a move to the history game.history.append(("X" if x else "O", move)) game.next_move = game.user_o if x else game.user_x winner = check_winner(game.board) if not winner and check_full(game.board): # Just delete the game game.key.delete() raise endpoints.NotFoundException("Tie game, game deleted!") if winner: game.end_game(user.key) else: # Send reminder email taskqueue.add( url="/tasks/send_move_email", params={"user_key": game.next_move.urlsafe(), "game_key": game.key.urlsafe()}, ) game.put() return game.to_form()
def make_move(self, request): """Makes a move. Returns a game state with message""" game = get_by_urlsafe(request.urlsafe_game_key, Game) if not game: raise endpoints.NotFoundException('Game not found!') if game.game_over: raise endpoints.NotFoundException('Game is already over!') user = User.query(User.name == request.user_name).get() if user.key != game.next_move: raise endpoints.BadRequestException('It\'s not your turn!') move = request.move if not IsValidMove(move, game.board): raise endpoints.BadRequestException('Invalid move!') # Game history is a list of which player put pieces into which column. # Since the list is chronological, a game can be recreated using only # this information. if user.key == game.player_1: piece = '1' game.next_move = game.player_2 game.history.append('%s placed piece in column %s' % (str(user.name), move)) else: piece = '2' game.next_move = game.player_1 game.history.append('%s placed piece in column %s' % (str(user.name), move)) makeMove(piece, move, game.board) winner = check_winner(game.board) if not winner and check_full(game.board): game.tie_game() game.history.append('game ended in a tie') if winner: game.end_game(user.key) game.history.append('%s wins the game!' % str(user.name)) game.put() return game.to_form('board updated!')
def decrypt(text, alpha_key, num_key, add_key): ''' Function -- decrypt decrypts cipher text by reversing the cipher algorithm starting with adder text that is converted to numeric text and finally plain text using a key grid. paramters: text -- cipher text string of int literals alpha_key -- full alphabet in any order (str) num_key -- 2 digit integer (string or int) add_key -- int of any length returns decrypted plain text version of the cipher text ''' # check validity of the inputs if add_key == '' or num_key == '' or alpha_key == '' or text == '': raise ValueError('both text and key values must be given') if not isinstance(text, str): raise TypeError('text must be a string') if not isinstance(alpha_key, str): raise TypeError('all keys must be strings') ''' if not isinstance(num_key, str): raise TypeError('all keys must be strings') if not isinstance(add_key, str): raise TypeError('all keys must be strings') ''' num_key = str(num_key) if (len(str(num_key)) != 2 or not num_key[0].isnumeric() or not num_key[1].isnumeric()): raise ValueError('num_key must be have 2 unique integer digits') if int(str(num_key)[0]) == 0 or int(str(num_key)[1]) == 0: raise ValueError('digits of num_key must be greater than 0') if not utils.check_full(alpha_key): msg = ('alpha_key must contain only each letter of alphabet once') raise ValueError(msg) alpha_key = alpha_key.upper() try: int(num_key) num_key = str(num_key) add_key = int(add_key) if int(num_key) < 0 or int(add_key) < 0: print('Warning: negative keys will be assumed to be positive') except ValueError: raise ValueError('num_key and add_key must be ints') try: text = utils.strip(text) text = text.upper() for x in text: if (ord(x) >= 65 and ord(x) <= 90) or x == '1' or x == '0': pass else: raise ValueError('text must only contain valid letters') except ValueError: raise ValueError('text must only contain valid letters') # construct cipher square key_square = {} # first row key_square[0] = [alpha_key[i] for i in range(8)] if int(num_key[0]) > int(num_key[1]): key_square[0].insert(int(num_key[1]), '') key_square[0].insert(int(num_key[0]), '') else: key_square[0].insert(int(num_key[0]), '') key_square[0].insert(int(num_key[1]), '') # next rows key_square[int(num_key[0])] = [alpha_key[i] for i in range(8, 18)] key_square[int(num_key[1])] = [alpha_key[i] for i in range(18, 26)] key_square[int(num_key[1])].append('0') key_square[int(num_key[1])].append('1') # generate adder text adder = '' for letter in text: if letter in key_square[0]: adder = adder + str(key_square[0].index(letter)) elif letter in key_square[int(num_key[0])]: combo = num_key[0] + str(key_square[int(num_key[0])].index(letter)) adder = adder + combo elif letter in key_square[int(num_key[1])]: combo = num_key[1] + str(key_square[int(num_key[1])].index(letter)) adder = adder + combo else: raise ValueError('letters in plain text must be latin') # generate numeric text num_text = '' for i in range(len(adder)): subbed = int(adder[i]) - int(str(add_key)[i % len(str(add_key))]) if subbed < 0: new_sub = list(range(10))[subbed] num_text = num_text + str(new_sub) else: num_text = num_text + str(subbed)[-1] # generate original plain text plain = '' count = 0 while count < len(num_text): num = int(num_text[count]) if key_square[0][num] == '': if (count + 1) >= len(num_text): count += 2 else: next_num = int(num_text[count + 1]) cross = key_square[num][next_num] plain = plain + cross count += 2 else: plain += key_square[0][num] count += 1 return plain
def encrypt(text, alpha_key, num_key, add_key): ''' Function -- encrypt encrypts plain text by filling a 3x10 key using the first two keys. Letters in the plain text are then assigned numbers via the key square. The digits of this set of numbers is added sequentially to the add_key to yield the final cipher number. paramters: text -- plain text string alpha_key -- full alphabet in any order (str) num_key -- 2 digit integer (string or int) add_key -- int of any length returns encrypted cipher text version of the plain text (int) ''' # check validity of the inputs if add_key == '' or num_key == '' or alpha_key == '' or text == '': raise ValueError('both text and key values must be given') if not isinstance(text, str): raise TypeError('text must be a string') if not isinstance(alpha_key, str): raise TypeError('all keys must be strings') ''' if not isinstance(num_key, str): raise TypeError('all keys must be strings') if not isinstance(add_key, str): raise TypeError('all keys must be strings') ''' num_key = str(num_key) if (len(num_key) != 2 or not num_key[0].isnumeric() or not num_key[1].isnumeric() or num_key[0] == num_key[1]): raise ValueError('num_key must be have 2 unique integer digits') if int(num_key[0]) == 0 or int(num_key[1]) == 0: raise ValueError('digits of num_key must be greater than 0') if not utils.check_full(alpha_key): msg = ('alpha_key must contain only each letter of alphabet once') raise ValueError(msg) alpha_key = alpha_key.upper() try: int(num_key) num_key = str(num_key) add_key = int(add_key) if int(num_key) < 0 or int(add_key) < 0: print('Warning: negative keys will be assumed to be positive') except ValueError: raise ValueError('num_key and add_key must be ints') try: text = utils.strip(text) text = utils.process_text(text) text = utils.latin_caps(text) except ValueError: raise ValueError('text must only contain valid letters') # construct cipher square key_square = {} # first row key_square[0] = [alpha_key[i] for i in range(8)] if int(num_key[0]) > int(num_key[1]): key_square[0].insert(int(num_key[1]), '') key_square[0].insert(int(num_key[0]), '') else: key_square[0].insert(int(num_key[0]), '') key_square[0].insert(int(num_key[1]), '') # next rows key_square[int(num_key[0])] = [alpha_key[i] for i in range(8, 18)] key_square[int(num_key[1])] = [alpha_key[i] for i in range(18, 26)] key_square[int(num_key[1])].append('0') key_square[int(num_key[1])].append('1') # generate numeric text num_text = '' for letter in text: if letter in key_square[0]: num_text = num_text + str(key_square[0].index(letter)) elif letter in key_square[int(num_key[0])]: combo = num_key[0] + str(key_square[int(num_key[0])].index(letter)) num_text = num_text + combo elif letter in key_square[int(num_key[1])]: combo = num_key[1] + str(key_square[int(num_key[1])].index(letter)) num_text = num_text + combo else: raise ValueError('letters in plain text must be latin') # add the adder text adder = '' for i in range(len(num_text)): added = int(num_text[i]) + int(str(add_key)[i % len(str(add_key))]) adder = adder + str(added)[-1] # make cipher text via the grid cipher = '' count = 0 while count < len(adder): num = int(adder[count]) if key_square[0][num] == '': if (count + 1) >= len(adder): count += 2 else: next_num = int(adder[count + 1]) cross = key_square[num][next_num] cipher = cipher + cross count += 2 else: cipher += key_square[0][num] count += 1 return cipher
def main(): ciphers = 'caesar (c), railfence (r), playfair (p)\ substitution (su), beale (b), straddle (st)' while True: cmd = input('encrypt, decrypt, or exit (en, de, ex)? ') # ENCRYPT while cmd == 'en': enc = input('select cipher: \n \ caesar (c), railfence (r), playfair (p) \n \ substitution (su), beale (b), straddle (st): \n') # caesar if enc == 'c': t = input('enter plain text: ') if t != '' and utils.check_latin(t): pass else: print('text can only consist of latin letters') break k = input('enter integer key: ') if utils.check_int(k): print(caesar.encrypt(t, int(k))) cmd = '' else: cmd = '' # railfence elif enc == 'r': t = input('enter plain text: ') k = input('enter integer key: ') if utils.check_int(k): if int(k) > 1: print(railfence.encrypt(t, int(k))) cmd = '' else: print('key must be at least 2') cmd = '' else: cmd = '' # playfair elif enc == 'p': t = input('enter plain text: ') if t != '' and utils.check_latin(t): pass else: print('text can only consist of latin letters') break k = input('enter string key: ') if k != '' and utils.check_latin(k): print(playfair.encrypt(t, k)) pass else: print('key can only consist of latin letters') break cmd = '' # substitution elif enc == 'su': t = input('enter plain text: ') if t != '' and utils.check_latin(t): pass else: print('text can only consist of latin letters') break k = input('enter string key: ') if k != '' and utils.check_latin(k): try: utils.check_full(k) except ValueError: print('key should bee full alphabet') break try: print(substitution.encrypt(t, k)) except ValueError: print('check errors for parameter issues') pass else: print('key can only consist of latin letters') break cmd = '' # beale elif enc == 'b': t = input('enter plain text: ') if t != '' and utils.check_latin(t): pass else: print('text can have letters + punctuation') break k = input('enter file name key: ') if k != '': pass s = input('enter an integer seed: ') if s != '': try: s = int(s) except ValueError: print('seed must be integer') break try: print(beale.encrypt(t, k, s)) except ValueError: print('make sure your file is correct') pass else: print('text cannot be empty') break cmd = '' # straddle elif enc == 'st': t = input('enter plain text: ') warn = 0 for x in t: if (t not in string.ascii_letters and t != '0' and t != '1' and t != ' '): warn += 1 if warn > 0: print('warning: text should include only letters, 0, or 1') if t != '': pass else: print('text cannot be empty') break alk = input('enter alpha key: ') if alk != '': pass else: print('alpha_key cannot be empty') break try: utils.check_full(alk) except ValueError: print('alpha_key must be full alphabet') break nk = input('enter 2 digit numeric key: ') if nk != '': pass if (len(nk) != 2 or not nk[0].isnumeric() or not nk[1].isnumeric() or '0' in nk): print('num_key must be a 2 digit int with unique digits') print('cannot contain 0') break adk = input('enter adding key:') if adk != '': try: print(straddle.encrypt(t, alk, nk, adk)) except ValueError: print('make sure your add key is an integer') pass else: print('input cannot be empty') break cmd = '' else: print('Please enter a valid input for a cipher.') # DECRYPT while cmd == 'de': dec = input('select cipher: \n \ caesar (c), railfence (r), playfair (p) \n \ substitution (su), beale (b), straddle (st): \n') # caesar if dec == 'c': t = input('enter cipher text: ') if t != '' and utils.check_latin(t): pass else: print('text can only consist of latin letters') break k = input('enter integer key: ') if utils.check_int(k): print(caesar.decrypt(t, int(k))) cmd = '' else: cmd = '' # railfence elif dec == 'r': t = input('enter cipher text: ') k = input('enter integer key: ') if utils.check_int(k): if int(k) > 1: print(railfence.decrypt(t, int(k))) cmd = '' else: print('key must be at least 2') cmd = '' else: cmd = '' # playfair elif dec == 'p': t = input('enter cipher text: ') if t != '' and utils.check_latin(t): pass else: print('text can only consist of latin letters') break k = input('enter string key: ') if k != '' and utils.check_latin(k): print(playfair.decrypt(t, k)) pass else: print('text can only consist of latin letters') break cmd = '' # substitution elif dec == 'su': t = input('enter cipher text: ') if t != '' and utils.check_latin(t): pass else: print('text can only consist of latin letters') break k = input('enter string key: ') if k != '' and utils.check_latin(k): try: utils.check_full(k) except ValueError: print('key should be full alphabet') break try: print(substitution.decrypt(t, k)) except ValueError: print('check errors for parameter issues') pass else: print('key can only consist of latin letters') break cmd = '' # beale elif dec == 'b': t = input('enter cipher text: ') for x in t: if x != ' ': if not x.isnumeric(): print('text should consist of int literals') break if t != '': pass else: print('warning: text should only consist of integers') break k = input('enter file name key: ') if k != '': try: print(beale.decrypt(t, k)) except ValueError: print('check that your text file is correct') pass else: print('text cannot be empty') break cmd = '' # straddle elif dec == 'st': t = input('enter cipher text: ') warn = 0 for x in t: if (t not in string.ascii_letters and t != '0' and t != '1' and t != ' '): warn += 1 if warn > 0: print('warning: text should include only letters, 0, or 1') if t != '': pass else: print('text cannot be empty') break alk = input('enter alpha key: ') if alk != '': pass else: print('alpha_key cannot be empty') break try: utils.check_full(alk) except ValueError: print('alpha_key must be full alphabet') break nk = input('enter 2 digit numeric key: ') if nk != '': pass if (len(nk) != 2 or not nk[0].isnumeric() or not nk[1].isnumeric() or '0' in nk): print('num_key must be a 2 digit int with unique digits') print('cannot contain 0') break adk = input('enter adding key:') if adk != '': try: print(straddle.decrypt(t, alk, nk, adk)) except ValueError: print('make sure your add key is an integer') pass else: print('text cannot be empty') break cmd = '' else: print('Please enter a valid input for a cipher.') if cmd == 'ex': print('exit') return False elif cmd == '' or cmd == 'en' or cmd == 'de': pass else: print('Please enter a valid input of en, de, or ex.')
def make_move(self, request): """Makes a move. Returns a game state with message""" game = get_by_urlsafe(request.urlsafe_game_key, Game) player = Player.get_player_by_name(request.player_name) if not game: raise endpoints.NotFoundException('Game not found!') if game.status == 1: raise endpoints.NotFoundException('Game not in session!') if game.check_player(player): if game.check_player_turn(player): if 1 <= move <= 9: if move in game.setup: move = request.move game.history.append([player_name, move]) if game.is_host(player): game.host_moves.append(move) if check_winner(game.host_moves): game.end_game(player) taskqueue.add(url='/tasks/send_congrats_email', params={ 'user_key': game.host.urlsafe(), 'game_key': game.key.urlsafe() }) else: game.next_turn = game.oppoent if game.is_oppoent(player): game.oppoent_moves.append(move) if check_winner(game.oppoent_moves): game.end_game(player) taskqueue.add(url='/tasks/send_congrats_email', params={ 'user_key': game.oppoent.urlsafe(), 'game_key': game.key.urlsafe() }) else: game.next_turn = game.host else: msg = 'Your oppoent has taken this spot. Please try again' else: msg = 'Invalid move! Please choose a number (1-9).' else: raise endpoints.ConflictException( 'Please wait until your turn to make a move!') else: raise endpoints.NotFoundException( 'Player not current game session!') position = game.setup.index(move) del game.setup[position] game.put() if check_full(game.setup): game.end_game() msg = 'It\'s a tie! Thank you for playing!' taskqueue.add(url='/tasks/send_finish_email', params={ 'user_key': game.next_turn.urlsafe(), 'game_key': game.key.urlsafe() }) taskqueue.add(url='/tasks/send_finish_email', params={ 'user_key': player.urlsafe(), 'game_key': game.key.urlsafe() }) else: # If game is still ongoing, send remainder email to player taskqueue.add(url='/tasks/send_congrats_email', params={ 'user_key': game.next_turn.urlsafe(), 'game_key': game.key.urlsafe() }) return game.to_form(msg)