Python Battleships Game

I am currently making a simple Battleships game using Python 3, but I can't seem to get the board to display. Here is my code;

# Battleships

def main():
    pass

if __name__ == '__main__':
    main()

from random import randint

# this initialises the board
board = []

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

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

# this starts the game and prints the board
    print ("Let's play Battleship!")
    print_board(board)

# defines the location of the ship
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)

# asks the player to make a guess
for turn in range(5):
    guess_row = int(input("Guess Row:"))
    guess_col = int(input("Guess Col:"))

# if the player guesses correctly, then the game ends cleanly
if guess_row == ship_row and guess_col == ship_col:
    print ("Congratulations! You sunk my battleship!")

else:
# if the player guesses outside the board, then the following message appears
    if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4):
        print ("Oh dear, you've hit an island!")

# a warning if the guess has already been made by the player
    elif(board[guess_row][guess_col] == "X"):
        print ("That guess has already been made.")

# if the guess is wrong, then the relevant board place is marked with an X
    else:
        print ("You've missed my battleship!")
        board[guess_row][guess_col] = "X"

# prints the turn and updates the board accordingly
    print ("Turn " + str(turn+1) + " out of 5.")
    print_board(board)

# if the user has had 5 guesses, it's game over
if turn >= 3:
    print ("You sunk my battleship! We're gonna need a bigger boat.")

The game accepts the co-ordinates, but doesn't print anything to do with the board or if the player makes a repeated guess or one that's outside the field of play.

Any help would be much appreciated!

Upvotes: 0

Views: 869

Answers (3)

Nep Nep
Nep Nep

Reputation: 1

import random from datetime import date grid = []

def createGrid(): global grid grid = [] for i in range(0,10): grid.append([]) for j in range(0,10): grid[i].append("W") def renderGrid(): global grid for i in range(0,10): for j in range(0,10): block = grid[i][j] if block == "s": block = "W" print(block,end=" ") print() print()

def placeGrid():

xsize = 10
ysize = 10
shipBlocks = 17 
length = 2 
submarineException = True
while shipBlocks > 0: 
    x = random.randint(0,xsize-1) 
    y = random.randint(0,ysize-1)
    value = 1
    cx = 0 
    cy = 0 
    if random.randint(0,1) == 1:
        value = -value
    if random.randint(0,1) == 1:
        cx = value
    else:
        cy = value
    broken = False
    for b in range(0,length):
        xpos = x+cx*b 
        ypos = y+cy*b
        if xpos<0 or xpos>xsize-1 or ypos<0 or ypos>ysize-1: broken = True 

    if broken: continue
    for b in range(0,length):
        grid[x+cx*b][y+cy*b] = "s"
    shipBlocks = shipBlocks - length
    if length == 3:
        if submarineException:
            submarineException = False
        else:
            length+=1
    else:
        length+=1

def runGame():

name = input("Enter your username: ")
global grid 
createGrid() 
placeGrid() 
hits = 0 
while True:
    won = True
    for row in grid:
        for character in row:
            if character == "s":
                won = False
    if won:
        print("You have won the game in "+str(hits)+" hits!")        
    renderGrid()
    y = input("Hit X: ")
    x = input("Hit Y: ")
    try:
        x = int(x)-1
        y = int(y)-1 
        if x < 0 or y < 0:
            raise
        if grid[x][y] == "s": 
            grid[x][y] = "S" 
            print("Ship hit.")
        elif grid[x][y] == "S": 
            print("You already hit here.")
            continue
        hits+=1
    except Exception as e:
        print("Error, number from 1 to 10 please.")
        #stackoverflow saves lives

runGame()

Upvotes: 0

PeterGenius
PeterGenius

Reputation: 1

You are iterating over the loop THEN all the if statements. Put all the if statements inside the for loop. Add a counter saying if you hit my ship add one point (score += 1) then

if score >= 3:
    print ("You sunk my battleship! We're gonna need a bigger boat.")

Upvotes: 0

Scott Hunter
Scott Hunter

Reputation: 49920

Your code asks for 5 sets of guesses before it does anything with them, because the code to respond to a guess is outside of the loop asking for the guesses. I'm, ahem, guessing that in your testing you never entered enough guesses to get past that loop. Move the guess-processing code into the loop, and you should at least see reactions to those guesses.

Upvotes: 2

Related Questions