Commits

Allan Davis committed 8dd3235 Merge

merged in updates

  • Participants
  • Parent commits 3149dcf, 9b53c47

Comments (0)

Files changed (27)

File code/AISim1.py

+# Reversi
+
+import random
+import sys
+
+def drawBoard(board):
+    # This function prints out the board that it was passed. Returns None.
+    HLINE = '  +---+---+---+---+---+---+---+---+'
+    VLINE = '  |   |   |   |   |   |   |   |   |'
+
+    print('    1   2   3   4   5   6   7   8')
+    print(HLINE)
+    for y in range(8):
+        print(VLINE)
+        print(y+1, end=' ')
+        for x in range(8):
+            print('| %s' % (board[x][y]), end=' ')
+        print('|')
+        print(VLINE)
+        print(HLINE)
+
+
+def resetBoard(board):
+    # Blanks out the board it is passed, except for the original starting position.
+    for x in range(8):
+        for y in range(8):
+            board[x][y] = ' '
+
+    # Starting pieces:
+    board[3][3] = 'X'
+    board[3][4] = 'O'
+    board[4][3] = 'O'
+    board[4][4] = 'X'
+
+
+def getNewBoard():
+    # Creates a brand new, blank board data structure.
+    board = []
+    for i in range(8):
+        board.append([' '] * 8)
+
+    return board
+
+
+def isValidMove(board, tile, xstart, ystart):
+    # Returns False if the player's move on space xstart, ystart is invalid.
+    # If it is a valid move, returns a list of spaces that would become the player's if they made a move here.
+    if board[xstart][ystart] != ' ' or not isOnBoard(xstart, ystart):
+        return False
+
+    board[xstart][ystart] = tile # temporarily set the tile on the board.
+
+    if tile == 'X':
+        otherTile = 'O'
+    else:
+        otherTile = 'X'
+
+    tilesToFlip = []
+    for xdirection, ydirection in [[0, 1], [1, 1], [1, 0], [1, -1], [0, -1], [-1, -1], [-1, 0], [-1, 1]]:
+        x, y = xstart, ystart
+        x += xdirection # first step in the direction
+        y += ydirection # first step in the direction
+        if isOnBoard(x, y) and board[x][y] == otherTile:
+            # There is a piece belonging to the other player next to our piece.
+            x += xdirection
+            y += ydirection
+            if not isOnBoard(x, y):
+                continue
+            while board[x][y] == otherTile:
+                x += xdirection
+                y += ydirection
+                if not isOnBoard(x, y): # break out of while loop, then continue in for loop
+                    break
+            if not isOnBoard(x, y):
+                continue
+            if board[x][y] == tile:
+                # There are pieces to flip over. Go in the reverse direction until we reach the original space, noting all the tiles along the way.
+                while True:
+                    x -= xdirection
+                    y -= ydirection
+                    if x == xstart and y == ystart:
+                        break
+                    tilesToFlip.append([x, y])
+
+    board[xstart][ystart] = ' ' # restore the empty space
+    if len(tilesToFlip) == 0: # If no tiles were flipped, this is not a valid move.
+        return False
+    return tilesToFlip
+
+
+def isOnBoard(x, y):
+    # Returns True if the coordinates are located on the board.
+    return x >= 0 and x <= 7 and y >= 0 and y <=7
+
+
+def getBoardWithValidMoves(board, tile):
+    # Returns a new board with . marking the valid moves the given player can make.
+    dupeBoard = getBoardCopy(board)
+
+    for x, y in getValidMoves(dupeBoard, tile):
+        dupeBoard[x][y] = '.'
+    return dupeBoard
+
+
+def getValidMoves(board, tile):
+    # Returns a list of [x,y] lists of valid moves for the given player on the given board.
+    validMoves = []
+
+    for x in range(8):
+        for y in range(8):
+            if isValidMove(board, tile, x, y) != False:
+                validMoves.append([x, y])
+    return validMoves
+
+
+def getScoreOfBoard(board):
+    # Determine the score by counting the tiles. Returns a dictionary with keys 'X' and 'O'.
+    xscore = 0
+    oscore = 0
+    for x in range(8):
+        for y in range(8):
+            if board[x][y] == 'X':
+                xscore += 1
+            if board[x][y] == 'O':
+                oscore += 1
+    return {'X':xscore, 'O':oscore}
+
+
+def enterPlayerTile():
+    # Let's the player type which tile they want to be.
+    # Returns a list with the player's tile as the first item, and the computer's tile as the second.
+    tile = ''
+    while not (tile == 'X' or tile == 'O'):
+        print('Do you want to be X or O?')
+        tile = input().upper()
+
+    # the first element in the tuple is the player's tile, the second is the computer's tile.
+    if tile == 'X':
+        return ['X', 'O']
+    else:
+        return ['O', 'X']
+
+
+def whoGoesFirst():
+    # Randomly choose the player who goes first.
+    if random.randint(0, 1) == 0:
+        return 'computer'
+    else:
+        return 'player'
+
+
+def playAgain():
+    # This function returns True if the player wants to play again, otherwise it returns False.
+    print('Do you want to play again? (yes or no)')
+    return input().lower().startswith('y')
+
+
+def makeMove(board, tile, xstart, ystart):
+    # Place the tile on the board at xstart, ystart, and flip any of the opponent's pieces.
+    # Returns False if this is an invalid move, True if it is valid.
+    tilesToFlip = isValidMove(board, tile, xstart, ystart)
+
+    if tilesToFlip == False:
+        return False
+
+    board[xstart][ystart] = tile
+    for x, y in tilesToFlip:
+        board[x][y] = tile
+    return True
+
+
+def getBoardCopy(board):
+    # Make a duplicate of the board list and return the duplicate.
+    dupeBoard = getNewBoard()
+
+    for x in range(8):
+        for y in range(8):
+            dupeBoard[x][y] = board[x][y]
+
+    return dupeBoard
+
+
+def isOnCorner(x, y):
+    # Returns True if the position is in one of the four corners.
+    return (x == 0 and y == 0) or (x == 7 and y == 0) or (x == 0 and y == 7) or (x == 7 and y == 7)
+
+
+def getPlayerMove(board, playerTile):
+    # Let the player type in their move.
+    # Returns the move as [x, y] (or returns the strings 'hints' or 'quit')
+    DIGITS1TO8 = '1 2 3 4 5 6 7 8'.split()
+    while True:
+        print('Enter your move, or type quit to end the game, or hints to turn off/on hints.')
+        move = input().lower()
+        if move == 'quit':
+            return 'quit'
+        if move == 'hints':
+            return 'hints'
+
+        if len(move) == 2 and move[0] in DIGITS1TO8 and move[1] in DIGITS1TO8:
+            x = int(move[0]) - 1
+            y = int(move[1]) - 1
+            if isValidMove(board, playerTile, x, y) == False:
+                continue
+            else:
+                break
+        else:
+            print('That is not a valid move. Type the x digit (1-8), then the y digit (1-8).')
+            print('For example, 81 will be the top-right corner.')
+
+    return [x, y]
+
+
+def getComputerMove(board, computerTile):
+    # Given a board and the computer's tile, determine where to
+    # move and return that move as a [x, y] list.
+    possibleMoves = getValidMoves(board, computerTile)
+
+    # randomize the order of the possible moves
+    random.shuffle(possibleMoves)
+
+    # always go for a corner if available.
+    for x, y in possibleMoves:
+        if isOnCorner(x, y):
+            return [x, y]
+
+    # Go through all the possible moves and remember the best scoring move
+    bestScore = -1
+    for x, y in possibleMoves:
+        dupeBoard = getBoardCopy(board)
+        makeMove(dupeBoard, computerTile, x, y)
+        score = getScoreOfBoard(dupeBoard)[computerTile]
+        if score > bestScore:
+            bestMove = [x, y]
+            bestScore = score
+    return bestMove
+
+
+def showPoints(playerTile, computerTile):
+    # Prints out the current score.
+    scores = getScoreOfBoard(mainBoard)
+    print('You have %s points. The computer has %s points.' % (scores[playerTile], scores[computerTile]))
+
+
+
+print('Welcome to Reversi!')
+
+while True:
+    # Reset the board and game.
+    mainBoard = getNewBoard()
+    resetBoard(mainBoard)
+    if whoGoesFirst() == 'player':
+        turn = 'X'
+    else:
+         turn = 'O'
+    print('The ' + turn + ' will go first.')
+
+    while True:
+         drawBoard(mainBoard)
+         scores = getScoreOfBoard(mainBoard)
+         print('X has %s points. O has %s points' % (scores['X'], scores['O']))
+         input('Press Enter to continue.')
+
+         if turn == 'X':
+              # X's turn.
+              otherTile = 'O'
+              x, y = getComputerMove(mainBoard, 'X')
+              makeMove(mainBoard, 'X', x, y)
+         else:
+              # O's turn.
+              otherTile = 'X'
+              x, y = getComputerMove(mainBoard, 'O')
+              makeMove(mainBoard, 'O', x, y)
+
+         if getValidMoves(mainBoard, otherTile) == []:
+              break
+         else:
+              turn = otherTile
+
+    # Display the final score.
+    drawBoard(mainBoard)
+    scores = getScoreOfBoard(mainBoard)
+    print('X scored %s points. O scored %s points.' % (scores['X'], scores['O']))
+
+    if not playAgain():
+         sys.exit()

