About restart ,how should i do


#1

how to restart the game


#!/usr/bin/env python
# encoding: utf-8

from random import randint

board = []

for x in range(5):
    board.append(["O"] * 5)

def print_board(board):
    for item in board:
        print " ".join(item)

def random_row(board):
    return randint(0, len(board) - 1)

def random_col(board):
    return randint(0, len(board[0]) - 1)

ship_row = random_row(board)
ship_col = random_col(board)

print ship_row
print ship_col

def game():
    for turn in range(3):
        print "Turn", turn + 1
        for user in range(2):
            print "User", user + 1
            guess_row = int(raw_input("Guess row: "))
            guess_col = int(raw_input("Guess col: "))
            if guess_row == ship_row and guess_col == ship_col:
                print "Good job! You hit it!"
                return
            elif guess_row not in range(5) or \
                guess_col not in range(5):
                print "Bad shoot!"
            elif board[guess_row][guess_col] == "X":
                print "You already hit that place!"
            else:
                print "Miss!"
                board[guess_row][guess_col] = "X"
                print_board(board)
        if turn == 2:
            print "Game Over!"  

game()


#2

Hello

I figured this out so far,

Enter at the bottom line at the for range section.

playAgain = "y"

Add the bottom lines after print_board sections.

playAgain = raw_input("Would you like to play again? (y/n)")
print str("Thanks for playing!")

Need to figure out how to let it only apply at the end of game and what happens when you enter 'n' for No.

If you get there first will you share with me?

Hope that little bit helps. Thanks for the challenge.


#3

Hello

I think this is where we need to use a loop. I have not done loops in python yet. But the limited knowledge I have, I think you need to use a 'while' loop, to reset.

I am sure others who have done this can offer more insights to your questions. The bit I gave you I figured out by myself but my knowledge is limited regarding loops.

Good luck.
Hope that helps.


#4

python unfortunately doesn't have a do while loop, but you could do something like:

playAgain = True
while play_again:
   // game code
playAgain = raw_input("Would you like to play again? (y/n)")
if playAgain == "n":
    playAgain = False

while loops are covered at this poin in the course, right?


#5

Awesome. Thanks.
Loops is covered after the Battleship lessons.
About to start it. Did not know that the restart question fell within the 'loop' lessons.:grin:
Now we know. Thanks again!!


#6

2 posts were split to a new topic: If/loop question


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.