Okay I'm not sure how to develop another board with hidden spaces for the computers ships per-se, and have it test for hits. Again I'm not even sure how I'm going to test for hits on the board I have now. Make note: The player turn function will be migrated to the computer board since you wouldn't be attacking your own ships. Here is the code. It may not be the best formatting (as in with Methods and objects and such) but I can polish it up a little later. Also would there be another way to make placing the ships all in one function? Or with the way I have it, will it have to stay that way?
class battleship(object):
def __init__(self):
self.board = [["O"] * 10, ["O"] * 10, ["O"] * 10, ["O"] * 10, ["O"] * 10, ["O"] * 10, ["O"] * 10, ["O"] * 10, ["O"] * 10, ["O"] * 10, ]
self.printboard()
self.placeAircraftCarrier()
self.placeBattleShip()
self.placeSubmarine()
self.placeDestroyer()
self.placePatrolBoat()
for i in range(100):
self.playerTurn()
def printboard(self):
print "Game Board\n"
print "1","2","3","4","5","6","7","8","9","10"
for row in self.board:
print "|".join(row)
def placeBattleShip(self):
while True:
self.vOrHPlacement = input("Would you like to place the Battleship (1) Vertically or (2)Horizontally?:")
if self.vOrHPlacement == 1 or self.vOrHPlacement == 2:
break
else:
print "You must press 1 or 2."
while True:
self.battleshipRow = input("With the head as the starting place what row would you like to place the Battleship (Takes 4 Spaces)?:")
self.battleshipCol = input("What column would you like to start the BattleShip at?:")
if self.vOrHPlacement == 1:
if self.battleshipRow > 7 or self.battleshipRow <= 0:
print "\nIf placing vertically you can only choose 1-7 for the row."
elif self.battleshipCol <= 0 or self.battleshipCol > 10:
print "You must choose 1 - 10 for a column."
elif self.board[self.battleshipRow - 1][self.battleshipCol - 1] == "X":
print "There is already a ship there."
else:
self.battleshipRow -= 2
self.battleshipCol -= 1
for i in range(4):
self.board[self.battleshipRow + 1][self.battleshipCol] = "X"
self.battleshipRow += 1
break
elif self.vOrHPlacement == 2:
if self.battleshipCol > 7 or self.battleshipCol <= 0:
print "\nIf placing horizontally you can only choose 1-7 for a column."
elif self.battleshipRow <= 0 or self.battleshipRow > 10:
print "\n You must choose 1 - 10 as a row choice."
elif self.board[self.battleshipRow - 1][self.battleshipCol - 1] == "X":
print "There is already a ship there."
else:
self.battleshipRow -= 1
self.battleshipCol -= 2
for i in range(4):
self.board[self.battleshipRow][self.battleshipCol + 1] = "X"
self.battleshipCol += 1
break
self.printboard()
def placeAircraftCarrier(self):
while True:
self.vOrHPlacement = input("Would you like to place the Aircraft Carrier (1) Vertically or (2)Horizontally?:")
if self.vOrHPlacement == 1 or self.vOrHPlacement == 2:
break
else:
print "You must press 1 or 2."
while True:
self.battleshipRow = input("With the head as the starting place what row would you like to place the Aircraft Carrier (Takes 5 Spaces)?:")
self.battleshipCol = input("What column would you like to start the Aircraft Carrier at?:")
if self.vOrHPlacement == 1:
if self.battleshipRow > 6 or self.battleshipRow <= 0:
print "\nIf placing vertically you can only choose 1-6 for the row."
elif self.battleshipCol <= 0 or self.battleshipCol > 10:
print "You must choose 1 - 10 for a column."
elif self.board[self.battleshipRow - 1][self.battleshipCol - 1] == "X":
print "There is already a ship there."
else:
self.battleshipRow -= 2
self.battleshipCol -= 1
for i in range(5):
self.board[self.battleshipRow + 1][self.battleshipCol] = "X"
self.battleshipRow += 1
break
elif self.vOrHPlacement == 2:
if self.battleshipCol > 6 or self.battleshipCol <= 0:
print "\nIf placing horizontally you can only choose 1-6 for a column."
elif self.battleshipRow <= 0 or self.battleshipRow > 10:
print "\n You must choose 1 - 10 as a row choice."
elif self.board[self.battleshipRow - 1][self.battleshipCol - 1] == "X":
print "There is already a ship there."
else:
self.battleshipRow -= 1
self.battleshipCol -= 2
for i in range(5):
self.board[self.battleshipRow][self.battleshipCol + 1] = "X"
self.battleshipCol += 1
break
self.printboard()
def placeSubmarine(self):
while True:
self.vOrHPlacement = input("Would you like to place the Submarine (1) Vertically or (2)Horizontally?:")
if self.vOrHPlacement == 1 or self.vOrHPlacement == 2:
break
else:
print "You must press 1 or 2."
while True:
self.battleshipRow = input("With the head as the starting place what row would you like to place the Submarine (Takes 3 Spaces)?:")
self.battleshipCol = input("What column would you like to start the Submarine at?:")
if self.vOrHPlacement == 1:
if self.battleshipRow > 8 or self.battleshipRow <= 0:
print "\nIf placing vertically you can only choose 1-8 for the row."
elif self.battleshipCol <= 0 or self.battleshipCol > 10:
print "You must choose 1 - 10 for a column."
elif self.board[self.battleshipRow - 1][self.battleshipCol - 1] == "X":
print "There is already a ship there."
else:
self.battleshipRow -= 2
self.battleshipCol -= 1
for i in range(3):
self.board[self.battleshipRow + 1][self.battleshipCol] = "X"
self.battleshipRow += 1
break
elif self.vOrHPlacement == 2:
if self.battleshipCol > 8 or self.battleshipCol <= 0:
print "\nIf placing horizontally you can only choose 1-8 for a column."
elif self.battleshipRow <= 0 or self.battleshipRow > 10:
print "\n You must choose 1 - 10 as a row choice."
elif self.board[self.battleshipRow - 1][self.battleshipCol - 1] == "X":
print "There is already a ship there."
else:
self.battleshipRow -= 1
self.battleshipCol -= 2
for i in range(3):
self.board[self.battleshipRow][self.battleshipCol + 1] = "X"
self.battleshipCol += 1
break
self.printboard()
def placeDestroyer(self):
while True:
self.vOrHPlacement = input("Would you like to place the Destroyer (1) Vertically or (2)Horizontally?:")
if self.vOrHPlacement == 1 or self.vOrHPlacement == 2:
break
else:
print "You must press 1 or 2."
while True:
self.battleshipRow = input("With the head as the starting place what row would you like to place the Destroyer (Takes 3 Spaces)?:")
self.battleshipCol = input("What column would you like to start the Destroyer at?:")
if self.vOrHPlacement == 1:
if self.battleshipRow > 8 or self.battleshipRow <= 0:
print "\nIf placing vertically you can only choose 1-8 for the row."
elif self.battleshipCol <= 0 or self.battleshipCol > 10:
print "You must choose 1 - 10 for a column."
elif self.board[self.battleshipRow - 1][self.battleshipCol - 1] == "X":
print "There is already a ship there."
else:
self.battleshipRow -= 2
self.battleshipCol -= 1
for i in range(3):
self.board[self.battleshipRow + 1][self.battleshipCol] = "X"
self.battleshipRow += 1
break
elif self.vOrHPlacement == 2:
if self.battleshipCol > 8 or self.battleshipCol <= 0:
print "\nIf placing horizontally you can only choose 1-8 for a column."
elif self.battleshipRow <= 0 or self.battleshipRow > 10:
print "\n You must choose 1 - 10 as a row choice."
elif self.board[self.battleshipRow - 1][self.battleshipCol - 1] == "X":
print "There is already a ship there."
else:
self.battleshipRow -= 1
self.battleshipCol -= 2
for i in range(3):
self.board[self.battleshipRow][self.battleshipCol + 1] = "X"
self.battleshipCol += 1
break
self.printboard()
def placePatrolBoat(self):
while True:
self.vOrHPlacement = input("Would you like to place the Patrol Boat (1) Vertically or (2)Horizontally?:")
if self.vOrHPlacement == 1 or self.vOrHPlacement == 2:
break
else:
print "You must press 1 or 2."
while True:
self.battleshipRow = input("With the head as the starting place what row would you like to place the Patrol Boat (Takes 2 Spaces)?:")
self.battleshipCol = input("What column would you like to start the Patrol Boat at?:")
if self.vOrHPlacement == 1:
if self.battleshipRow > 9 or self.battleshipRow <= 0:
print "\nIf placing vertically you can only choose 1-9 for the row."
elif self.battleshipCol <= 0 or self.battleshipCol > 10:
print "You must choose 1 - 10 for a column."
elif self.board[self.battleshipRow - 1][self.battleshipCol - 1] == "X":
print "There is already a ship there."
else:
self.battleshipRow -= 2
self.battleshipCol -= 1
for i in range(2):
self.board[self.battleshipRow + 1][self.battleshipCol] = "X"
self.battleshipRow += 1
break
elif self.vOrHPlacement == 2:
if self.battleshipCol > 9 or self.battleshipCol <= 0:
print "\nIf placing horizontally you can only choose 1-9 for a column."
elif self.battleshipRow <= 0 or self.battleshipRow > 10:
print "\n You must choose 1 - 10 as a row choice."
elif self.board[self.battleshipRow - 1][self.battleshipCol - 1] == "X":
print "There is already a ship there."
else:
self.battleshipRow -= 1
self.battleshipCol -= 2
for i in range(2):
self.board[self.battleshipRow][self.battleshipCol + 1] = "X"
self.battleshipCol += 1
break
self.printboard()
def playerTurn(self):
while True:
self.row = input("What row coordinate would you like to hit?:")
self.column = input("What column coordinate would you like to hit?")
if self.row > 10 or self.row < 0:
print "You must pick a row coordinate between 1 and 10."
elif self.column > 10 or self.column < 0:
print "You must pick a column coordinate between 1 and 10."
elif self.board[self.row - 1][self.column - 1] == "*":
print "You have already hit there."
else:
self.board[self.row - 1][self.column - 1] = "*"
break
self.printboard()
b = battleship()
You need a lot of code organisation. I would suggest keeping Classes free from any sort of looping or inputs! Input stuff from the user & then add that to the class instance, not the other way round. Organize your code & add documentation to it so that others can help you.
You can do some stuff like this
class BattleShip:
""" Ship object container"""
def __init__(self, position_x, position_y, size):
""" Necessary variables for the ship go here """
self.position_x = position_x
self.position_y = position_y
self.size = size
def contains(self, position_x, position_y):
""" Returns true if supplied point lies inside this ship """
# code
def destroy(self, position_x, position_y):
""" Destroys the ship's point supplied if it contains it """
assert self.contains(position_x, position_y)
# Now update the gameboard
# code
def isCompletelyDestroyed(self):
""" Returns True if ship is completely destoryed else False """
# code
class GameBoard:
""" The container for the ships """
def __init__(self, size):
"""Initialize clean GameBoard depending on size, etc """
self.occupied = "+" # representation for ships
self.destroyed = 'x' # representation for destroyed area
self.clear = '-' # representation for clear water
def printBoard(self):
""" Print the current gameboard state """
def update(self, ship):
""" Updates the gameboard according to updated ship """
# Now do the mainloop
while game_not_over:
# run game
Related
I have a problem using the while loop. When I am inputting right answer for example, and the second one is wrong, the tryAgain input is showing. If I want to play again, it just looping in from the start and choosing a topic won't work. If I made it wrong, from the start, it will just loop on its own from inputting answers.
tryAgain = True
repeat = True
while tryAgain:
print("TOPICS: \n")
print("1. topic 1")
print("2. topic 2")
print("3. topic 3")
print("======================================")
num = int(input("PICK A NUMBER FOR THE TOPIC [1-3]: "))
if num > 3:
print("There is no given topic")
print("==========================")
tryAgain = True
else:
if num == 1:
reader = WordListCorpusReader('filename', ['textfile'])
with open('filename') as f:
text = [line.strip().upper() for line in f]
answer = []
while lives > 0:
while repeat:
index = 0
while index < 10:
answerlst = input(str(index + 1) + '. ').upper()
if answerlst in text: #condition if the inputted answer is on the file
if answerlst in answer: #check if the inputted answer is on the array
print("\nYou repeated your answer!")
repeat = True
continue
else:
answer.append(answerlst)
print("Correct!")
repeat = False
if answerlst == "ans1":
print("Points: 10")
points += 10
elif answerlst == "ans2":
print("Points: 20")
points += 20
elif answerlst == "ans3":
print("Points: 30")
points += 30
elif answerlst == "ans4":
print("Points: 40")
points += 40
elif answerlst == "ans5":
print("Points: 50")
points += 50
elif answerlst == "ans6":
print("Points: 60")
points += 60
elif answerlst == "ans7":
print("Points: 70")
points += 70
elif answerlst == "ans8":
print("Points: 80")
points += 80
elif answerlst == "ans9":
print("Points: 90")
points += 90
elif answerlst == "ans10":
print("Points: 100")
points += 100
if points == 550:
print("\nCONGRATULATIONS!!!! YOU GOT A PERFECT POINTS OF:", points)
break
else:
if answerlst == "ans1":
points += 10
elif answerlst == "ans2":
points += 20
elif answerlst == "ans":
points += 30
elif answerlst == "ans4":
points += 40
elif answerlst == "ans5":
points += 50
elif answerlst == "ans6":
points += 60
elif answerlst == "ans7":
points += 70
elif answerlst == "ans8":
points += 80
elif answerlst == "ans9":
points += 90
elif answerlst == "ans10":
points += 100
lives -= 1
if lives == 0:
print("\nGAME OVER!!!!!\n")
print("You just got a: ", points)
break
index +=1
playAgain = input("Do you want to play again? [Y] / [N]: ").upper()
if playAgain == 'Y':
answer.clear() #to clear the list
tryAgain = True
I just show the structure of my code in order to understand.
Congratulations, because now you've learned what spaghetti code is - it's just a mess, where you can't properly find errors. When such situation occurs, try to divide your problem into smaller parts (stages). Implement the stages as functions, and your code will become much easier.
For example I tried to rework your program like this. ATTENTION: I don't have your files, so this code probably won't work out of the box, I cannot test it. But just try to read it and understand the approaches.
After reworking this code I noticed that you never set lives to any number, but you should.
def input_topic():
while True:
print("TOPICS: \n")
print("1. topic 1")
print("2. topic 2")
print("3. topic 3")
print("======================================")
topic = int(input("PICK A NUMBER FOR THE TOPIC [1-3]: "))
if topic > 3:
print("There is no given topic")
print("==========================")
else:
return topic
def read_text(filename):
reader = WordListCorpusReader(filename, ['textfile'])
with open(filename) as f:
text = [line.strip().upper() for line in f]
return text
def input_answer_and_check(index, text, already_answered):
while True:
answerlst = input(str(index+1) + '. ').upper()
if answerlst in text:
if answerlst not in answer:
return True, answerlst
else:
print("\nYou repeated your answer!")
else:
return False, answerlst
def get_answer_points(answerlst)
if answerlst == "ans1":
return 10
elif answerlst == "ans2":
return 20
elif answerlst == "ans3":
return 30
elif answerlst == "ans4":
return 40
elif answerlst == "ans5":
return 50
elif answerlst == "ans6":
return 60
elif answerlst == "ans7":
return 70
elif answerlst == "ans8":
return 80
elif answerlst == "ans9":
return 90
elif answerlst == "ans10":
return 100
def ask_try_again():
playAgain = input("Do you want to play again? [Y] / [N]: ").upper()
return playAgain == 'Y'
while True:
topic = input_topic()
text = read_text('filename')
answer = []
lives_left = 5
index = 0
max_index = 10
total_points = 0
while lives_left > 0 and index < max_index and total_points < 550:
is_correct_answer, answerlst = input_answer_and_check(index, text, answer)
answer_points = get_answer_points(answerlst)
total_points += answer_points
if is_correct_answer:
answer.append(answerlst)
print("Correct!")
print(f"Points: {answer_points}")
else:
lives_left -= 1
index += 1
if lives_left == 0:
print("\nGAME OVER!!!!!\n")
print("You just got a: ", total_points)
elif total_points >= 550:
print("\nCONGRATULATIONS!!!! YOU GOT A PERFECT POINTS OF:", total_points)
if not ask_try_again():
break
I apologize if there is a answer to this question on a previous post. I seen a few posts about guessing games but couldn't seem to find how to recall a guess and see if it was closer then the previous one. I'm a complete beginner in python, I want the game to indicate if the first guess is within 10 or not, then say warmer or colder base on the next guesses. Thank you in advance.
from random import randint
win = randint(1,101)
count = 0
while True:
try:
result = int(input('Guess a number between 1 and 100 \n'))
if result > 100 or result < 1:
print('oops, pick between 1 and 100!')
continue
except:
print("oops, that's not a number!")
continue
if result == win:
print(f"YOU WON, it took you {count} guesses")
count += 1
break
else:
if abs(result - win) <= 10:
print("HOT WITHIN 10")
count += 1
continue
elif abs(result - win) > 10:
print("COLD ")
count += 1
continue
# call previous guess
# if abs(win - new_guess) < (previous_guess - win)
# print warmer
# else print colder
Here is some modification on your code to print warmer or colder based on previous guess:
from random import randint
win = randint(1,101)
count = 1
prev_guess = guess = None
while True:
try:
prev_guess = guess
guess = int(input('Guess a number between 1 and 100 \n'))
if guess > 100 or guess < 1:
print('oops, pick between 1 and 100!')
continue
except:
print("oops, that's not a number!")
continue
if guess == win:
print(f"YOU WON, it took you {count} guesses")
count += 1
break
else:
guess_dist = abs(guess - win) # _dist for distance to the win number
print(guess, prev_guess)
if guess_dist <= 10:
if not prev_guess or abs(prev_guess - win) > 10:
print("HOT WITHIN 10")
elif guess_dist < abs(prev_guess - win):
print('warmer')
else:
print('colder')
elif guess_dist > 10:
print("COLD ")
count += 1
continue
I'm trying to write the Camel game using functions instead of so many nested if statements. I think I've done something wrong though, I've had to tinker with the native distance portion a lot as I kept getting into parts where they only got further away not closer. But now after trying to change the randomint values I can never escape them. Any suggestions for improvement are much appreciated!
Here is my code:
import random
def quitGame():
print("I am guitting now.")
return True
def status(milesTraveled, thirst, camelTiredness, distanceNativesTraveled, drinks):
print(
"""
You have traveled %d miles
Your Camel Status is %d (lower is better)
You have %d drinks left in your canteen
Your thirst is %d (lower is better)
The Natives are %d miles behind you
"""%(milesTraveled,camelTiredness,drinks,thirst,distanceNativesTraveled))
def rest():
print("The camel is happy")
distanceN = random.randint(7,14)
return(distanceN)
def fullSpeed():
distanceT = random.randint(10,20)
print("You travel %d miles"%distanceT)
camelT = random.randint(1,3)
distanceN = random.randint(7,14)
return(distanceT,camelT,distanceN)
def moderateSpeed():
distanceB = random.randint(5,12)
print("You travel %d miles"%distanceB)
nativesB = random.randint(7,14)
return(distanceB,nativesB)
def thirsty(drinksLeft):
drinksL = drinksLeft - 1
return(drinksL)
def main():
choice = ""
done = False # loop variable
#variables for game
milesTraveled = 0
thirst = 0
camelTiredness = 0
distanceNativesTraveled = -20
drinks = 5
print(
"""
Welcome to the Camel Game!
You have stolen a camel to make your way across the great Mobi desert.
The natives want their camel back and are chasing you down. Survive your
desert trek and out run the native.
"""
)
while not done:
findOasis = random.randint(1,20)
print(
"""
Here are your choices:
A - Drink from you canteen.
B - Ahead moderate speed.
C - Ahead full speed.
D - Stop and rest for night.
E - Status check.
Q - Quit the Game
"""
)
choice = input(" Your choice?\n")
if choice.upper() == "Q":
done = quitGame()
elif findOasis is 1 :
print("Wow! You've found an Oasis. Your thirst is quenched, canteen topped off, \
and your camel is now well rested and happy.")
drinks = 5
thirst = 0
camelTiredness = 0
elif choice.upper() == "A":
if drinks > 0:
drinks = thirsty(drinks)
thirst = 0
else:
print("Error: Uh oh! No water left.")
elif choice.upper() == "B":
milesB,nativesB = moderateSpeed()
milesTraveled += milesB
camelTiredness += 1
thirst += 1
distanceNativesTraveled += nativesB
elif choice.upper() == "C":
milesT,camelTired,nativesT= fullSpeed()
milesTraveled += milesT
camelTiredness += camelTired
distanceNativesTraveled += nativesT
thirst += 1
elif choice.upper() == "D":
distanceT = rest()
camelTiredness = 0
distanceNativesTraveled += distanceT
elif choice.upper() == "E":
statusCheck = status(milesTraveled, thirst, camelTiredness, distanceNativesTraveled, drinks)
else:
print("That was not a correct choice - Enter (A through E or Q)")
if thirst > 4 and thirst <= 6:
print("You are thirsty")
elif thirst > 6:
print("GAME OVER \nYou died of thirst!")
done = True
elif camelTiredness > 5 and camelTiredness <= 8:
print("Your camel is getting tired")
elif camelTiredness > 8:
print("GAME OVER \nYour camel is dead.")
done = True
elif distanceNativesTraveled >= 0:
print("GAME OVER \nThe natives have captured you!")
done = True
elif distanceNativesTraveled > -15:
print("The natives are getting close!")
elif milesTraveled >= 200:
print("YOU WIN \nCongrats, you made it across the desert!")
done = True
# call main
main()
The game ends when distanceNativesTraveled >= 0 and yet there's no code at all to decrease distanceNativesTraveled. So with every turn distanceNativesTraveled keeping increasing, the game is bound to end quickly.
What you really want here is to check if distanceNativesTraveled has surpassed milesTraveled, so change:
elif distanceNativesTraveled >= 0:
to:
elif distanceNativesTraveled >= milesTraveled:
And for the check to see if natives are getting close, change:
elif distanceNativesTraveled > -15:
to:
elif distanceNativesTraveled - milesTraveled > -15:
And to properly show the how many miles the natives are behind you, you should show the difference between the miles you and the natives traveled, so change:
"""%(milesTraveled,camelTiredness,drinks,thirst,distanceNativesTraveled))
to:
"""%(milesTraveled,camelTiredness,drinks,thirst,milesTraveled - distanceNativesTraveled))
I made a list of functions and want to randomly select one for a trivia game, it keeps printing out the functions of my list.(I already defined functions)
def NBAquestions():
x = 0
question6 = Question("What does the NBA stand for?", "National Basketball Live", "National Fun Live", "National Basketball League",
"Nothin But Liberals", 3)
if question6.ask() == True:
print("You are correct")
x += 1
else:
print("incorrect")
x -= 1
question7 = Question("What team won the championship last year (2016)?", "Golden State Warriors", "Miami Heat", "Minnesota Wild",
"Clevland Caviliers", 1)
if question7.ask() == True:
print("You are correct")
x += 1
else:
print("incorrect")
x -= 1
question8 = Question("What doesn't belong?", "Stephen Curry", "Kevin Durant", "Draymond Green",
"Mitch Marner", 4)
if question8.ask() == True:
print("You are correct")
x += 1
else:
print("incorrect")
x -= 1
question9 = Question("Is the Seattle Supersonics a current NBA team", "True", "False", "-",
"-", 2)
if question9.ask() == True:
print("You are correct")
x += 1
else:
print("incorrect")
x -= 1
question10 = Question("Micheal who?", "Jackson", "Johnson", "Jordan",
"Jarret", 3)
if question10.ask() == True:
print("You are correct")
x += 1
else:
print("incorrect")
x -= 1
print('Welcome to the Sports Trivia Game, you will compete head to head in a tivia matchup. One point will be awarded for getting 1 question right, but if you get 1 wrong you will lose a point')
a = input("please enter player 1's name: ")
b = input("please enter player 2's name: ")
questionList = ([NBAquestions(), MLBquestions(), NHLquestions(), NFLquestions()]
You have to call your function with a random number and use a flag to finish the game.
from random import randint # Generate random integers between 0 and 3
randomNum = (randint(0, 3)) # 0 1 2 3
while True:
if randomNum == 0:
NBAquestions()
elif randomNum == 1:
MLBquestions()
elif randomNum == 2:
NHLquestions()
elif randomNum == 3:
NFLquestions()
# Condition-flag indicate Game Over
# You have to declare your global variable inside your functions
# And when you have to end the game, set it True
global flag
if flag == True:
break
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!
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.
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.")
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()