File code/AISim2.py

+# Reversi
+
+import random
+import sys
+
+def drawBoard(board):
+    # This function prints out the board that it was passed. Returns None.
+    HLINE = '  +---+---+---+---+---+---+---+---+'
+    VLINE = '  |   |   |   |   |   |   |   |   |'
+
+    print('    1   2   3   4   5   6   7   8')
+    print(HLINE)
+    for y in range(8):
+        print(VLINE)
+        print(y+1, end=' ')
+        for x in range(8):
+            print('| %s' % (board[x][y]), end=' ')
+        print('|')
+        print(VLINE)
+        print(HLINE)
+
+
+def resetBoard(board):
+    # Blanks out the board it is passed, except for the original starting position.
+    for x in range(8):
+        for y in range(8):
+            board[x][y] = ' '
+
+    # Starting pieces:
+    board[3][3] = 'X'
+    board[3][4] = 'O'
+    board[4][3] = 'O'
+    board[4][4] = 'X'
+
+
+def getNewBoard():
+    # Creates a brand new, blank board data structure.
+    board = []
+    for i in range(8):
+        board.append([' '] * 8)
+
+    return board
+
+
+def isValidMove(board, tile, xstart, ystart):
+    # Returns False if the player's move on space xstart, ystart is invalid.
+    # If it is a valid move, returns a list of spaces that would become the player's if they made a move here.
+    if board[xstart][ystart] != ' ' or not isOnBoard(xstart, ystart):
+        return False
+
+    board[xstart][ystart] = tile # temporarily set the tile on the board.
+
+    if tile == 'X':
+        otherTile = 'O'
+    else:
+        otherTile = 'X'
+
+    tilesToFlip = []
+    for xdirection, ydirection in [[0, 1], [1, 1], [1, 0], [1, -1], [0, -1], [-1, -1], [-1, 0], [-1, 1]]:
+        x, y = xstart, ystart
+        x += xdirection # first step in the direction
+        y += ydirection # first step in the direction
+        if isOnBoard(x, y) and board[x][y] == otherTile:
+            # There is a piece belonging to the other player next to our piece.
+            x += xdirection
+            y += ydirection
+            if not isOnBoard(x, y):
+                continue
+            while board[x][y] == otherTile:
+                x += xdirection
+                y += ydirection
+                if not isOnBoard(x, y): # break out of while loop, then continue in for loop
+                    break
+            if not isOnBoard(x, y):
+                continue
+            if board[x][y] == tile:
+                # There are pieces to flip over. Go in the reverse direction until we reach the original space, noting all the tiles along the way.
+                while True:
+                    x -= xdirection
+                    y -= ydirection
+                    if x == xstart and y == ystart:
+                        break
+                    tilesToFlip.append([x, y])
+
+    board[xstart][ystart] = ' ' # restore the empty space
+    if len(tilesToFlip) == 0: # If no tiles were flipped, this is not a valid move.
+        return False
+    return tilesToFlip
+
+
+def isOnBoard(x, y):
+    # Returns True if the coordinates are located on the board.
+    return x >= 0 and x <= 7 and y >= 0 and y <=7
+
+
+def getBoardWithValidMoves(board, tile):
+    # Returns a new board with . marking the valid moves the given player can make.
+    dupeBoard = getBoardCopy(board)
+
+    for x, y in getValidMoves(dupeBoard, tile):
+        dupeBoard[x][y] = '.'
+    return dupeBoard
+
+
+def getValidMoves(board, tile):
+    # Returns a list of [x,y] lists of valid moves for the given player on the given board.
+    validMoves = []
+
+    for x in range(8):
+        for y in range(8):
+            if isValidMove(board, tile, x, y) != False:
+                validMoves.append([x, y])
+    return validMoves
+
+
+def getScoreOfBoard(board):
+    # Determine the score by counting the tiles. Returns a dictionary with keys 'X' and 'O'.
+    xscore = 0
+    oscore = 0
+    for x in range(8):
+        for y in range(8):
+            if board[x][y] == 'X':
+                xscore += 1
+            if board[x][y] == 'O':
+                oscore += 1
+    return {'X':xscore, 'O':oscore}
+
+
+def enterPlayerTile():
+    # Let's the player type which tile they want to be.
+    # Returns a list with the player's tile as the first item, and the computer's tile as the second.
+    tile = ''
+    while not (tile == 'X' or tile == 'O'):
+        print('Do you want to be X or O?')
+        tile = input().upper()
+
+    # the first element in the tuple is the player's tile, the second is the computer's tile.
+    if tile == 'X':
+        return ['X', 'O']
+    else:
+        return ['O', 'X']
+
+
+def whoGoesFirst():
+    # Randomly choose the player who goes first.
+    if random.randint(0, 1) == 0:
+        return 'computer'
+    else:
+        return 'player'
+
+
+def playAgain():
+    # This function returns True if the player wants to play again, otherwise it returns False.
+    print('Do you want to play again? (yes or no)')
+    return input().lower().startswith('y')
+
+
+def makeMove(board, tile, xstart, ystart):
+    # Place the tile on the board at xstart, ystart, and flip any of the opponent's pieces.
+    # Returns False if this is an invalid move, True if it is valid.
+    tilesToFlip = isValidMove(board, tile, xstart, ystart)
+
+    if tilesToFlip == False:
+        return False
+
+    board[xstart][ystart] = tile
+    for x, y in tilesToFlip:
+        board[x][y] = tile
+    return True
+
+
+def getBoardCopy(board):
+    # Make a duplicate of the board list and return the duplicate.
+    dupeBoard = getNewBoard()
+
+    for x in range(8):
+        for y in range(8):
+            dupeBoard[x][y] = board[x][y]
+
+    return dupeBoard
+
+
+def isOnCorner(x, y):
+    # Returns True if the position is in one of the four corners.
+    return (x == 0 and y == 0) or (x == 7 and y == 0) or (x == 0 and y == 7) or (x == 7 and y == 7)
+
+
+def getPlayerMove(board, playerTile):
+    # Let the player type in their move.
+    # Returns the move as [x, y] (or returns the strings 'hints' or 'quit')
+    DIGITS1TO8 = '1 2 3 4 5 6 7 8'.split()
+    while True:
+        print('Enter your move, or type quit to end the game, or hints to turn off/on hints.')
+        move = input().lower()
+        if move == 'quit':
+            return 'quit'
+        if move == 'hints':
+            return 'hints'
+
+        if len(move) == 2 and move[0] in DIGITS1TO8 and move[1] in DIGITS1TO8:
+            x = int(move[0]) - 1
+            y = int(move[1]) - 1
+            if isValidMove(board, playerTile, x, y) == False:
+                continue
+            else:
+                break
+        else:
+            print('That is not a valid move. Type the x digit (1-8), then the y digit (1-8).')
+            print('For example, 81 will be the top-right corner.')
+
+    return [x, y]
+
+
+def getComputerMove(board, computerTile):
+    # Given a board and the computer's tile, determine where to
+    # move and return that move as a [x, y] list.
+    possibleMoves = getValidMoves(board, computerTile)
+
+    # randomize the order of the possible moves
+    random.shuffle(possibleMoves)
+
+    # always go for a corner if available.
+    for x, y in possibleMoves:
+        if isOnCorner(x, y):
+            return [x, y]
+
+    # Go through all the possible moves and remember the best scoring move
+    bestScore = -1
+    for x, y in possibleMoves:
+        dupeBoard = getBoardCopy(board)
+        makeMove(dupeBoard, computerTile, x, y)
+        score = getScoreOfBoard(dupeBoard)[computerTile]
+        if score > bestScore:
+            bestMove = [x, y]
+            bestScore = score
+    return bestMove
+
+
+def showPoints(playerTile, computerTile):
+    # Prints out the current score.
+    scores = getScoreOfBoard(mainBoard)
+    print('You have %s points. The computer has %s points.' % (scores[playerTile], scores[computerTile]))
+
+
+
+print('Welcome to Reversi!')
+
+xwins = 0
+owins = 0
+ties = 0
+numGames = int(input('Enter number of games to run: '))
+
+for game in range(numGames):
+    print('Game #%s:' % (game), end=' ')
+    # Reset the board and game.
+    mainBoard = getNewBoard()
+    resetBoard(mainBoard)
+    if whoGoesFirst() == 'player':
+        turn = 'X'
+    else:
+        turn = 'O'
+
+    while True:
+        if turn == 'X':
+            # X's turn.
+            otherTile = 'O'
+            x, y = getComputerMove(mainBoard, 'X')
+            makeMove(mainBoard, 'X', x, y)
+        else:
+            # O's turn.
+            otherTile = 'X'
+            x, y = getComputerMove(mainBoard, 'O')
+            makeMove(mainBoard, 'O', x, y)
+
+        if getValidMoves(mainBoard, otherTile) == []:
+            break
+        else:
+            turn = otherTile
+
+    # Display the final score.
+    scores = getScoreOfBoard(mainBoard)
+    print('X scored %s points. O scored %s points.' % (scores['X'], scores['O']))
+
+    if scores['X'] > scores['O']:
+        xwins += 1
+    elif scores['X'] < scores['O']:
+        owins += 1
+    else:
+        ties += 1
+
+numGames = float(numGames)
+xpercent = round(((xwins / numGames) * 100), 2)
+opercent = round(((owins / numGames) * 100), 2)
+tiepercent = round(((ties / numGames) * 100), 2)
+print('X wins %s games (%s%%), O wins %s games (%s%%), ties for %s games (%s%%) of %s games total.' % (xwins, xpercent, owins, opercent, ties, tiepercent, numGames))

