Real World Examples
This is a revision of everything we have done so far. This unit will have two programs on two different themes. The aim is to understand them by doing a read through. Relevant comments will be provided but no further explanation. This is to make sure that we are on the right track.
NOTE: The comments are written in a way that can guide someone who is attempting this code. If you are enthusiastic enough, you can not read the implementation and try it yourself.
Program #1 - Battleship
As described by Wikipedia, Battleship (also Battleships or Sea Battle) is a guessing game for two players. It is played on ruled grids (paper or board) on which the players' fleets of ships (including battleships) are marked. The locations of the fleet are concealed from the other player. Players alternate turns calling "shots" at the other player's ships, and the objective of the game is to destroy the opposing player's fleet.
Following is the code for it, which you can paste on your Repl window (white screen) and run to test out!
from random import randint
#empty board list
board = []
#the next few lines generate an empty board
for x in range(5):
board.append(["O"] * 5)
#the next few lines draws the board on the console
def print_board(board):
for row in board:
print (" ".join(row))
print ("Let's play Battleship!")
print_board(board)
#the next few lines hide the ship in the board!
def random_row(board):
return randint(0, len(board) - 1)
def random_col(board):
return randint(0, len(board) - 1)
ship_row = random_row(board)
ship_col = random_col(board)
#you may comment the next two lines while playing as they display the location of the ship
#print (ship_row)
#print (ship_col)
# Everything from here on should go in your for loop!
# Be sure to indent!
history = []
def guess(row,col):
if(row == ship_row and col == ship_col):
return 'correct'
elif(row > 4 or col > 4 or row < 0 or col < 0):
return 'outside_board'
elif [row, col] in history:
return 'already_guessed'
for turn in range(4):
guess_row = int(input("Guess Row(0-4):"))
guess_col = int(input("Guess Col(0-4):"))
#checks if guess is correct
if guess(guess_row, guess_col) is 'correct':
print ("Congratulation s! You sunk my battleship!")
break
#checks if guess is outside the board
elif guess(guess_row, guess_col) is 'outside_board':
print ("Oops, that's not even in the ocean.")
#checks if guess has already been guessed
elif guess(guess_row, guess_col) is 'already_guessed':
print ("You guessed that one already.")
else:
print ("You missed my battleship!")
history.append([guess_row,guess_col])
board[guess_row][guess_col] = "X"
print_board(board)
#ends game
if turn == 3:
print ("Game Over")
Program #2 - Tic Tac Toe
Wikipedia describes it as: Tic-tac-toe (also known as noughts and crosses or Xs and Os) is a paper-and-pencil game for two players, X and O, who take turns marking the spaces in a 3×3 grid. The player who succeeds in placing three of their marks in a horizontal, vertical, or diagonal row wins the game.
Here is the code for it. As mentioned above, paste this on your Repl window (white part) and run it:
def drawBoard(board):
# This function prints out the board that it was passed.
# "board" is a list of 10 strings representing the board (ignore index 0)
print(' | |')
print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])
print(' | |')
def winner(board, player):
#this function returns true if a player has three in a row, horizontally, vertically or diagonally
#else, return false
#hint, use boolean operators (“==”, “and”, “or”)
if(board[1] == player and board[2] == player and board[3] == player ):
return True
elif(board[4] == player and board[5] == player and board[6] == player):
return True
elif(board[7] == player and board[8] == player and board[9] == player):
return True
elif(board[1] == player and board[4] == player and board[7] == player):
return True
elif(board[3] == player and board[6] == player and board[9] == player):
return True
elif(board[2] == player and board[5] == player and board[8] == player):
return True
elif(board[1] == player and board[5] == player and board[9] == player):
return True
elif(board[3] == player and board[5] == player and board[7] == player):
return True
else:
return False
play = True #starts the game loop
while play:
#resets the board
theBoard = [' '] * 10
valid_moves = ['1','2','3','4','5','6','7','8','9']
labels = ['0','1','2','3','4','5','6','7','8','9']
print("Welcome to Tic Tac Toe! Player 1 goes first.")
#initialize necessary variables
drawBoard(labels)
player = 1
game = True
while game:
# :take in user input
player_input = input("Input your move: ")
#check if the move is valid
if player_input in valid_moves:
# : Mark the board with the necessary mark (“X” or “O”)
if player == 1:
#
#add the move onto the board
#remove player_input from list of valid_moves
#check if player has won
valid_moves.remove(player_input)
theBoard[int(player_input)]='O'
player = 2
if winner(theBoard, "O"):
# : What happens when a player wins?
print('Player 1 wins!')
drawBoard(theBoard)
break
else:
print('Player 2\'s turn!')
else:
# : repeat similar steps from player 1 for player 2
valid_moves.remove(player_input)
theBoard[int(player_input)]="X"
player = 1
if winner(theBoard, "X"):
# : What happens when a player wins?
print('Player 2 wins!')
drawBoard(theBoard)
break
else:
print('Player 1\'s turn !')
#print the board to the console
drawBoard(theBoard)
else:
print("Invalid input. Try again")
#Should end game if someone won or there are not more valid moves
#after game over, ask if players want to play again
if(len(valid_moves)==0):
print("Draw!")
game = False
if (input("play again? y/n") == "n"):
play = False
print("Thanks for playing!")
If you are here already, then it means that you have sucessfully finished learning the basics of Programming in Python and are able to learn from looking at a code.