ANI Coding Competition — Challenge 2
Our second challenge is here! You could win £50!
This week, we have code for a game of Battleships! Like last week there are errors in the code. If you can identify any line of code which contains an error, then click the link at the bottom of the page for a chance to win £50! Fill out the form and, if you correct an erroneous line of code, you'll be added to or prize draw. Three winners will be drawn next Monday, could you be one of them?
1 from random import randint
2 #initializing board
3 board = []
4 for x in range(5):
5 board.append(["O"] * 5)
6 def print_board(board):
7 for row in board:
8 print " ".join(row)
9 #starting the game and printing the board
10 print "Let's play Battleship!"
11 print_board(board)
12 #defining where the ship is
13 def random_row(board):
14 return randint(0, len(board) - 1)
15 def random_col(board):
16 return randint(0, len(board) - 1)
17 ship_row = random_row(board)
18 ship_col = random_col(board)
19 #asking the user for a guess
20 for turn in range(4):
21 guess_row = int(raw_input("Guess Row:"))
22 guess_col = int(raw_input("Guess Col:"))
23 # if the user's right, the game ends
24 if guess_row == ship_row and guess_col == ship_col:
25 print "Congratulations! You sunk my battleship!"
26 break
27 else:
28 #warning if the guess is out of the board
29 if (guess_row > 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4):
30 print "Oops, that's not even in the ocean."
31 #warning if the guess was already made
32 elif(board[guess_row][guess_col] == "X"):
33 print "You guessed that one already."
34 #if the guess is wrong, mark the point with an X and start again
35 else:
36 print "You missed my battleship!"
37 board[guess_row][guess_col] = "X"
38 # Print turn and board again here
39 print "Turn " + str(turn+1) + " out of 4."
40 print_board(board)
41 #if the user have made 4 tries, it's game over
42 if turn >= 3:
43 print "Game Over"
Enter to win here