File code/AISim3.py

+# Reversi
+
+import random
+import sys
+
+def drawBoard(board):
+    # This function prints out the board that it was passed. Returns None.
+    HLINE = '  +---+---+---+---+---+---+---+---+'
+    VLINE = '  |   |   |   |   |   |   |   |   |'
+
+    print('    1   2   3   4   5   6   7   8')
+    print(HLINE)
+    for y in range(8):
+        print(VLINE)
+        print(y+1, end=' ')
+        for x in range(8):
+            print('| %s' % (board[x][y]), end=' ')
+        print('|')
+        print(VLINE)
+        print(HLINE)
+
+
+def resetBoard(board):
+    # Blanks out the board it is passed, except for the original starting position.
+    for x in range(8):
+        for y in range(8):
+            board[x][y] = ' '
+
+    # Starting pieces:
+    board[3][3] = 'X'
+    board[3][4] = 'O'
+    board[4][3] = 'O'
+    board[4][4] = 'X'
+
+
+def getNewBoard():
+    # Creates a brand new, blank board data structure.
+    board = []
+    for i in range(8):
+        board.append([' '] * 8)
+
+    return board
+
+
+def isValidMove(board, tile, xstart, ystart):
+    # Returns False if the player's move on space xstart, ystart is invalid.
+    # If it is a valid move, returns a list of spaces that would become the player's if they made a move here.
+    if board[xstart][ystart] != ' ' or not isOnBoard(xstart, ystart):
+        return False
+
+    board[xstart][ystart] = tile # temporarily set the tile on the board.
+
+    if tile == 'X':
+        otherTile = 'O'
+    else:
+        otherTile = 'X'
+
+    tilesToFlip = []
+    for xdirection, ydirection in [[0, 1], [1, 1], [1, 0], [1, -1], [0, -1], [-1, -1], [-1, 0], [-1, 1]]:
+        x, y = xstart, ystart
+        x += xdirection # first step in the direction
+        y += ydirection # first step in the direction
+        if isOnBoard(x, y) and board[x][y] == otherTile:
+            # There is a piece belonging to the other player next to our piece.
+            x += xdirection
+            y += ydirection
+            if not isOnBoard(x, y):
+                continue
+            while board[x][y] == otherTile:
+                x += xdirection
+                y += ydirection
+                if not isOnBoard(x, y): # break out of while loop, then continue in for loop
+                    break
+            if not isOnBoard(x, y):
+                continue
+            if board[x][y] == tile:
+                # There are pieces to flip over. Go in the reverse direction until we reach the original space, noting all the tiles along the way.
+                while True:
+                    x -= xdirection
+                    y -= ydirection
+                    if x == xstart and y == ystart:
+                        break
+                    tilesToFlip.append([x, y])
+
+    board[xstart][ystart] = ' ' # restore the empty space
+    if len(tilesToFlip) == 0: # If no tiles were flipped, this is not a valid move.
+        return False
+    return tilesToFlip
+
+
+def isOnBoard(x, y):
+    # Returns True if the coordinates are located on the board.
+    return x >= 0 and x <= 7 and y >= 0 and y <=7
+
+
+def getBoardWithValidMoves(board, tile):
+    # Returns a new board with . marking the valid moves the given player can make.
+    dupeBoard = getBoardCopy(board)
+
+    for x, y in getValidMoves(dupeBoard, tile):
+        dupeBoard[x][y] = '.'
+    return dupeBoard
+
+
+def getValidMoves(board, tile):
+    # Returns a list of [x,y] lists of valid moves for the given player on the given board.
+    validMoves = []
+
+    for x in range(8):
+        for y in range(8):
+            if isValidMove(board, tile, x, y) != False:
+                validMoves.append([x, y])
+    return validMoves
+
+
+def getScoreOfBoard(board):
+    # Determine the score by counting the tiles. Returns a dictionary with keys 'X' and 'O'.
+    xscore = 0
+    oscore = 0
+    for x in range(8):
+        for y in range(8):
+            if board[x][y] == 'X':
+                xscore += 1
+            if board[x][y] == 'O':
+                oscore += 1
+    return {'X':xscore, 'O':oscore}
+
+
+def enterPlayerTile():
+    # Let's the player type which tile they want to be.
+    # Returns a list with the player's tile as the first item, and the computer's tile as the second.
+    tile = ''
+    while not (tile == 'X' or tile == 'O'):
+        print('Do you want to be X or O?')
+        tile = input().upper()
+
+    # the first element in the tuple is the player's tile, the second is the computer's tile.
+    if tile == 'X':
+        return ['X', 'O']
+    else:
+        return ['O', 'X']
+
+
+def whoGoesFirst():
+    # Randomly choose the player who goes first.
+    if random.randint(0, 1) == 0:
+        return 'computer'
+    else:
+        return 'player'
+
+
+def playAgain():
+    # This function returns True if the player wants to play again, otherwise it returns False.
+    print('Do you want to play again? (yes or no)')
+    return input().lower().startswith('y')
+
+
+def makeMove(board, tile, xstart, ystart):
+    # Place the tile on the board at xstart, ystart, and flip any of the opponent's pieces.
+    # Returns False if this is an invalid move, True if it is valid.
+    tilesToFlip = isValidMove(board, tile, xstart, ystart)
+
+    if tilesToFlip == False:
+        return False
+
+    board[xstart][ystart] = tile
+    for x, y in tilesToFlip:
+        board[x][y] = tile
+    return True
+
+
+def getBoardCopy(board):
+    # Make a duplicate of the board list and return the duplicate.
+    dupeBoard = getNewBoard()
+
+    for x in range(8):
+        for y in range(8):
+            dupeBoard[x][y] = board[x][y]
+
+    return dupeBoard
+
+
+def isOnCorner(x, y):
+    # Returns True if the position is in one of the four corners.
+    return (x == 0 and y == 0) or (x == 7 and y == 0) or (x == 0 and y == 7) or (x == 7 and y == 7)
+
+
+def getPlayerMove(board, playerTile):
+    # Let the player type in their move.
+    # Returns the move as [x, y] (or returns the strings 'hints' or 'quit')
+    DIGITS1TO8 = '1 2 3 4 5 6 7 8'.split()
+    while True:
+        print('Enter your move, or type quit to end the game, or hints to turn off/on hints.')
+        move = input().lower()
+        if move == 'quit':
+            return 'quit'
+        if move == 'hints':
+            return 'hints'
+
+        if len(move) == 2 and move[0] in DIGITS1TO8 and move[1] in DIGITS1TO8:
+            x = int(move[0]) - 1
+            y = int(move[1]) - 1
+            if isValidMove(board, playerTile, x, y) == False:
+                continue
+            else:
+                break
+        else:
+            print('That is not a valid move. Type the x digit (1-8), then the y digit (1-8).')
+            print('For example, 81 will be the top-right corner.')
+
+    return [x, y]
+
+
+def getComputerMove(board, computerTile):
+    # Given a board and the computer's tile, determine where to
+    # move and return that move as a [x, y] list.
+    possibleMoves = getValidMoves(board, computerTile)
+
+    # randomize the order of the possible moves
+    random.shuffle(possibleMoves)
+
+    # always go for a corner if available.
+    for x, y in possibleMoves:
+        if isOnCorner(x, y):
+            return [x, y]
+
+    # Go through all the possible moves and remember the best scoring move
+    bestScore = -1
+    for x, y in possibleMoves:
+        dupeBoard = getBoardCopy(board)
+        makeMove(dupeBoard, computerTile, x, y)
+        score = getScoreOfBoard(dupeBoard)[computerTile]
+        if score > bestScore:
+            bestMove = [x, y]
+            bestScore = score
+    return bestMove
+
+
+def showPoints(playerTile, computerTile):
+    # Prints out the current score.
+    scores = getScoreOfBoard(mainBoard)
+    print('You have %s points. The computer has %s points.' % (scores[playerTile], scores[computerTile]))
+
+
+def getRandomMove(board, tile):
+    # Return a random move.
+    return random.choice( getValidMoves(board, tile) )
+
+
+def isOnSide(x, y):
+    return x == 0 or x == 7 or y == 0 or y ==7
+
+
+def getCornerSideBestMove(board, tile):
+    # Return a corner move, or a side move, or the best move.
+    possibleMoves = getValidMoves(board, tile)
+
+    # randomize the order of the possible moves
+    random.shuffle(possibleMoves)
+
+    # always go for a corner if available.
+    for x, y in possibleMoves:
+        if isOnCorner(x, y):
+            return [x, y]
+
+    # if there is no corner, return a side move.
+    for x, y in possibleMoves:
+        if isOnSide(x, y):
+            return [x, y]
+
+    return getComputerMove(board, tile)
+
+
+def getSideBestMove(board, tile):
+    # Return a corner move, or a side move, or the best move.
+    possibleMoves = getValidMoves(board, tile)
+
+    # randomize the order of the possible moves
+    random.shuffle(possibleMoves)
+
+    # return a side move, if available
+    for x, y in possibleMoves:
+        if isOnSide(x, y):
+            return [x, y]
+
+    return getComputerMove(board, tile)
+
+
+def getWorstMove(board, tile):
+    # Return the move that flips the least number of tiles.
+    possibleMoves = getValidMoves(board, tile)
+
+    # randomize the order of the possible moves
+    random.shuffle(possibleMoves)
+
+    # Go through all the possible moves and remember the best scoring move
+    worstScore = 64
+    for x, y in possibleMoves:
+        dupeBoard = getBoardCopy(board)
+        makeMove(dupeBoard, tile, x, y)
+        score = getScoreOfBoard(dupeBoard)[tile]
+        if score < worstScore:
+            worstMove = [x, y]
+            worstScore = score
+
+    return worstMove
+
+
+def getCornerWorstMove(board, tile):
+    # Return a corner, a space, or the move that flips the least number of tiles.
+    possibleMoves = getValidMoves(board, tile)
+
+    # randomize the order of the possible moves
+    random.shuffle(possibleMoves)
+
+    # always go for a corner if available.
+    for x, y in possibleMoves:
+        if isOnCorner(x, y):
+            return [x, y]
+
+    return getWorstMove(board, tile)
+
+
+
+print('Welcome to Reversi!')
+
+
+xwins = 0
+owins = 0
+ties = 0
+numGames = int(input('Enter number of games to run: '))
+
+for game in range(numGames):
+    print('Game #%s:' % (game), end=' ')
+    # Reset the board and game.
+    mainBoard = getNewBoard()
+    resetBoard(mainBoard)
+    if whoGoesFirst() == 'player':
+        turn = 'X'
+    else:
+        turn = 'O'
+
+    while True:
+        if turn == 'X':
+            # X's turn.
+            otherTile = 'O'
+            x, y = getComputerMove(mainBoard, 'X')
+            makeMove(mainBoard, 'X', x, y)
+        else:
+            # O's turn.
+            otherTile = 'X'
+            x, y = getComputerMove(mainBoard, 'O')
+            makeMove(mainBoard, 'O', x, y)
+
+        if getValidMoves(mainBoard, otherTile) == []:
+            break
+        else:
+            turn = otherTile
+
+    # Display the final score.
+    scores = getScoreOfBoard(mainBoard)
+    print('X scored %s points. O scored %s points.' % (scores['X'], scores['O']))
+
+    if scores['X'] > scores['O']:
+        xwins += 1
+    elif scores['X'] < scores['O']:
+        owins += 1
+    else:
+        ties += 1
+
+numGames = float(numGames)
+xpercent = round(((xwins / numGames) * 100), 2)
+opercent = round(((owins / numGames) * 100), 2)
+tiepercent = round(((ties / numGames) * 100), 2)
+print('X wins %s games (%s%%), O wins %s games (%s%%), ties for %s games (%s%%) of %s games total.' % (xwins, xpercent, owins, opercent, ties, tiepercent, numGames))

