Friday, December 20, 2013
Friday, December 6, 2013
(12.2.2013 - 12.6.2013)
Things Ben accomplished this week:
1. Hardcore python
2. This meme
Here's some code for your perusing:
# 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),
for x in range(8):
print('| %s' % (board[x][y])),
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 = raw_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 raw_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 = raw_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)
playerTile, computerTile = enterPlayerTile()
showHints = False
turn = whoGoesFirst()
print('The ' + turn + ' will go first.')
while True:
if turn == 'player':
# Player's turn.
if showHints:
validMovesBoard = getBoardWithValidMoves(mainBoard, playerTile)
drawBoard(validMovesBoard)
else:
drawBoard(mainBoard)
showPoints(playerTile, computerTile)
move = getPlayerMove(mainBoard, playerTile)
if move == 'quit':
print('Thanks for playing!')
sys.exit() # terminate the program
elif move == 'hints':
showHints = not showHints
continue
else:
makeMove(mainBoard, playerTile, move[0], move[1])
if getValidMoves(mainBoard, computerTile) == []:
break
else:
turn = 'computer'
else:
# Computer's turn.
drawBoard(mainBoard)
showPoints(playerTile, computerTile)
raw_input('Press Enter to see the computer\'s move.')
x, y = getComputerMove(mainBoard, computerTile)
makeMove(mainBoard, computerTile, x, y)
if getValidMoves(mainBoard, playerTile) == []:
break
else:
turn = 'player'
# Display the final score.
drawBoard(mainBoard)
scores = getScoreOfBoard(mainBoard)
print('X scored %s points. O scored %s points.' % (scores['X'], scores['O']))
if scores[playerTile] > scores[computerTile]:
print('You beat the computer by %s points! Congratulations!' % (scores[playerTile] - scores[computerTile]))
elif scores[playerTile] < scores[computerTile]:
print('You lost. The computer beat you by %s points.' % (scores[computerTile] - scores[playerTile]))
else:
print('The game was a tie!')
if not playAgain():
break
#Fibonacci
import time
fib=1
n=0
temp=0
#def nextNum():
# print('Do you want to go the the next number in teh sequence? (y or n) '),
# return raw_input().lower().startswith('y')
while True:
n=fib+temp
print n
temp=fib
fib=n
time.sleep(.25)
import time
float(fib=1.0)
float(n=0.0)
float(temp=0.0)
float(phi=0.0)
float(binaryPhi=0.0)
float(octalPhi=0.0)
float(hexPhi=0.0)
while True:
n=fib+temp
temp=fib
fib=n
phi=fib/temp
binaryPhi=bin(phi)
hexPhi=hex(phi)
octalPhi=oct(phi)
print('Phi: '),
print phi
print('Binary phi: '),
print binaryPhi
print('Hexadecimal phi: '),
print hexPhi
print('Octal phi: ')
print octalPhi
time.sleep(.25)
1. Hardcore python
2. This meme
Here's some code for your perusing:
# 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),
for x in range(8):
print('| %s' % (board[x][y])),
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 = raw_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 raw_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 = raw_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)
playerTile, computerTile = enterPlayerTile()
showHints = False
turn = whoGoesFirst()
print('The ' + turn + ' will go first.')
while True:
if turn == 'player':
# Player's turn.
if showHints:
validMovesBoard = getBoardWithValidMoves(mainBoard, playerTile)
drawBoard(validMovesBoard)
else:
drawBoard(mainBoard)
showPoints(playerTile, computerTile)
move = getPlayerMove(mainBoard, playerTile)
if move == 'quit':
print('Thanks for playing!')
sys.exit() # terminate the program
elif move == 'hints':
showHints = not showHints
continue
else:
makeMove(mainBoard, playerTile, move[0], move[1])
if getValidMoves(mainBoard, computerTile) == []:
break
else:
turn = 'computer'
else:
# Computer's turn.
drawBoard(mainBoard)
showPoints(playerTile, computerTile)
raw_input('Press Enter to see the computer\'s move.')
x, y = getComputerMove(mainBoard, computerTile)
makeMove(mainBoard, computerTile, x, y)
if getValidMoves(mainBoard, playerTile) == []:
break
else:
turn = 'player'
# Display the final score.
drawBoard(mainBoard)
scores = getScoreOfBoard(mainBoard)
print('X scored %s points. O scored %s points.' % (scores['X'], scores['O']))
if scores[playerTile] > scores[computerTile]:
print('You beat the computer by %s points! Congratulations!' % (scores[playerTile] - scores[computerTile]))
elif scores[playerTile] < scores[computerTile]:
print('You lost. The computer beat you by %s points.' % (scores[computerTile] - scores[playerTile]))
else:
print('The game was a tie!')
if not playAgain():
break
#Fibonacci
import time
fib=1
n=0
temp=0
#def nextNum():
# print('Do you want to go the the next number in teh sequence? (y or n) '),
# return raw_input().lower().startswith('y')
while True:
n=fib+temp
print n
temp=fib
fib=n
time.sleep(.25)
import time
float(fib=1.0)
float(n=0.0)
float(temp=0.0)
float(phi=0.0)
float(binaryPhi=0.0)
float(octalPhi=0.0)
float(hexPhi=0.0)
while True:
n=fib+temp
temp=fib
fib=n
phi=fib/temp
binaryPhi=bin(phi)
hexPhi=hex(phi)
octalPhi=oct(phi)
print('Phi: '),
print phi
print('Binary phi: '),
print binaryPhi
print('Hexadecimal phi: '),
print hexPhi
print('Octal phi: ')
print octalPhi
time.sleep(.25)
Friday, November 22, 2013
lel (11.18.2013 - 11.22.2013)
import random
import sys
def drawBoard(board):
#prints 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),
for x in range(8):
print('| %s'%(board[x][y])),
print('|')
print(VLINE)
print(HLINE)
def resetBoard(board):
#Blanks out the board it is passed, except for th eoriginal 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 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's valid, returns a list of spaces that would become players' if they made a move here.
if board[xstart][ystart]!=' ' or not isOnBoard(xstart, ystart):
return False
board[xstart][ystart]=tile #temporarialy sets 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 si 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
if not isOnBoard(x, y):
continue
if board[x][y]==tile:
#There are pieces to filp over. Go reverse direction till we reach orig space, noting 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, not a valid move
return False
return tilesToFlip
def isOnBoard(x, y):
#Retursn 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 teh 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 dict 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():
#Lets the player type which tile they wanna be
#Return a list with the player's tile as the first item, and teh computer's tile as the second
tile=''
while not (tile=='X' or tile=='O'):
print('Do you want to be X or O?'),
tile=raw_input().upper()
#the first element in the tuple is the player's tile, the second is the computer's
if tile=='X':
return ['X', 'O']
else:
return ['O', 'X']
def whoGoesFirst():
#randomly chooses the player who goes first
if random.randint(0, 1)==0:
return 'computer'
else:
return 'player'
def playAgain():
print('Do you want to play again?')
return raw_input().lower().startswith('y')
def makeMove(board, tile, xstart, ystart):
#Place tile on teh board at xstart, ystart, and flip any of the opponent's pieces
#Returns False if this is an invalid move, true if it's 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 pos is in one of the corners
return (x==0 and y==0) or (x==7 and y==0) or (x==0 and y==7) or (x==y and y==7)
def getPlayerMove(board, playerTile):
#Let teh player type their move
#returns teh move as [x, y] (or returns 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 on/off hints.')
move=raw_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 an [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 cmoputer has %s points.'%(scores[playerTile], scores[computerTile]))
print('Welcome to Reversi!')
while True:
#Retet board and game
mainBoard=getNewBoard()
resetBoard(mainBoard)
playerTile, computerTile=enterPlayerTile()
showHints=False
turn=whoGoesFirst()
print('The '+turn+' will go first.')
while True:
if turn=='player':
#Player's turn
if showHints:
validMovesBoard=getBoardWithValidMoves(mainBoard, playerTile)
drawBoard(validMovesBoard)
else:
drawBoard(mainBoard)
showPoints(playerTile, computerTile)
move=getPlayerMove(mainBoard, playerTile)
if move=='quit':
print('Thanks for playing!')
sys.exit() #Terminate program
elif move=='hints':
showHints=not showHints
continue
else:
makeMove(mainBoard, playerTile, move[0], move[1])
if getValidMoves(mainBoard, computerTile)==[]:
break
else:
turn='computer'
else:
#computer's turn
drawBoard(mainBoard)
showPoints(playerTile, computerTile)
raw_input('Press Enter to see the computer\'s move.')
x, y=getComputerMove(mainBoard, computerTile)
makeMove(mainBoard, computerTile, x, y)
if getValidMoves(mainBoard, playerTile)==[]:
break
else:
turn='player'
#Display the final score
drawBoard(mainBoard)
scores=getScoreOfBoard(mainBoard)
print('X scored %s points. Y scored %s points.'%(scores['X'], scores['O']))
if scores[playerTile]>scores[computerTile]:
print('You won by %s points!' %(scores[playerTile]-scores[computerTile]))
elif scores[playerTile]<scores[computerTile]:
print('You lost by %s points.' %(scores[computerTile]-scores[playerTile]))
else:
print('The game was a tie!')
if not playAgain():
break
Friday, November 15, 2013
Reversi (11.11.13 - 11.15.13)
import random
import sys
def drawBoard(board):
#prints 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 th eoriginal starting position
for x in range(8):
for y in range(8):
board[x][y]=' '
#Starting pieces:
board[3][3]='X'
board[4][4]='O'
board[4][3]='O'
board[4][4]='O'
def getNewBoard():
#Creates a new blank board data structure
board=[]
for i in range(8):
board.append([' ']*8)
return board
def isValidMove(board, title, xstart, ystart):
#returns false if the player's move on space xstart, ystart is invalid
#If it's valid, returns a list of spaces that would become players' if they made a move here.
if board[xstart][ystart]!=' ' or not isOnBoard(xstart, ystart):
return Flalse
board[xstart][ystart]=title #temporarialy sets title on the board
if title=='X':
otherTitle='O'
else:
otherTitle='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]==otherTitle:
#There si 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]==otherTitle:
x+=xdirection
y+=ydirection
if not isOnBoard(x, y):
break
if not isOnBoard(x, y):
continue
if board[x][y]==title:
#There are pieces to filp over. Go reverse direction till we reach orig space, noting tiles along the way
whiel 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, not a valid move
return False
return tilesToFlip
def isOnBoard(x, y):
#Retursn True if the coordinates are located on the board
return x>=0 and x<=7 and y>=0 and y<=7
def getBoardWithValidMoves(board, title):
#Returns a new board with . marking teh 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, title):
#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 dict 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 enterPlayerTitle():
#Lets the player type which tile they wanna be
#Return a list with the player's tile as the first item, and teh 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
if tile=='X':
return ['X', 'O']
else:
return ['O', 'X']
def whoGoesFirst():
#randomly chooses the player who goes first
if random.randint(0, 1)==0:
return 'computer'
else:
return 'player'
def playAgain():
print('Do you want to play again?')
return input().lower().startswith('y')
def makeMove(board, tile, xstart, ystart):
#Place tile on teh board at xstart, ystart, and flip any of the opponent's pieces
#Returns False if this is an invalid move, true if it's 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 pos is in one of the corners
return (x==0 and y==0) or (x==7 and y==0) or (x==0 and y==7) or (x==y and y==7)
def getPlayerMove(board, playerTile):
#Let teh player type their move
#returns teh move as [x, y] (or returns 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 on/off hints.')
move=raw_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 an [x, y] list.
possibleMoves=getValidMoves(board, computerTile)
#Randomize the order of the possible moves
ramdom.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 cmoputer has %s points.'%(score[playerTile], score[cmoputerTile]))
print('Welcome to Reversi!')
while True:
#Retet board and game
mainBoard=getNewBoard()
resetBoard(mainBoard)
playerTile, computerTile=enterPlayerTile()
showHints=false
turn=whoGoesFirst()
print('The '+turn+' will go first.')
while True:
if turn=='player':
#Player's turn
if showHints:
validMovesBoard=getboardWithValidMoves(mainBoard, playerTile)
drawBoard(validMovesBoard)
else:
drawBoard(mainBoard)
showPoints(playerTile, computerTile)
move=getPlayerMove(mainBoard, playerTile)
if move=='quit':
print('Thanks for playing!')
sys.exit() #Terminate program
elif move=='hints':
showHints=not showHints
continue
else:
makeMove(mainBoard, playerTile, move[0], move[1])
if getValidMoves(mainBoard, computerTile)==[]:
break
else:
turn='computer'
else:
#computer's turn
drawBoard(mainBoard)
showPoints(playerTile, computerTile)
raw_input('Press Enter to see the computer\'s move.')
x, y=getcomputerMove(mainBoard, computerTile)
makeMove(mainBoard, computerTile, x, y)
if getValidMoves(mainBoard, playerTile)==[]:
break
else:
turn='player'
#Display the final score
drawBoard(mainBoard)
scores=getScoreOfBoard(mainBoard)
print('X scored %s points. Y scored %s points.'%(scores['X'], scores['O']))
if scores[playerTile]>scores[computerTile]:
print('You won by %s points!' %(scores[playerTile]-scores[computerTile]))
elif scores[playerTile]<scores[computerTile]:
print('You lost by %s points.' %(scores[computerTile]-scores[playerTile]))
else:
print('The game was a tie!')
if not playAgain():
break
So this is my reverse program. It still has a lot of errors. Like, don't even try running it. I ought to have it fixed by next week sometime.
If you want to know how many errors are in the program, see picture at top.
EDIT:
Here, I felt real bad like about not actually finishing anything this week, so I made a program that prints out Fibonacci numbers.
#Fibonacci
import time
fib=1
n=0
temp=0
#def nextNum():
# print('Do you want to go the the next number in teh sequence? (y or n) '),
# return raw_input().lower().startswith('y')
while True:
n=fib+temp
print n
temp=fib
fib=n
#time.sleep(.01)
If you actually want to see any of the numbers, change #time.sleep(.01) to time.sleep(.5)
import sys
def drawBoard(board):
#prints 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 th eoriginal starting position
for x in range(8):
for y in range(8):
board[x][y]=' '
#Starting pieces:
board[3][3]='X'
board[4][4]='O'
board[4][3]='O'
board[4][4]='O'
def getNewBoard():
#Creates a new blank board data structure
board=[]
for i in range(8):
board.append([' ']*8)
return board
def isValidMove(board, title, xstart, ystart):
#returns false if the player's move on space xstart, ystart is invalid
#If it's valid, returns a list of spaces that would become players' if they made a move here.
if board[xstart][ystart]!=' ' or not isOnBoard(xstart, ystart):
return Flalse
board[xstart][ystart]=title #temporarialy sets title on the board
if title=='X':
otherTitle='O'
else:
otherTitle='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]==otherTitle:
#There si 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]==otherTitle:
x+=xdirection
y+=ydirection
if not isOnBoard(x, y):
break
if not isOnBoard(x, y):
continue
if board[x][y]==title:
#There are pieces to filp over. Go reverse direction till we reach orig space, noting tiles along the way
whiel 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, not a valid move
return False
return tilesToFlip
def isOnBoard(x, y):
#Retursn True if the coordinates are located on the board
return x>=0 and x<=7 and y>=0 and y<=7
def getBoardWithValidMoves(board, title):
#Returns a new board with . marking teh 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, title):
#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 dict 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 enterPlayerTitle():
#Lets the player type which tile they wanna be
#Return a list with the player's tile as the first item, and teh 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
if tile=='X':
return ['X', 'O']
else:
return ['O', 'X']
def whoGoesFirst():
#randomly chooses the player who goes first
if random.randint(0, 1)==0:
return 'computer'
else:
return 'player'
def playAgain():
print('Do you want to play again?')
return input().lower().startswith('y')
def makeMove(board, tile, xstart, ystart):
#Place tile on teh board at xstart, ystart, and flip any of the opponent's pieces
#Returns False if this is an invalid move, true if it's 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 pos is in one of the corners
return (x==0 and y==0) or (x==7 and y==0) or (x==0 and y==7) or (x==y and y==7)
def getPlayerMove(board, playerTile):
#Let teh player type their move
#returns teh move as [x, y] (or returns 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 on/off hints.')
move=raw_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 an [x, y] list.
possibleMoves=getValidMoves(board, computerTile)
#Randomize the order of the possible moves
ramdom.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 cmoputer has %s points.'%(score[playerTile], score[cmoputerTile]))
print('Welcome to Reversi!')
while True:
#Retet board and game
mainBoard=getNewBoard()
resetBoard(mainBoard)
playerTile, computerTile=enterPlayerTile()
showHints=false
turn=whoGoesFirst()
print('The '+turn+' will go first.')
while True:
if turn=='player':
#Player's turn
if showHints:
validMovesBoard=getboardWithValidMoves(mainBoard, playerTile)
drawBoard(validMovesBoard)
else:
drawBoard(mainBoard)
showPoints(playerTile, computerTile)
move=getPlayerMove(mainBoard, playerTile)
if move=='quit':
print('Thanks for playing!')
sys.exit() #Terminate program
elif move=='hints':
showHints=not showHints
continue
else:
makeMove(mainBoard, playerTile, move[0], move[1])
if getValidMoves(mainBoard, computerTile)==[]:
break
else:
turn='computer'
else:
#computer's turn
drawBoard(mainBoard)
showPoints(playerTile, computerTile)
raw_input('Press Enter to see the computer\'s move.')
x, y=getcomputerMove(mainBoard, computerTile)
makeMove(mainBoard, computerTile, x, y)
if getValidMoves(mainBoard, playerTile)==[]:
break
else:
turn='player'
#Display the final score
drawBoard(mainBoard)
scores=getScoreOfBoard(mainBoard)
print('X scored %s points. Y scored %s points.'%(scores['X'], scores['O']))
if scores[playerTile]>scores[computerTile]:
print('You won by %s points!' %(scores[playerTile]-scores[computerTile]))
elif scores[playerTile]<scores[computerTile]:
print('You lost by %s points.' %(scores[computerTile]-scores[playerTile]))
else:
print('The game was a tie!')
if not playAgain():
break
So this is my reverse program. It still has a lot of errors. Like, don't even try running it. I ought to have it fixed by next week sometime.
If you want to know how many errors are in the program, see picture at top.
EDIT:
Here, I felt real bad like about not actually finishing anything this week, so I made a program that prints out Fibonacci numbers.
#Fibonacci
import time
fib=1
n=0
temp=0
#def nextNum():
# print('Do you want to go the the next number in teh sequence? (y or n) '),
# return raw_input().lower().startswith('y')
while True:
n=fib+temp
print n
temp=fib
fib=n
#time.sleep(.01)
If you actually want to see any of the numbers, change #time.sleep(.01) to time.sleep(.5)
Wednesday, November 6, 2013
Second post (10.04.13 - 10.08.13)
Cipher:
The program asks you to input a string and whether you want to encrypt or decrypt it. If you choose encrypt, you input your string and a key and it moves X ASCII characters up. If you decrypt it, you input a string and a key and it moves X ASCII characters down. More exciting stuff to come.
MAX_KEY_SIZE=26
def getMode():
while True:
print('Do you wanna encrypt or decrypt a message? '),
mode=raw_input().lower()
if mode in 'encrypt e decrypt d'.split():
return mode
else:
print('Enter either "encrypt" or "decrypt"')
def getMessage():
print('Enter your message:')
return raw_input()
def getKey():
key=0
while True:
print('Enter the key number (1-%s)'%(MAX_KEY_SIZE))
key=int(raw_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
def again():
print('Translate another message? '),
return raw_input().lower().startswith('y')
while True:
mode=getMode()
message=getMessage()
key=getKey()
print('Your translated text is:')
print(getTranslatedMessage(mode, message, key))
if not again():
break
The program asks you to input a string and whether you want to encrypt or decrypt it. If you choose encrypt, you input your string and a key and it moves X ASCII characters up. If you decrypt it, you input a string and a key and it moves X ASCII characters down. More exciting stuff to come.
MAX_KEY_SIZE=26
def getMode():
while True:
print('Do you wanna encrypt or decrypt a message? '),
mode=raw_input().lower()
if mode in 'encrypt e decrypt d'.split():
return mode
else:
print('Enter either "encrypt" or "decrypt"')
def getMessage():
print('Enter your message:')
return raw_input()
def getKey():
key=0
while True:
print('Enter the key number (1-%s)'%(MAX_KEY_SIZE))
key=int(raw_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
def again():
print('Translate another message? '),
return raw_input().lower().startswith('y')
while True:
mode=getMode()
message=getMessage()
key=getKey()
print('Your translated text is:')
print(getTranslatedMessage(mode, message, key))
if not again():
break
Tuesday, October 29, 2013
First post (10.28.13 - 11.01.13)
Finally finished SONAR:
A single spacing issue has held me up on this for the past 3 days but I finally found it.
Code:
import random
import sys
#IS VALID MOVE
def drawBoard(board):
#Draw the board data struct
hline=' '#Initial space for the numbers down the left side of the board
for i in range(1, 6):
hline+=(' '*9)+str(i)
#print the numbers across the top
print(hline)
print(' '+('0123456789'*6))
print
#print each of teh 15 rows
for i in range(15):
#single-digit numbers need to be padded with an extra space
if i<10:
extraSpace=' '
else:
extraSpace=''
print('%s%s %s %s' %(extraSpace, i, getRow(board,i),i))
#print the numbers across the bottom
print
print(' '+('0123456789'*6))
print(hline)
def getRow(board, row):
#Return a string from the board data structure at a certain row.
boardRow=''
for i in range(60):
boardRow+=board[i][row]
return boardRow
def getNewBoard():
#Create a new 60x15 board data structure
board=[]
for x in range(60): #The main list is a list of 60 lists
board.append([])
for y in range(15): #Each list in the main list has 15 single-character strings
#use different characters for the ocean to make it more readable.
if random.randint(0,1)==0:
board[x].append('~')
else:
board[x].append('`')
return board
def getRandomChests(numChests):
#Create a list of chest data structures (two-item lists of x, y int coordinates)
chests=[]
for i in range(numChests):
chests.append([random.randint(0, 59), random.randint(0, 14)])
return chests
def isValidMove(x, y):
#Return true if the coordinates are on the board, otherwise false.
return x>=0 and x<=59 and y>=0 and y<=14
def makeMove(board, chests, x, y):
# Change the board data structure with a sonar device character. Remove treasure chests
# from the chests list as they are found. Return False if this is an invalid move.
# Otherwise, return the string of the result of this move.
if not isValidMove(x, y):
return False
smallestDistance = 100 # any chest will be closer than 100.
for cx, cy in chests:
if abs(cx - x) > abs(cy - y):
distance = abs(cx - x)
else:
distance = abs(cy - y)
if distance < smallestDistance: # we want the closest treasure chest.
smallestDistance = distance
if smallestDistance == 0:
# xy is directly on a treasure chest!
chests.remove([x, y])
return 'You have found a sunken treasure chest!'
else:
if smallestDistance < 10:
board[x][y] = str(smallestDistance)
return 'Treasure detected at a distance of %s from the sonar device.' % (smallestDistance)
else:
board[x][y] = 'O'
return 'Sonar did not detect anything. All treasure chests out of range.'
def enterPlayerMove():
#Let the player type in her move. Return a two-item list of int xy coordinates
print('Where do you want to drop the next sonar device? (0-59 0-14) (or type quit)')
while True:
move=raw_input()
if move.lower()=='quit':
print('Thanks for playing!')
sys.exit()
move=move.split()
if len(move)==2 and move[0].isdigit() and move[1].isdigit() and isValidMove(int(move[0]), int(move[1])):
return [int(move[0]), int(move[1])]
print('Enter a number from 0 to 59, a space, then a number from 0 to 14.')
def playAgain():
#Does the player want to play again
print('Play again? (yes or no)')
return raw_input().lower().startswith('y')
def showInstructions():
print('''Instructions:
You are the captain of teh Simon, a treasure-hunting
ship. Your current mission
is to find the three sunken treasure chests that are
lurking in the part of the
ocean you are in and collect them.
To play, enter the coordinates of teh point in the ocean
you wish to drop a
sonar device. The sonar can find out how far away the
closest chest is to it.
For example, teh d below marks where the device was
dropped, and the 2's
represent distances of 2 away from teh device. The 4's
represent
distances of 4 away from teh device
444444444
4 4
4 22222 4
4 2 2 4
4 2 d 2 4
4 2 2 4
4 22222 4
4 4
444444444
Press enter to continue...''')
raw_input()
print('''For example, here is a treasure chest (the
c) located a distance of 2 away
from teh sonar device (the d):
22222
c 2
2 d 2
2 2
22222
The point where the device was dropped will be barked
with a 2.
The treasure chests don't move around. Sonar devices can
detect treasure
chests up to a distance of 9. If all chests are out of
range, the point
will be marked with O
If a device is directly dropped on a treasure chest, you have discovered
the location of the chest, and it will be collected. The
sonar device will
remain there.
When you collect a chest, all sonar devices will update
to locate the next
closest sunken treasure chest.
Press enter to continue...''')
raw_input()
print
print ('S O N A R !')
print
print('Would you like to view the instructions?(yes / no)')
if raw_input().lower().startswith('y'):
showInstructions()
while True:
#game setup
sonarDevices=16
theBoard=getNewBoard()
theChests=getRandomChests(3)
drawBoard(theBoard)
previousMoves=[]
while sonarDevices>0:
#Start of a turn:
#show sonar device/chest status
if sonarDevices>1: extraSsonar='s'
else: extraSsonar=''
if len(theChests)>1: extraSchest='s'
else: extraSchest=''
print('You have %s sonar device%s left. %s treasure chest%s remaining.'%(sonarDevices, extraSsonar, len(theChests), extraSchest))
x, y=enterPlayerMove()
previousMoves.append([x, y]) #We must track all moves so that sonar devices can be updated
moveResult=makeMove(theBoard, theChests, x, y)
if moveResult==False:
continue
else:
if moveResult=='You have found a sunken treasure chest!':
#update all the sonar devices currently on the map
for x, y in previousMoves:
makeMove(theBoard, theChests, x, y)
drawBoard(theBoard)
print(moveResult)
if len(theChests)==0:
print('You have found all the sunken treasure chests! congratulations and good game!')
break
sonarDevices-=1
if sonarDevices==0:
print('You coundn\'t find them all... game over')
print(' The remaining chests were here:')
for x, y in theChests:
print(' %s, %s'%(x, y))
if not playAgain():
sys.exit()
It's ok to be jelly.
A single spacing issue has held me up on this for the past 3 days but I finally found it.
Code:
import random
import sys
#IS VALID MOVE
def drawBoard(board):
#Draw the board data struct
hline=' '#Initial space for the numbers down the left side of the board
for i in range(1, 6):
hline+=(' '*9)+str(i)
#print the numbers across the top
print(hline)
print(' '+('0123456789'*6))
#print each of teh 15 rows
for i in range(15):
#single-digit numbers need to be padded with an extra space
if i<10:
extraSpace=' '
else:
extraSpace=''
print('%s%s %s %s' %(extraSpace, i, getRow(board,i),i))
#print the numbers across the bottom
print(' '+('0123456789'*6))
print(hline)
def getRow(board, row):
#Return a string from the board data structure at a certain row.
boardRow=''
for i in range(60):
boardRow+=board[i][row]
return boardRow
def getNewBoard():
#Create a new 60x15 board data structure
board=[]
for x in range(60): #The main list is a list of 60 lists
board.append([])
for y in range(15): #Each list in the main list has 15 single-character strings
#use different characters for the ocean to make it more readable.
if random.randint(0,1)==0:
board[x].append('~')
else:
board[x].append('`')
return board
def getRandomChests(numChests):
#Create a list of chest data structures (two-item lists of x, y int coordinates)
chests=[]
for i in range(numChests):
chests.append([random.randint(0, 59), random.randint(0, 14)])
return chests
def isValidMove(x, y):
#Return true if the coordinates are on the board, otherwise false.
return x>=0 and x<=59 and y>=0 and y<=14
def makeMove(board, chests, x, y):
# Change the board data structure with a sonar device character. Remove treasure chests
# from the chests list as they are found. Return False if this is an invalid move.
# Otherwise, return the string of the result of this move.
if not isValidMove(x, y):
return False
smallestDistance = 100 # any chest will be closer than 100.
for cx, cy in chests:
if abs(cx - x) > abs(cy - y):
distance = abs(cx - x)
else:
distance = abs(cy - y)
if distance < smallestDistance: # we want the closest treasure chest.
smallestDistance = distance
if smallestDistance == 0:
# xy is directly on a treasure chest!
chests.remove([x, y])
return 'You have found a sunken treasure chest!'
else:
if smallestDistance < 10:
board[x][y] = str(smallestDistance)
return 'Treasure detected at a distance of %s from the sonar device.' % (smallestDistance)
else:
board[x][y] = 'O'
return 'Sonar did not detect anything. All treasure chests out of range.'
def enterPlayerMove():
#Let the player type in her move. Return a two-item list of int xy coordinates
print('Where do you want to drop the next sonar device? (0-59 0-14) (or type quit)')
while True:
move=raw_input()
if move.lower()=='quit':
print('Thanks for playing!')
sys.exit()
move=move.split()
if len(move)==2 and move[0].isdigit() and move[1].isdigit() and isValidMove(int(move[0]), int(move[1])):
return [int(move[0]), int(move[1])]
print('Enter a number from 0 to 59, a space, then a number from 0 to 14.')
def playAgain():
#Does the player want to play again
print('Play again? (yes or no)')
return raw_input().lower().startswith('y')
def showInstructions():
print('''Instructions:
You are the captain of teh Simon, a treasure-hunting
ship. Your current mission
is to find the three sunken treasure chests that are
lurking in the part of the
ocean you are in and collect them.
To play, enter the coordinates of teh point in the ocean
you wish to drop a
sonar device. The sonar can find out how far away the
closest chest is to it.
For example, teh d below marks where the device was
dropped, and the 2's
represent distances of 2 away from teh device. The 4's
represent
distances of 4 away from teh device
444444444
4 4
4 22222 4
4 2 2 4
4 2 d 2 4
4 2 2 4
4 22222 4
4 4
444444444
Press enter to continue...''')
raw_input()
print('''For example, here is a treasure chest (the
c) located a distance of 2 away
from teh sonar device (the d):
22222
c 2
2 d 2
2 2
22222
The point where the device was dropped will be barked
with a 2.
The treasure chests don't move around. Sonar devices can
detect treasure
chests up to a distance of 9. If all chests are out of
range, the point
will be marked with O
If a device is directly dropped on a treasure chest, you have discovered
the location of the chest, and it will be collected. The
sonar device will
remain there.
When you collect a chest, all sonar devices will update
to locate the next
closest sunken treasure chest.
Press enter to continue...''')
raw_input()
print ('S O N A R !')
print('Would you like to view the instructions?(yes / no)')
if raw_input().lower().startswith('y'):
showInstructions()
while True:
#game setup
sonarDevices=16
theBoard=getNewBoard()
theChests=getRandomChests(3)
drawBoard(theBoard)
previousMoves=[]
while sonarDevices>0:
#Start of a turn:
#show sonar device/chest status
if sonarDevices>1: extraSsonar='s'
else: extraSsonar=''
if len(theChests)>1: extraSchest='s'
else: extraSchest=''
print('You have %s sonar device%s left. %s treasure chest%s remaining.'%(sonarDevices, extraSsonar, len(theChests), extraSchest))
x, y=enterPlayerMove()
previousMoves.append([x, y]) #We must track all moves so that sonar devices can be updated
moveResult=makeMove(theBoard, theChests, x, y)
if moveResult==False:
continue
else:
if moveResult=='You have found a sunken treasure chest!':
#update all the sonar devices currently on the map
for x, y in previousMoves:
makeMove(theBoard, theChests, x, y)
drawBoard(theBoard)
print(moveResult)
if len(theChests)==0:
print('You have found all the sunken treasure chests! congratulations and good game!')
break
sonarDevices-=1
if sonarDevices==0:
print('You coundn\'t find them all... game over')
print(' The remaining chests were here:')
for x, y in theChests:
print(' %s, %s'%(x, y))
if not playAgain():
sys.exit()
It's ok to be jelly.
Wednesday, October 23, 2013
Subscribe to:
Comments (Atom)



