Imagine i have the following problem.Write a program to play the following simple game. The player starts with $100. On each
turn a coin is flipped and the player has to guess heads or tails. The player wins $9 for each
correct guess and loses $10 for each incorrect guess. The game ends either when the player
runs out of money or gets to $200.
I have already solved the problem by using a while loop and some if and else statements. I will post the code. When i use if and else my program prints p1_points and p2_points.
import random
coin = ['h','t']
def cpu_guess():
return random.choice(coin)
def player1_guess():
return input('Digit your choice player 1\n')
def player2_guess():
return input('Digit your choice player 2\n')
def guessing_game():
p1_points = 100 #each player starts with 100$
p2_points = 100 #each player starts with 100$
while (0 < p1_points <= 200) or (0 < p2_points < 200):
cpu_choice = cpu_guess()
print(cpu_choice)
player1_choice = player2_guess()
player2_choice = player2_guess()
if player1_choice == cpu_choice:
p1_points += 45
print(p1_points)
else:
p1_points = p1_points - 45
print(p1_points)
if player2_choice == cpu_choice:
p2_points += 45
print(p2_points)
else:
p2_points = p2_points - 45
print(p2_points)
if p1_points > p2_points:
print('Player 1 won the game (',p1_points,'-',p2_points,')')
elif p2_points > p1_points:
print('Player 2 won the game (', p2_points, '-', p1_points, ')')
else:
print('Even game (',p1_points,'-',p2_points,')')
return p1_points,p2_points
print(guessing_game())
However imagine i want to put the following code.
if player1_choice == cpu_choice:
p1_points += 45
print(p1_points)
elif player_choice != cpu_choice
p1_points = p1_points - 45
print(p1_points)
elif player2_choice == cpu_choice:
p2_points += 45
print(p2_points)
else:
p2_points = p2_points - 45
print(p2_points)
In this situation why are only the player 1 points printed and not the player 2 points aswell?
It sounds like you want two separate if/else blocks:
if player1_choice == cpu_choice:
p1_points += 45
else:
p1_points -= 45
print(p1_points)
if player2_choice == cpu_choice:
p2_points += 45
else:
p2_points -= 45
print(p2_points)
Related
import random
player_health = 100
boss_health = 80
guard1_health = 10
guard1_status = "alive"
guard2_health = 15
gladiator_health = 20
weapon = 0
level = 0
turn = 0
def choose_weapon():
global weapon
global level
weapon = int(input("Choose your weapon:\n 1: Sword \n 2: Daggers \n 3: Bow \n Type here to choose:"
"\n--------------------------"))
if weapon == 1:
weapon = str("Sword")
print("You have chosen", weapon)
elif weapon == 2:
weapon = str("Daggers")
print("You have chosen", weapon)
else:
weapon = str("Bow")
print("You have chosen", weapon)
level += 1
choose_weapon()
def level_1_enemy():
global guard1_status
global guard1_health
global level
global turn
global weapon
print("Player turn")
if guard1_status == "alive" and guard1_health > 0 and turn == 1:
print("test")
if weapon == 1:
guard1_health -= 8
print("Guard health:", guard1_health)
turn -= 1
elif weapon == 2:
guard1_health -= 5
print("Guard health:", guard1_health)
turn -= 1
elif weapon == 3:
bow_crit = random.randint(1, 10)
if bow_crit == 1:
guard1_health -= 20
print("Guard health:", guard1_health)
else:
guard1_health -= 5
print("Guard health:", guard1_health)
if guard1_health <= 0:
print("You defeated the Guard, next level!")
guard1_status = "dead"
level += 1
return
def level_1_player():
global player_health
global weapon
global level
global turn
if player_health > 0 and turn == 0:
if weapon == 2:
dodge = random.randint(1, 3)
if dodge == 1:
print("You dodged the attack!")
return
else:
player_health -= 5
print("\n\nThe enemy hit you! (-5 hp)")
print("Enemy health: ", guard1_health)
print("Your health: ", player_health)
return
else:
player_health -= 5
print("\n\nThe enemy hit you! (-5 hp)")
print("Enemy health: ", guard1_health)
print("Your health: ", player_health)
return
print("You have died, Game Over.")
return
while level == 1:
if turn == 0:
level_1_player()
turn += 1
elif turn == 1:
level_1_enemy()
turn -= 1
I want to have the game loop through player and enemy turns until either the player is dead or the enemy. It reaches the first IF in level_1_enemy and prints "test", but does not continue to the next if statement even though the condition "weapon == 1" is true.
The last while loop is meant to repeat the level_1_enemy and level_1_player functions. It does do both but will also not stop looping once the guard or player is dead.
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
im just working on a blackjack project and im new to coding so its a little tough trying to add new functions such as the hit/stand function. I have tried making a hit/stand function but im not sure how to actually add a new card to the total of the players cards and the dealer also. im just staring by adding the players to try and get some result but a am just stuck at this rate and have no idea how i can properly implement this. I have a sep file that stores the list of the deck and shuffle but is imported
import playing_cards
import random
player_hand = []
dealers_hand = []
hands = [[]]
#STAGE 1 - testing purpose only
# Testing code for step 1
##card = playing_cards.deal_one_card()
##print(card)
#Stage 2 - testing purpose only (PLAYERS HAND)
# Deal first card
card = playing_cards.deal_one_card()
# Append it to the player_hand list
player_hand.append(card)
# Deal second card
card = playing_cards.deal_one_card()
# Append it to the player_hand list
player_hand.append(card)
#ADDING UP BOTH CARDS
# Display the player's hand to the screen using a simple print statement
#print("Player's hand is ", player_hand)
#Stage 4 and 5
suits = {'C': 'Club', 'H': 'Heart', 'D': 'Diamond', 'S': 'Spade'}
names = {'2': '2', '3': '3', '4': '4',
'5':'5', '6': '6', '7': '7', '8': '8', '9': '9', 'T': '10','J': 'Jack', 'Q': 'Queen', 'K': 'King', 'A': 'Ace'}
def score_hand(player_hand):
" Scores hand with adjustment for Ace "
value = {}
for i in range(10):
value[str(i)] = i
value['J'] = 10
value['Q'] = 10
value['K'] = 10
value['A'] = 11
value['T'] = 10
score = sum(int(value[card[0]]) for card in player_hand)
if score > 21:
# Adjust for Aces
adjustment = sum(10 if card[0]=='A' else 0 for card in player_hand)
score -= adjustment
return score
#ask about this
def show_result(player_hand):
player_score = int(score_hand(player_hand))
if player_score > 21:
print('*** Player Bust! ***')
elif player_score == 21:
print('*** Blackjack! Player Wins! ***')
##else:
## push(player_hand,dealer_hand)
##def push(player_score,dealers_score):
## print("Dealer and Player tie! It's a push.")
##else:
## // Logic to continue game
def hit_stand(show_hand,player_hand):
while True:
x = input("Would you like to Hit or Stand? Enter 'h' or 's'")
if x[0].lower() == 'h':
hit(show_hand,player_hand) # hit() function defined above
elif x[0].lower() == 's':
print("Player stands. Dealer is playing.")
playing = False
def show_hand(player_hand):
score_hand(player_hand)
score = f"Player's hand is {score_hand(player_hand)}: "
cards = ' | '.join([f"{names[card[0]]} of {suits[card[1]]}" for card in player_hand])
return score + cards
for hand in hands:
print(show_hand(player_hand))
show_result(player_hand)
#Stage 3 - Testing purpose only (DEALERS HAND)
### Deal first card
card = playing_cards.deal_one_card()
### Append it to the player_hand list
dealers_hand.append(card)
### Deal second card
card = playing_cards.deal_one_card()
### Append it to the player_hand list
dealers_hand.append(card)
### Display the player's hand to the screen using a simple print statement
#Stage 4 and 5
def score_hand(dealers_hand):
" Scores hand with adjustment for Ace "
value = {}
for i in range(10):
value[str(i)] = i
value['J'] = 10
value['Q'] = 10
value['K'] = 10
value['A'] = 11
value['T'] = 10
score = sum(int(value[card[0]]) for card in dealers_hand)
if score > 21:
# Adjust for Aces
adjustment = sum(10 if card[0]=='A' else 0 for card in dealers_hand)
score -= adjustment
return score
#ask about this
def show_result(dealers_hand):
dealers_score = int(score_hand(dealers_hand))
if dealers_score > 21:
print('*** Dealer Bust! ***')
elif dealers_score == 21:
print('*** Blackjack! Dealer Wins! ***')
def show_hand(dealers_hand):
score = f"Dealers's hand is {score_hand(dealers_hand)}: "
cards = ' | '.join([f"{names[card[0]]} of {suits[card[1]]}" for card in dealers_hand])
return score + cards
for hand in hands:
print(show_hand(dealers_hand))
print('')
show_result(dealers_hand)
hit_stand(show_hand, player_hand)
import random
Dealer_Cards=[]
Player_Cards=[] # im also beginner in programming just little know some C from College
Total_Player=0 # and watched some tutorial like 5 min and get the whole algorithm
# then start thinking and coding i have little excuse like how to i
Total_Dealer=0 # stop when player or dealer hit >=21 expect option .
#Deal the cards
#Dealer Cards
while len(Dealer_Cards) != 2:
Dealer_Cards.append(random.randint(1,11))
if len(Dealer_Cards) == 2:
print("Dealer has ",Dealer_Cards)
# Player Cards
while len(Player_Cards) != 2:
Player_Cards.append(random.randint(1,11))
if len(Player_Cards) == 2:
print("You have ",Player_Cards)
print("you have 2 option Hit or Stay:[Click '1' for Hit and if you want to Stay click '0']:")
option= int(input(""))
if option == 0:
Total_Dealer+= sum(Dealer_Cards) #Dealer_Cards= i
print("sum of the Dealer cards:",Total_Dealer)
Total_Player+= sum(Player_Cards) # Player_Cards= x
print("sum of the Player cards:",Total_Player)
if Total_Dealer > Total_Player:
print("Dealer Wons")
break
elif Total_Player > Total_Dealer:
print("You Won")
break
else:
print("Scoreless.")
break
elif option == 1:
while len(Player_Cards) != 3:
Player_Cards.append(random.randint(1,11))
Dealer_Cards.append(random.randint(1,11))
if len(Player_Cards) == 3:
print("You have ",Player_Cards)
print("you have 2 option Hit or Stay:[Click '1' for Stay and if you want to Stay click '0']")
option= int(input(""))
if option== 0:
Total_Dealer += sum(Dealer_Cards)
print("sum of the Dealer cards:", Total_Dealer)
Total_Player += sum(Player_Cards)
print("sum of the Player cards:", Total_Player)
if Total_Player > 21 and Total_Dealer <= 21:
print("You are BUSTED !")
break
elif Total_Player == Total_Dealer:
print("Scoreless")
break
elif Total_Player <= 21 and Total_Dealer > 21:
print("You WON !")
break
elif (Total_Player < 21 and Total_Dealer < 21) and (Total_Player > Total_Dealer):
print("You WON !")
elif (Total_Player < 21 and Total_Dealer < 21) and (Total_Dealer > Total_Player):
print("Dealer WON !")
break
elif option == 1:
while len(Player_Cards) != 4:
Player_Cards.append(random.randint(1,11))
Dealer_Cards.append(random.randint(1,11))
if len(Player_Cards) == 4:
print("You have ",Player_Cards)
print("you have 2 option Hit or Stay:[Click '1' for Stay and if you want to Stay click '0']")
option= int(input(""))
if option == 0:
Total_Dealer += sum(Dealer_Cards)
print("sum of the Dealer cards:", Total_Dealer)
Total_Player += sum(Player_Cards)
print("sum of the Player cards:", Total_Player)
if Total_Player > 21 and Total_Dealer <= 21:
print("You are BUSTED !")
break
elif Total_Player == Total_Dealer:
print("Scoreless")
break
elif Total_Player <= 21 and Total_Dealer > 21:
print("You WON !")
break
elif (Total_Player < 21 and Total_Dealer < 21) and (Total_Player > Total_Dealer):
print("You WON !")
break
elif (Total_Player < 21 and Total_Dealer < 21) and (Total_Dealer > Total_Player):
print("Dealer WON !")
break
elif option == 1:
while len(Player_Cards) != 5:
Player_Cards.append(random.randint(1, 11))
Dealer_Cards.append(random.randint(1,11))
if len(Player_Cards) == 5:
print("You have ",Player_Cards)
Total_Dealer+= sum(Dealer_Cards)
print("sum of the Dealer cards:",Total_Dealer)
Total_Player+= sum(Player_Cards)
print("sum of the Player cards:",Total_Player)
if Total_Player > 21 and Total_Dealer <= 21:
print("You are BUSTED !")
break
elif Total_Player == Total_Dealer:
print("Scoreless")
break
elif Total_Player <= 21 and Total_Dealer > 21:
print("You WON !")
break
elif (Total_Player < 21 and Total_Dealer < 21) and (Total_Player > Total_Dealer):
print("You WON !")
break
elif (Total_Player < 21 and Total_Dealer < 21) and (Total_Dealer > Total_Player):
print("Dealer WON !")
break
Maybe this will get you on the right track (I couldn't find a 'hit' function defined, so you can do all the work right in hit_stand, as follows):
def hit_stand(show_hand,player_hand):
while True:
x = input("Would you like to Hit or Stand? Enter 'h' or 's'")
if x[0].lower() == 'h':
player_hand.append(playing_cards.deal_one_card())
elif x[0].lower() == 's':
print("Player stands. Dealer is playing.")
playing = False
That will solve how the player hits, but I didn't see logic in your code for the dealer to decide to hit or stand, which are based on standard house rules.
I'm having trouble with a list index error, the code may not be the sharpest. But I only know so much about coding in python, but I know enough to code a game.
The code that the function are used in:
#Checks if the move counter is more than 3, if it is, the player gets to decide what he/she wants to do
if Moves != 0:
Do = input('What do you do? Help to see all commands ')
#Tests for if the player wants a magic spell
if Do == 'Magic':
if Moves == 3:
ListToDo = MagicDmg(ListToDo, Moves)
if ListToDo[0] == 'Ice' or 'Fire' or 'Bolt':
Mana = CheckMagicCost1(ListToDo, Mana, Moves)
else:
Moves = Moves - 1
elif Moves == 2:
ListToDo = MagicDmg(ListToDo, Moves)
Mana = CheckMagicCost2(ListToDo, Mana, Moves)
Moves = Moves - 1
else:
ListToDo = MagicDmg(ListToDo, Moves)
Mana = CheckMagicCost3(ListToDo, Mana, Moves)
Moves = Moves - 1
#This function does not handle damage
def MagicDmg(ListToDo, Moves):
print('Which magic? Ice, Fire or Bolt')
MagicDo = input()
if MagicDo != 'Ice' or 'Fire' or 'Bolt':
if MagicDo == 'Ice':
ListToDo.append('Ice')
elif MagicDo == 'Fire':
ListToDo.append('Fire')
elif MagicDo == 'Bolt':
ListToDo.append('Bolt')
else:
LIstToDo.remove(MagicDo)
print('That is not a valid spell')
Moves = Moves + 1
return(ListToDo)
#Subtracts the mana cost of spells from mana
def CheckMagicCost1(ListToDo, Mana, Moves):
if ListToDo[0] and Mana >= 10 == 'Ice':
Mana = Mana - 10
elif ListToDo[0] and Mana >= 15 == 'Fire':
Mana = Mana - 15
elif ListToDo[0] and Mana >= 25 == 'Bolt':
Mana = Mana - 25
else:
print('You do not have enough Mana')
Moves = Moves + 1
return(Mana)
def CheckMagicCost2(ListToDo, Mana, Moves):
if ListToDo[1] and Mana >= 10 == 'Ice':
Mana = Mana - 10
elif ListToDo[1] and Mana >= 15 == 'Fire':
Mana = Mana - 15
elif ListToDo[1] and Mana >= 25 == 'Bolt':
Mana = Mana - 25
else:
print('You do not have enough Mana')
Moves = Moves + 1
return(Mana)
def CheckMagicCost3(ListToDo, Mana, Moves):
if ListToDo[2] and Mana > 9 == 'Ice':
Mana = Mana - 10
elif ListToDo[2] and Mana > 14 == 'Fire':
Mana = Mana - 15
elif ListToDo[2] and Mana > 24 == 'Bolt':
Mana = Mana - 25
else:
print('You do not have enough Mana')
Moves = Moves + 1
return(Mana)
The result:
A Azure Drake appeared! With 500 HP!
HP = 250 Mana = 250
Moves left: 3
Boss's HP: 500
What do you do? Help to see all commands Magic
Which magic? Ice, Fire or Bolt
i (False spell)
Traceback (most recent call last):
File "D:\Python\Battle Test V2.py", line 186, in <module>
if ListToDo[0] != 'Ice' or 'Fire' or 'Bolt':
IndexError: list index out of range
I can't immediately tell if this is your only problem, but this line will definitely not work.
if MagicDo != 'Ice' or 'Fire' or 'Bolt':
What that really is checking is the following:
if (MagicDo != 'Ice') or ('Fire' != None) or ('Bolt' != None):
A possible fix for this is changing to this:
if MagicDo in(['Ice','Fire','Bolt']):
This will check if MagicDo is one of the three spells you want. Again, I'm not sure if this is your only problem, but it's definitely a problem.
EDIT: I'm also noticing a problem in your CheckMagicCost functions. None of your conditionals will do what you want them to do. for example, the line
if ListToDo[0] and Mana >= 10 == 'Ice':
is really checking the following
if (ListToDo[0] != None) and ((Mana >= 10) == 'Ice'):
I'm guessing what you want is something more like the following:
if ListToDo[0] == 'Ice' and Mana >= 10:
This change should be propagated out to the rest of your conditionals in the CheckMagicCost1, CheckMagicCost2, and CheckMagicCost3 functions.
Without the error code there's not much to go on, but my gut feeling is you are going to run into trouble with these kinds of statements in your functions:
if ListToDo[1]
Might be better to wrap in a try block and catch the IndexError? Just a thought
try:
#code
except IndexError:
#contingency plan
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