File code/animation.py

+import pygame, sys, time
+from pygame.locals import *
+
+# set up pygame
+pygame.init()
+
+# set up the window
+WINDOWWIDTH = 400
+WINDOWHEIGHT = 400
+windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
+pygame.display.set_caption('Animation')
+
+# set up direction variables
+DOWNLEFT = 1
+DOWNRIGHT = 3
+UPLEFT = 7
+UPRIGHT = 9
+
+MOVESPEED = 4
+
+# set up the colors
+BLACK = (0, 0, 0)
+RED = (255, 0, 0)
+GREEN = (0, 255, 0)
+BLUE = (0, 0, 255)
+
+# set up the block data structure
+b1 = {'rect':pygame.Rect(300, 80, 50, 100), 'color':RED, 'dir':UPRIGHT}
+b2 = {'rect':pygame.Rect(200, 200, 20, 20), 'color':GREEN, 'dir':UPLEFT}
+b3 = {'rect':pygame.Rect(100, 150, 60, 60), 'color':BLUE, 'dir':DOWNLEFT}
+blocks = [b1, b2, b3]
+
+# run the game loop
+while True:
+    # check for the QUIT event
+    for event in pygame.event.get():
+        if event.type == QUIT:
+            pygame.quit()
+            sys.exit()
+
+    # draw the black background onto the surface
+    windowSurface.fill(BLACK)
+
+    for b in blocks:
+        # move the block data structure
+        if b['dir'] == DOWNLEFT:
+            b['rect'].left -= MOVESPEED
+            b['rect'].top += MOVESPEED
+        if b['dir'] == DOWNRIGHT:
+            b['rect'].left += MOVESPEED
+            b['rect'].top += MOVESPEED
+        if b['dir'] == UPLEFT:
+            b['rect'].left -= MOVESPEED
+            b['rect'].top -= MOVESPEED
+        if b['dir'] == UPRIGHT:
+            b['rect'].left += MOVESPEED
+            b['rect'].top -= MOVESPEED
+
+        # check if the block has move out of the window
+        if b['rect'].top < 0:
+            # block has moved past the top
+            if b['dir'] == UPLEFT:
+                b['dir'] = DOWNLEFT
+            if b['dir'] == UPRIGHT:
+                b['dir'] = DOWNRIGHT
+        if b['rect'].bottom > WINDOWHEIGHT:
+            # block has moved past the bottom
+            if b['dir'] == DOWNLEFT:
+                b['dir'] = UPLEFT
+            if b['dir'] == DOWNRIGHT:
+                b['dir'] = UPRIGHT
+        if b['rect'].left < 0:
+            # block has moved past the left side
+            if b['dir'] == DOWNLEFT:
+                b['dir'] = DOWNRIGHT
+            if b['dir'] == UPLEFT:
+                b['dir'] = UPRIGHT
+        if b['rect'].right > WINDOWWIDTH:
+            # block has moved past the right side
+            if b['dir'] == DOWNRIGHT:
+                b['dir'] = DOWNLEFT
+            if b['dir'] == UPRIGHT:
+                b['dir'] = UPLEFT
+
+        # draw the block onto the surface
+        pygame.draw.rect(windowSurface, b['color'], b['rect'])
+
+    # draw the window onto the screen
+    pygame.display.update()
+    time.sleep(0.02)

File code/background.mid

Binary file added.

File code/baddie.png

Added
New image

File code/bagels.py

+import random
+def getSecretNum(numDigits):
+    # Returns a string that is numDigits long, made up of unique random digits.
+    numbers = list(range(10))
+    random.shuffle(numbers)
+    secretNum = ''
+    for i in range(numDigits):
+        secretNum += str(numbers[i])
+    return secretNum
+
+def getClues(guess, secretNum):
+    # Returns a string with the pico, fermi, bagels clues to the user.
+    if guess == secretNum:
+        return 'You got it!'
+
+    clue = []
+
+    for i in range(len(guess)):
+        if guess[i] == secretNum[i]:
+            clue.append('Fermi')
+        elif guess[i] in secretNum:
+            clue.append('Pico')
+    if len(clue) == 0:
+        return 'Bagels'
+
+    clue.sort()
+    return ' '.join(clue)
+
+def isOnlyDigits(num):
+    # Returns True if num is a string made up only of digits. Otherwise returns False.
+    if num == '':
+        return False
+
+    for i in num:
+        if i not in '0 1 2 3 4 5 6 7 8 9'.split():
+            return False
+
+    return True
+
+def playAgain():
+    # This function returns True if the player wants to play again, otherwise it returns False.
+    print('Do you want to play again? (yes or no)')
+    return input().lower().startswith('y')
+
+NUMDIGITS = 3
+MAXGUESS = 10
+
+print('I am thinking of a %s-digit number. Try to guess what it is.' % (NUMDIGITS))
+print('Here are some clues:')
+print('When I say:    That means:')
+print('  Pico         One digit is correct but in the wrong position.')
+print('  Fermi        One digit is correct and in the right position.')
+print('  Bagels       No digit is correct.')
+
+while True:
+    secretNum = getSecretNum(NUMDIGITS)
+    print('I have thought up a number. You have %s guesses to get it.' % (MAXGUESS))
+
+    numGuesses = 1
+    while numGuesses <= MAXGUESS:
+        guess = ''
+        while len(guess) != NUMDIGITS or not isOnlyDigits(guess):
+            print('Guess #%s: ' % (numGuesses))
+            guess = input()
+
+        clue = getClues(guess, secretNum)
+        print(clue)
+        numGuesses += 1
+
+        if guess == secretNum:
+            break
+        if numGuesses > MAXGUESS:
+            print('You ran out of guesses. The answer was %s.' % (secretNum))
+
+    if not playAgain():
+        break

File code/cherry.png

Added
New image

File code/cipher.py

+# Caesar Cipher
+
+MAX_KEY_SIZE = 26
+
+def getMode():
+    while True:
+        print('Do you wish to encrypt or decrypt a message?')
+        mode = input().lower()
+        if mode in 'encrypt e decrypt d'.split():
+            return mode
+        else:
+            print('Enter either "encrypt" or "e" or "decrypt" or "d".')
+
+def getMessage():
+    print('Enter your message:')
+    return input()
+
+def getKey():
+    key = 0
+    while True:
+        print('Enter the key number (1-%s)' % (MAX_KEY_SIZE))
+        key = int(input())
+        if (key >= 1 and key <= MAX_KEY_SIZE):
+            return key
+
+def getTranslatedMessage(mode, message, key):
+    if mode[0] == 'd':
+        key = -key
+    translated = ''
+
+    for symbol in message:
+        if symbol.isalpha():
+            num = ord(symbol)
+            num += key
+
+            if symbol.isupper():
+                if num > ord('Z'):
+                    num -= 26
+                elif num < ord('A'):
+                    num += 26
+            elif symbol.islower():
+                if num > ord('z'):
+                    num -= 26
+                elif num < ord('a'):
+                    num += 26
+
+            translated += chr(num)
+        else:
+            translated += symbol
+    return translated
+
+mode = getMode()
+message = getMessage()
+key = getKey()
+
+print('Your translated text is:')
+print(getTranslatedMessage(mode, message, key))

File code/collisionDetection.py

+import pygame, sys, random
+from pygame.locals import *
+
+def doRectsOverlap(rect1, rect2):
+    for a, b in [(rect1, rect2), (rect2, rect1)]:
+        # Check if a's corners are inside b
+        if ((isPointInsideRect(a.left, a.top, b)) or
+            (isPointInsideRect(a.left, a.bottom, b)) or
+            (isPointInsideRect(a.right, a.top, b)) or
+            (isPointInsideRect(a.right, a.bottom, b))):
+            return True
+
+    return False
+
+def isPointInsideRect(x, y, rect):
+    if (x > rect.left) and (x < rect.right) and (y > rect.top) and (y < rect.bottom):
+        return True
+    else:
+        return False
+
+
+# set up pygame
+pygame.init()
+mainClock = pygame.time.Clock()
+
+# set up the window
+WINDOWWIDTH = 400
+WINDOWHEIGHT = 400
+windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
+pygame.display.set_caption('Collision Detection')
+
+# set up direction variables
+DOWNLEFT = 1
+DOWNRIGHT = 3
+UPLEFT = 7
+UPRIGHT = 9
+
+MOVESPEED = 4
+
+# set up the colors
+BLACK = (0, 0, 0)
+GREEN = (0, 255, 0)
+WHITE = (255, 255, 255)
+
+# set up the bouncer and food data structures
+foodCounter = 0
+NEWFOOD = 40
+FOODSIZE = 20
+bouncer = {'rect':pygame.Rect(300, 100, 50, 50), 'dir':UPLEFT}
+foods = []
+for i in range(20):
+    foods.append(pygame.Rect(random.randint(0, WINDOWWIDTH - FOODSIZE), random.randint(0, WINDOWHEIGHT - FOODSIZE), FOODSIZE, FOODSIZE))
+
+# run the game loop
+while True:
+    # check for the QUIT event
+    for event in pygame.event.get():
+        if event.type == QUIT:
+            pygame.quit()
+            sys.exit()
+
+    foodCounter += 1
+    if foodCounter >= NEWFOOD:
+        # add new food
+        foodCounter = 0
+        foods.append(pygame.Rect(random.randint(0, WINDOWWIDTH - FOODSIZE), random.randint(0, WINDOWHEIGHT - FOODSIZE), FOODSIZE, FOODSIZE))
+
+    # draw the black background onto the surface
+    windowSurface.fill(BLACK)
+
+    # move the bouncer data structure
+    if bouncer['dir'] == DOWNLEFT:
+        bouncer['rect'].left -= MOVESPEED
+        bouncer['rect'].top += MOVESPEED
+    if bouncer['dir'] == DOWNRIGHT:
+        bouncer['rect'].left += MOVESPEED
+        bouncer['rect'].top += MOVESPEED
+    if bouncer['dir'] == UPLEFT:
+        bouncer['rect'].left -= MOVESPEED
+        bouncer['rect'].top -= MOVESPEED
+    if bouncer['dir'] == UPRIGHT:
+        bouncer['rect'].left += MOVESPEED
+        bouncer['rect'].top -= MOVESPEED
+
+    # check if the bouncer has move out of the window
+    if bouncer['rect'].top < 0:
+        # bouncer has moved past the top
+        if bouncer['dir'] == UPLEFT:
+            bouncer['dir'] = DOWNLEFT
+        if bouncer['dir'] == UPRIGHT:
+            bouncer['dir'] = DOWNRIGHT
+    if bouncer['rect'].bottom > WINDOWHEIGHT:
+        # bouncer has moved past the bottom
+        if bouncer['dir'] == DOWNLEFT:
+            bouncer['dir'] = UPLEFT
+        if bouncer['dir'] == DOWNRIGHT:
+            bouncer['dir'] = UPRIGHT
+    if bouncer['rect'].left < 0:
+        # bouncer has moved past the left side
+        if bouncer['dir'] == DOWNLEFT:
+            bouncer['dir'] = DOWNRIGHT
+        if bouncer['dir'] == UPLEFT:
+            bouncer['dir'] = UPRIGHT
+    if bouncer['rect'].right > WINDOWWIDTH:
+        # bouncer has moved past the right side
+        if bouncer['dir'] == DOWNRIGHT:
+            bouncer['dir'] = DOWNLEFT
+        if bouncer['dir'] == UPRIGHT:
+            bouncer['dir'] = UPLEFT
+
+    # draw the bouncer onto the surface
+    pygame.draw.rect(windowSurface, WHITE, bouncer['rect'])
+
+    # check if the bouncer has intersected with any food squares.
+    for food in foods[:]:
+        if doRectsOverlap(bouncer['rect'], food):
+            foods.remove(food)
+
+    # draw the food
+    for i in range(len(foods)):
+        pygame.draw.rect(windowSurface, GREEN, foods[i])
+
+    # draw the window onto the screen
+    pygame.display.update()
+    mainClock.tick(40)

File code/dodger.py

+import pygame, random, sys
+from pygame.locals import *
+
+WINDOWWIDTH = 600
+WINDOWHEIGHT = 600
+TEXTCOLOR = (255, 255, 255)
+BACKGROUNDCOLOR = (0, 0, 0)
+FPS = 40
+BADDIEMINSIZE = 10
+BADDIEMAXSIZE = 40
+BADDIEMINSPEED = 1
+BADDIEMAXSPEED = 8
+ADDNEWBADDIERATE = 6
+PLAYERMOVERATE = 5
+
+def terminate():
+    pygame.quit()
+    sys.exit()
+
+def waitForPlayerToPressKey():
+    while True:
+        for event in pygame.event.get():
+            if event.type == QUIT:
+                terminate()
+            if event.type == KEYDOWN:
+                if event.key == K_ESCAPE: # pressing escape quits
+                    terminate()
+                return
+
+def playerHasHitBaddie(playerRect, baddies):
+    for b in baddies:
+        if playerRect.colliderect(b['rect']):
+            return True
+    return False
+
+def drawText(text, font, surface, x, y):
+    textobj = font.render(text, 1, TEXTCOLOR)
+    textrect = textobj.get_rect()
+    textrect.topleft = (x, y)
+    surface.blit(textobj, textrect)
+
+# set up pygame, the window, and the mouse cursor
+pygame.init()
+mainClock = pygame.time.Clock()
+windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
+pygame.display.set_caption('Dodger')
+pygame.mouse.set_visible(False)
+
+# set up fonts
+font = pygame.font.SysFont(None, 48)
+
+# set up sounds
+gameOverSound = pygame.mixer.Sound('gameover.wav')
+pygame.mixer.music.load('background.mid')
+
+# set up images
+playerImage = pygame.image.load('player.png')
+playerRect = playerImage.get_rect()
+baddieImage = pygame.image.load('baddie.png')
+
+# show the "Start" screen
+drawText('Dodger', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
+drawText('Press a key to start.', font, windowSurface, (WINDOWWIDTH / 3) - 30, (WINDOWHEIGHT / 3) + 50)
+pygame.display.update()
+waitForPlayerToPressKey()
+
+
+topScore = 0
+while True:
+    # set up the start of the game
+    baddies = []
+    score = 0
+    playerRect.topleft = (WINDOWWIDTH / 2, WINDOWHEIGHT - 50)
+    moveLeft = moveRight = moveUp = moveDown = False
+    reverseCheat = slowCheat = False
+    baddieAddCounter = 0
+    pygame.mixer.music.play(-1, 0.0)
+
+    while True: # the game loop runs while the game part is playing
+        score += 1 # increase score
+
+        for event in pygame.event.get():
+            if event.type == QUIT:
+                terminate()
+
+            if event.type == KEYDOWN:
+                if event.key == ord('z'):
+                    reverseCheat = True
+                if event.key == ord('x'):
+                    slowCheat = True
+                if event.key == K_LEFT or event.key == ord('a'):
+                    moveRight = False
+                    moveLeft = True
+                if event.key == K_RIGHT or event.key == ord('d'):
+                    moveLeft = False
+                    moveRight = True
+                if event.key == K_UP or event.key == ord('w'):
+                    moveDown = False
+                    moveUp = True
+                if event.key == K_DOWN or event.key == ord('s'):
+                    moveUp = False
+                    moveDown = True
+
+            if event.type == KEYUP:
+                if event.key == ord('z'):
+                    reverseCheat = False
+                    score = 0
+                if event.key == ord('x'):
+                    slowCheat = False
+                    score = 0
+                if event.key == K_ESCAPE:
+                        terminate()
+
+                if event.key == K_LEFT or event.key == ord('a'):
+                    moveLeft = False
+                if event.key == K_RIGHT or event.key == ord('d'):
+                    moveRight = False
+                if event.key == K_UP or event.key == ord('w'):
+                    moveUp = False
+                if event.key == K_DOWN or event.key == ord('s'):
+                    moveDown = False
+
+            if event.type == MOUSEMOTION:
+                # If the mouse moves, move the player where the cursor is.
+                playerRect.move_ip(event.pos[0] - playerRect.centerx, event.pos[1] - playerRect.centery)
+
+        # Add new baddies at the top of the screen, if needed.
+        if not reverseCheat and not slowCheat:
+            baddieAddCounter += 1
+        if baddieAddCounter == ADDNEWBADDIERATE:
+            baddieAddCounter = 0
+            baddieSize = random.randint(BADDIEMINSIZE, BADDIEMAXSIZE)
+            newBaddie = {'rect': pygame.Rect(random.randint(0, WINDOWWIDTH-baddieSize), 0 - baddieSize, baddieSize, baddieSize),
+                        'speed': random.randint(BADDIEMINSPEED, BADDIEMAXSPEED),
+                        'surface':pygame.transform.scale(baddieImage, (baddieSize, baddieSize)),
+                        }
+
+            baddies.append(newBaddie)
+
+        # Move the player around.
+        if moveLeft and playerRect.left > 0:
+            playerRect.move_ip(-1 * PLAYERMOVERATE, 0)
+        if moveRight and playerRect.right < WINDOWWIDTH:
+            playerRect.move_ip(PLAYERMOVERATE, 0)
+        if moveUp and playerRect.top > 0:
+            playerRect.move_ip(0, -1 * PLAYERMOVERATE)
+        if moveDown and playerRect.bottom < WINDOWHEIGHT:
+            playerRect.move_ip(0, PLAYERMOVERATE)
+
+        # Move the mouse cursor to match the player.
+        pygame.mouse.set_pos(playerRect.centerx, playerRect.centery)
+
+        # Move the baddies down.
+        for b in baddies:
+            if not reverseCheat and not slowCheat:
+                b['rect'].move_ip(0, b['speed'])
+            elif reverseCheat:
+                b['rect'].move_ip(0, -5)
+            elif slowCheat:
+                b['rect'].move_ip(0, 1)
+
+         # Delete baddies that have fallen past the bottom.
+        for b in baddies[:]:
+            if b['rect'].top > WINDOWHEIGHT:
+                baddies.remove(b)
+
+        # Draw the game world on the window.
+        windowSurface.fill(BACKGROUNDCOLOR)
+
+        # Draw the score and top score.
+        drawText('Score: %s' % (score), font, windowSurface, 10, 0)
+        drawText('Top Score: %s' % (topScore), font, windowSurface, 10, 40)
+
+        # Draw the player's rectangle
+        windowSurface.blit(playerImage, playerRect)
+
+        # Draw each baddie
+        for b in baddies:
+            windowSurface.blit(b['surface'], b['rect'])
+
+        pygame.display.update()
+
+        # Check if any of the baddies have hit the player.
+        if playerHasHitBaddie(playerRect, baddies):
+            if score > topScore:
+                topScore = score # set new top score
+            break
+
+        mainClock.tick(FPS)
+
+    # Stop the game and show the "Game Over" screen.
+    pygame.mixer.music.stop()
+    gameOverSound.play()
+
+    drawText('GAME OVER', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
+    drawText('Press a key to play again.', font, windowSurface, (WINDOWWIDTH / 3) - 80, (WINDOWHEIGHT / 3) + 50)
+    pygame.display.update()
+    waitForPlayerToPressKey()
+
+    gameOverSound.stop()

File code/dragon.py

+import random
+import time
+
+def displayIntro():
+    print('You are in a land full of dragons. In front of you,')
+    print('you see two caves. In one cave, the dragon is friendly')
+    print('and will share his treasure with you. The other dragon')
+    print('is greedy and hungry, and will eat you on sight.')
+    print()
+
+def chooseCave():
+    cave = ''
+    while cave != '1' and cave != '2':
+        print('Which cave will you go into? (1 or 2)')
+        cave = input()
+
+    return cave
+
+def checkCave(chosenCave):
+    print('You approach the cave...')
+    time.sleep(2)
+    print('It is dark and spooky...')
+    time.sleep(2)
+    print('A large dragon jumps out in front of you! He opens his jaws and...')
+    print()
+    time.sleep(2)
+
+    friendlyCave = random.randint(1, 2)
+
+    if chosenCave == str(friendlyCave):
+         print('Gives you his treasure!')
+    else:
+         print('Gobbles you down in one bite!')
+
+playAgain = 'yes'
+while playAgain == 'yes' or playAgain == 'y':
+
+    displayIntro()
+
+    caveNumber = chooseCave()
+
+    checkCave(caveNumber)
+
+    print('Do you want to play again? (yes or no)')
+    playAgain = input()

File code/gameover.wav

Binary file added.

File code/guess.py

+# This is a guess the number game.
+import random
+
+guessesTaken = 0
+
+print('Hello! What is your name?')
+myName = input()
+
+number = random.randint(1, 20)
+print('Well, ' + myName + ', I am thinking of a number between 1 and 20.')
+
+while guessesTaken < 6:
+    print('Take a guess.') # There are four spaces in front of print.
+    guess = input()
+    guess = int(guess)
+
+    guessesTaken = guessesTaken + 1
+
+    if guess < number:
+        print('Your guess is too low.') # There are eight spaces in front of print.
+
+    if guess > number:
+        print('Your guess is too high.')
+
+    if guess == number:
+        break
+
+if guess == number:
+    guessesTaken = str(guessesTaken)
+    print('Good job, ' + myName + '! You guessed my number in ' + guessesTaken + ' guesses!')
+
+if guess != number:
+    number = str(number)
+    print('Nope. The number I was thinking of was ' + number)

File code/hangman.py

+HANGMANPICS = ['''
+
+  +---+
+  |   |
+      |
+      |
+      |
+      |
+=========''', '''
+
+  +---+
+  |   |
+  O   |
+      |
+      |
+      |
+=========''', '''
+
+  +---+
+  |   |
+  O   |
+  |   |
+      |
+      |
+=========''', '''
+
+  +---+
+  |   |
+  O   |
+ /|   |
+      |
+      |
+=========''', '''
+
+  +---+
+  |   |
+  O   |
+ /|\  |
+      |
+      |
+=========''', '''
+
+  +---+
+  |   |
+  O   |
+ /|\  |
+ /    |
+      |
+=========''', '''
+
+  +---+
+  |   |
+  O   |
+ /|\  |
+ / \  |
+      |
+=========''']
+
+words = 'ant baboon badger bat bear beaver camel cat clam cobra cougar coyote crow deer dog donkey duck eagle ferret fox frog goat goose hawk lion lizard llama mole monkey moose mouse mule newt otter owl panda parrot pigeon python rabbit ram rat raven rhino salmon seal shark sheep skunk sloth snake spider stork swan tiger toad trout turkey turtle weasel whale wolf wombat zebra'.split()
+
+def getRandomWord(wordList):
+    # This function returns a random string from the passed list of strings.
+    wordIndex = random.randint(0, len(wordList) - 1)
+    return wordList[wordIndex]
+
+def displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord):
+    print(HANGMANPICS[len(missedLetters)])
+    print()
+
+    print('Missed letters:', end=' ')
+    for letter in missedLetters:
+        print(letter, end=' ')
+    print()
+
+    blanks = '_' * len(secretWord)
+
+    for i in range(len(secretWord)): # replace blanks with correctly guessed letters
+        if secretWord[i] in correctLetters:
+            blanks = blanks[:i] + secretWord[i] + blanks[i+1:]
+
+    for letter in blanks: # show the secret word with spaces in between each letter
+        print(letter, end=' ')
+    print()
+
+def getGuess(alreadyGuessed):
+    # Returns the letter the player entered. This function makes sure the player entered a single letter, and not something else.
+    while True:
+        print('Guess a letter.')
+        guess = input()
+        guess = guess.lower()
+        if len(guess) != 1:
+            print('Please enter a single letter.')
+        elif guess in alreadyGuessed
+            print('You have already guessed that letter. Choose again.')
+        elif guess not in 'abcdefghijklmnopqrstuvwxyz':
+            print('Please enter a LETTER.')
+        else:
+            return guess
+
+def playAgain():
+    # This function returns True if the player wants to play again, otherwise it returns False.
+    print('Do you want to play again? (yes or no)')
+    return input().lower().startswith('y')
+
+
+print('H A N G M A N')
+missedLetters = ''
+correctLetters = ''
+secretWord = getRandomWord(words)
+gameIsDone = False
+
+while True:
+    displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord)
+
+    # Let the player type in a letter.
+    guess = getGuess(missedLetters + correctLetters)
+
+    if guess in secretWord:
+        correctLetters = correctLetters + guess
+
+        # Check if the player has won
+        foundAllLetters = True
+        for i in range(len(secretWord)):
+            if secretWord[i] not in correctLetters:
+                foundAllLetters = False
+                break
+        if foundAllLetters:
+            print('Yes! The secret word is "' + secretWord + '"! You have won!')
+            gameIsDone = True
+    else:
+        missedLetters = missedLetters + guess
+
+        # Check if player has guessed too many times and lost
+        if len(missedLetters) == len(HANGMANPICS) - 1:
+            displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord)
+            print('You have run out of guesses!\nAfter ' + str(len(missedLetters)) + ' missed guesses and ' + str(len(correctLetters)) + ' correct guesses, the word was "' + secretWord + '"')
+            gameIsDone = True
+
+    # Ask the player if they want to play again (but only if the game is done).
+    if gameIsDone:
+        if playAgain():
+            missedLetters = ''
+            correctLetters = ''
+            gameIsDone = False
+            secretWord = getRandomWord(words)
+        else:
+            break

File code/hello.py

+# This program says hello and asks for my name.
+print('Hello world!')
+print('What is your name?')
+myName = input()
+print('It is good to meet you, ' + myName)

File code/jokes.py

+print('What do you get when you cross a snowman with a vampire?')
+input()
+print('Frostbite!')
+print()
+print('What do dentists call a astronaut\'s cavity?')
+input()
+print('A black hole!')
+print()
+print('Knock knock.')
+input()
+print("Who's there?")
+input()
+print('Interrupting cow.')
+input()
+print('Interrupting cow wh', end='')
+print('-MOO!')

File code/pickup.wav

Binary file added.

File code/player.png

Added
New image

File code/pygameHelloWorld.py

+import pygame, sys
+from pygame.locals import *
+
+# set up pygame
+pygame.init()
+
+# set up the window
+windowSurface = pygame.display.set_mode((500, 400), 0, 32)
+pygame.display.set_caption('Hello world!')
+
+# set up the colors
+BLACK = (0, 0, 0)
+WHITE = (255, 255, 255)
+RED = (255, 0, 0)
+GREEN = (0, 255, 0)
+BLUE = (0, 0, 255)
+
+# set up fonts
+basicFont = pygame.font.SysFont(None, 48)
+
+# set up the text
+text = basicFont.render('Hello world!', True, WHITE, BLUE)
+textRect = text.get_rect()
+textRect.centerx = windowSurface.get_rect().centerx
+textRect.centery = windowSurface.get_rect().centery
+
+# draw the white background onto the surface
+windowSurface.fill(WHITE)
+
+# draw a green polygon onto the surface
+pygame.draw.polygon(windowSurface, GREEN, ((146, 0), (291, 106), (236, 277), (56, 277), (0, 106)))
+
+# draw some blue lines onto the surface
+pygame.draw.line(windowSurface, BLUE, (60, 60), (120, 60), 4)
+pygame.draw.line(windowSurface, BLUE, (120, 60), (60, 120))
+pygame.draw.line(windowSurface, BLUE, (60, 120), (120, 120), 4)
+
+# draw a blue circle onto the surface
+pygame.draw.circle(windowSurface, BLUE, (300, 50), 20, 0)
+
+# draw a red ellipse onto the surface
+pygame.draw.ellipse(windowSurface, RED, (300, 250, 40, 80), 1)
+
+# draw the text's background rectangle onto the surface
+pygame.draw.rect(windowSurface, RED, (textRect.left - 20, textRect.top - 20, textRect.width + 40, textRect.height + 40))
+
+# get a pixel array of the surface
+pixArray = pygame.PixelArray(windowSurface)
+pixArray[480][380] = BLACK
+del pixArray
+
+# draw the text onto the surface
+windowSurface.blit(text, textRect)
+
+# draw the window onto the screen
+pygame.display.update()
+
+# run the game loop
+while True:
+    for event in pygame.event.get():
+        if event.type == QUIT:
+            pygame.quit()
+            sys.exit()

File code/pygameInput.py

+import pygame, sys, random
+from pygame.locals import *
+
+# set up pygame
+pygame.init()
+mainClock = pygame.time.Clock()
+
+# set up the window
+WINDOWWIDTH = 400
+WINDOWHEIGHT = 400
+windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
+pygame.display.set_caption('Input')
+
+# set up the colors
+BLACK = (0, 0, 0)
+GREEN = (0, 255, 0)
+WHITE = (255, 255, 255)
+
+# set up the player and food data structure
+foodCounter = 0
+NEWFOOD = 40
+FOODSIZE = 20
+player = pygame.Rect(300, 100, 50, 50)
+foods = []
+for i in range(20):
+    foods.append(pygame.Rect(random.randint(0, WINDOWWIDTH - FOODSIZE), random.randint(0, WINDOWHEIGHT - FOODSIZE), FOODSIZE, FOODSIZE))
+
+# set up movement variables
+moveLeft = False
+moveRight = False
+moveUp = False
+moveDown = False
+
+MOVESPEED = 6
+
+
+# run the game loop
+while True:
+    # check for events
+    for event in pygame.event.get():
+        if event.type == QUIT:
+            pygame.quit()
+            sys.exit()
+        if event.type == KEYDOWN:
+            # change the keyboard variables
+            if event.key == K_LEFT or event.key == ord('a'):
+                moveRight = False
+                moveLeft = True
+            if event.key == K_RIGHT or event.key == ord('d'):
+                moveLeft = False
+                moveRight = True
+            if event.key == K_UP or event.key == ord('w'):
+                moveDown = False
+                moveUp = True
+            if event.key == K_DOWN or event.key == ord('s'):
+                moveUp = False
+                moveDown = True
+        if event.type == KEYUP:
+            if event.key == K_ESCAPE:
+                pygame.quit()
+                sys.exit()
+            if event.key == K_LEFT or event.key == ord('a'):
+                moveLeft = False
+            if event.key == K_RIGHT or event.key == ord('d'):
+                moveRight = False
+            if event.key == K_UP or event.key == ord('w'):
+                moveUp = False
+            if event.key == K_DOWN or event.key == ord('s'):
+                moveDown = False
+            if event.key == ord('x'):
+                player.top = random.randint(0, WINDOWHEIGHT - player.height)
+                player.left = random.randint(0, WINDOWWIDTH - player.width)
+
+        if event.type == MOUSEBUTTONUP:
+            foods.append(pygame.Rect(event.pos[0], event.pos[1], FOODSIZE, FOODSIZE))
+
+    foodCounter += 1
+    if foodCounter >= NEWFOOD:
+        # add new food
+        foodCounter = 0
+        foods.append(pygame.Rect(random.randint(0, WINDOWWIDTH - FOODSIZE), random.randint(0, WINDOWHEIGHT - FOODSIZE), FOODSIZE, FOODSIZE))
+
+    # draw the black background onto the surface
+    windowSurface.fill(BLACK)
+
+    # move the player
+    if moveDown and player.bottom < WINDOWHEIGHT:
+        player.top += MOVESPEED
+    if moveUp and player.top > 0:
+        player.top -= MOVESPEED
+    if moveLeft and player.left > 0:
+        player.left -= MOVESPEED
+    if moveRight and player.right < WINDOWWIDTH:
+        player.right += MOVESPEED
+
+    # draw the player onto the surface
+    pygame.draw.rect(windowSurface, WHITE, player)
+
+    # check if the player has intersected with any food squares.
+    for food in foods[:]:
+        if player.colliderect(food):
+            foods.remove(food)
+
+    # draw the food
+    for i in range(len(foods)):
+        pygame.draw.rect(windowSurface, GREEN, foods[i])
+
+    # draw the window onto the screen
+    pygame.display.update()
+    mainClock.tick(40)

File code/reversi.py

+# Reversi
+
+import random
+import sys
+
+def drawBoard(board):
+    # This function prints out the board that it was passed. Returns None.
+    HLINE = '  +---+---+---+---+---+---+---+---+'
+    VLINE = '  |   |   |   |   |   |   |   |   |'
+
+    print('    1   2   3   4   5   6   7   8')
+    print(HLINE)
+    for y in range(8):
+        print(VLINE)
+        print(y+1, end=' ')
+        for x in range(8):
+            print('| %s' % (board[x][y]), end=' ')
+        print('|')
+        print(VLINE)
+        print(HLINE)
+
+
+def resetBoard(board):
+    # Blanks out the board it is passed, except for the original starting position.
+    for x in range(8):
+        for y in range(8):
+            board[x][y] = ' '
+
+    # Starting pieces:
+    board[3][3] = 'X'
+    board[3][4] = 'O'
+    board[4][3] = 'O'
+    board[4][4] = 'X'
+
+
+def getNewBoard():
+    # Creates a brand new, blank board data structure.
+    board = []
+    for i in range(8):
+        board.append([' '] * 8)
+
+    return board
+
+
+def isValidMove(board, tile, xstart, ystart):
+    # Returns False if the player's move on space xstart, ystart is invalid.
+    # If it is a valid move, returns a list of spaces that would become the player's if they made a move here.
+    if board[xstart][ystart] != ' ' or not isOnBoard(xstart, ystart):
+        return False
+
+    board[xstart][ystart] = tile # temporarily set the tile on the board.
+
+    if tile == 'X':
+        otherTile = 'O'
+    else:
+        otherTile = 'X'
+
+    tilesToFlip = []
+    for xdirection, ydirection in [[0, 1], [1, 1], [1, 0], [1, -1], [0, -1], [-1, -1], [-1, 0], [-1, 1]]:
+        x, y = xstart, ystart
+        x += xdirection # first step in the direction
+        y += ydirection # first step in the direction
+        if isOnBoard(x, y) and board[x][y] == otherTile:
+            # There is a piece belonging to the other player next to our piece.
+            x += xdirection
+            y += ydirection
+            if not isOnBoard(x, y):
+                continue
+            while board[x][y] == otherTile:
+                x += xdirection
+                y += ydirection
+                if not isOnBoard(x, y): # break out of while loop, then continue in for loop
+                    break
+            if not isOnBoard(x, y):
+                continue
+            if board[x][y] == tile:
+                # There are pieces to flip over. Go in the reverse direction until we reach the original space, noting all the tiles along the way.
+                while True:
+                    x -= xdirection
+                    y -= ydirection
+                    if x == xstart and y == ystart:
+                        break
+                    tilesToFlip.append([x, y])
+
+    board[xstart][ystart] = ' ' # restore the empty space
+    if len(tilesToFlip) == 0: # If no tiles were flipped, this is not a valid move.
+        return False
+    return tilesToFlip
+
+
+def isOnBoard(x, y):
+    # Returns True if the coordinates are located on the board.
+    return x >= 0 and x <= 7 and y >= 0 and y <=7
+
+
+def getBoardWithValidMoves(board, tile):
+    # Returns a new board with . marking the valid moves the given player can make.
+    dupeBoard = getBoardCopy(board)
+
+    for x, y in getValidMoves(dupeBoard, tile):
+        dupeBoard[x][y] = '.'
+    return dupeBoard
+
+
+def getValidMoves(board, tile):
+    # Returns a list of [x,y] lists of valid moves for the given player on the given board.
+    validMoves = []
+
+    for x in range(8):
+        for y in range(8):
+            if isValidMove(board, tile, x, y) != False:
+                validMoves.append([x, y])
+    return validMoves
+
+
+def getScoreOfBoard(board):
+    # Determine the score by counting the tiles. Returns a dictionary with keys 'X' and 'O'.
+    xscore = 0
+    oscore = 0
+    for x in range(8):
+        for y in range(8):
+            if board[x][y] == 'X':
+                xscore += 1
+            if board[x][y] == 'O':
+                oscore += 1
+    return {'X':xscore, 'O':oscore}
+
+
+def enterPlayerTile():
+    # Let's the player type which tile they want to be.
+    # Returns a list with the player's tile as the first item, and the computer's tile as the second.
+    tile = ''
+    while not (tile == 'X' or tile == 'O'):
+        print('Do you want to be X or O?')
+        tile = input().upper()
+
+    # the first element in the tuple is the player's tile, the second is the computer's tile.
+    if tile == 'X':
+        return ['X', 'O']
+    else:
+        return ['O', 'X']
+
+
+def whoGoesFirst():
+    # Randomly choose the player who goes first.
+    if random.randint(0, 1) == 0:
+        return 'computer'
+    else:
+        return 'player'
+
+
+def playAgain():
+    # This function returns True if the player wants to play again, otherwise it returns False.
+    print('Do you want to play again? (yes or no)')
+    return input().lower().startswith('y')
+
+
+def makeMove(board, tile, xstart, ystart):
+    # Place the tile on the board at xstart, ystart, and flip any of the opponent's pieces.
+    # Returns False if this is an invalid move, True if it is valid.
+    tilesToFlip = isValidMove(board, tile, xstart, ystart)
+
+    if tilesToFlip == False:
+        return False
+
+    board[xstart][ystart] = tile
+    for x, y in tilesToFlip:
+        board[x][y] = tile
+    return True
+
+
+def getBoardCopy(board):
+    # Make a duplicate of the board list and return the duplicate.
+    dupeBoard = getNewBoard()
+
+    for x in range(8):
+        for y in range(8):
+            dupeBoard[x][y] = board[x][y]
+
+    return dupeBoard
+
+
+def isOnCorner(x, y):
+    # Returns True if the position is in one of the four corners.
+    return (x == 0 and y == 0) or (x == 7 and y == 0) or (x == 0 and y == 7) or (x == 7 and y == 7)