Vieux garcon game - Problem with execution - python

how would I solve this problem? The program is supposed to remove all pairs from your hand at the beginning but it is not working. This is what it outputs at the moment:
Hello. I am Robot and I distribute the cards.
Your hand is:
2♠ 5♡ Q♠ Q♡ 4♡ J♢ 2♣ J♠ K♢ 8♢ 10♠ A♣ 5♣ 3♣ 6♣ 4♢ 7♣ 9♢ 2♢ J♡ A♢ 8♠ 10♣ 6♢ 10♡
Don't worry, I cannot see your cards or their order.
Now discard all pairs in your hand. I will do it too.
Press Enter to continue.
************************************************************
Your turn.
Your hand is:
9♢ J♡ 3♣ K♢ 10♠ 2♢ 10♣ 10♡ 7♣
There is not supposed to be two 10s in your hand. This is the code:
# vieux garcon card game.
import random
def wait_for_player():
try:
input("Press Enter to continue. ")
except SyntaxError:
pass
def prepare_pack():
pack = []
colors = ['♠', '♡', '♢', '♣']
value = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
for val in value:
for color in colors:
pack.append(val + color)
pack.remove('J♣')
return pack
def shuffle_pack(p):
random.shuffle(p)
def give_cards(p):
giver = []
other = []
loop = 0
for i in p:
if (loop % 2) == 0:
giver.append(i)
else:
other.append(i)
loop += 1
return (giver, other)
def remove_pairs(l):
colors = ['♠', '♡', '♢', '♣']
result = []
for crt in l:
if crt[1] + crt[0] == '10':
nbr = '10'
else:
nbr = crt[0]
for i in colors:
find = False
if nbr + i in result:
find = True
result.remove(nbr + i)
break
if find == False:
result.append(crt)
random.shuffle(result)
return result
def show_cards(p):
for i in p:
print(i, end = " ")
print()
def enter_valid_position(n):
enter = int(input('Please enter a number from 1 to'+ str(n) +": ")) - 1
while enter not in range(0, n):
enter = int(input('Invalid position. Please enter a number from 1 to ' + str(n) +": ")) - 1
return enter
def play():
p = prepare_pack()
shuffle_pack(p)
tmp = give_cards(p)
giver = tmp[0]
human = tmp[1]
print("Hello. I am Robot and I distribute the cards.")
print("Your hand is:")
show_cards(human)
print("Don't worry, I cannot see your cards or their order.")
print(
"Now discard all pairs in your hand. I will do it too."
)
wait_for_player()
giver = remove_pairs(giver)
human = remove_pairs(human)
#Instance = 1, human's turn, instance = 2, robot's turn
instance = 1
while instance in range(1,2):
if instance == 1:
print('*' * 60)
print('Your turn.')
print('Your hand is: ')
show_cards(human)
print("I have ", len(giver), "cards. If 1 is the position of my first card and ")
print(len(giver), "is the position of my last card, which card do you want?")
entry = enter_valid_position(len(giver))
print("You asked for my card number ", entry+1, ".")
print("There it is. It is a ", giver[entry])
print("With ", giver[entry]," added, your hand is:")
human.append(giver[entry])
giver.remove(giver[entry])
show_cards(human)
human=remove_pairs(human)
if len(human) == 0:
print("I finished all the cards.")
win = True
break
print("After discarding all pairs and shuffling the cards, your hand is:")
show_cards(human)
wait_for_player()
instance = 2
pass
if instance == 2:
print('*' * 60)
print('My turn.')
take_card = random.randint(0, len(human) - 1)
giver.append(human[take_card])
human.remove(human[take_card])
print("I took your card number ", take_card+1,".")
giver=remove_pairs(giver)
if len(giver)==0:
print("I finished all the cards.")
win = False
break
wait_for_player()
instance = 1
pass
if win == True:
print("Congratulations! You, Human, have won.")
else:
print("You lost! Me, Robot, have won.")
# main
play()
What should I do? My program does remove pairs later on in the game, but not at the beginning.

I found my error.
for crt in l:
if crt[1] + crt[0] == '10':
nbr = '10'
I flipped the positions of the 1 and 0. it was checking for 01 and not 10. It was supposed to be:
for crt in l:
if crt[0] + crt[1] == '10':
nbr = '10'
Sorry for the inconvience.

Related

Error with a player turn ending loop in the Zombie Dice game

I'm trying to develop a code for the zombie dice game.
My problem is when the first player replies that he doesn't want to continue playing.
The game ends and I can't get the second player to play. Can someone help me?
import random
print("========== ZOMBIE DICE (PROTÓTIPO SEMANA 4) ==========")
print("========= WELCOME TO THE ZOMBIE DICE GAME! ========")
numeroJogadores = 0
while numeroJogadores < 2:
numeroJogadores = int(input("Enter the number of players: "))
print(numeroJogadores)
if numeroJogadores < 2:
print("NOTICE: You must have at least 2 players to continue!")
listaJogadores = []
for i in range(numeroJogadores):
nome = str(input("\nEnter player name: " + str(i+1) + ": "))
listaJogadores.append(nome)
print(listaJogadores)
dadoVerde = ("brain", "steps", "brain", "shot", "steps", "brain")
dadoAmarelo = ("shot", "steps", "brain", "shot", "steps", "brain")
dadoVermelho = ("shot", "steps", "shot", "brain", "steps", "shot")
listaDados = [dadoVerde, dadoVerde, dadoVerde, dadoVerde, dadoVerde, dadoVerde,
dadoAmarelo, dadoAmarelo, dadoAmarelo, dadoAmarelo,
dadoVerde, dadoVermelho, dadoVermelho]
print("\nSTARTING THE GAME...")
jogadorAtual = 0
dadosSorteados = []
tiros = 0
cerebros = 0
passos = 0
while True:
print("PLAYER TURN: ", listaJogadores[jogadorAtual])
for i in range (3):
numeroSorteado = random.randint(0, 12)
dadoSorteado = listaDados[numeroSorteado]
if (dadoSorteado == dadoVerde):
corDado = "Green"
elif (dadoSorteado == dadoAmarelo):
corDado = "Yellow"
else:
corDado = "Red"
print("Dice Drawn: ", corDado)
dadosSorteados.append(dadoSorteado)
print("\nThe faces drawn were: ")
for dadoSorteado in dadosSorteados:
numeroFaceDado = random.randint(0,5)
if dadoSorteado[numeroFaceDado] == "brain":
print("- brain (you ate a brain)")
cerebros = cerebros + 1
elif dadoSorteado[numeroFaceDado] == "tiro":
print("- shot (you got shot)")
tiros = tiros + 1
else:
print("- steps (a victim escaped)")
passos = passos + 1
print("\nCURRENT SCORE: ")
print("brins: ", cerebros)
print("shots: ", tiros)
if cerebros >= 13:
print("Congratulations, you've won the game!")
break
elif tiros >= 3:
print("You lost the game!")
break
else:
continuarTurno = str(input("\nNOTICE: Do you want to continue playing dice? (y=yes / n=no)")).lower()
if continuarTurno == "n":
jogadorAtual = jogadorAtual + 1
dadossorteados = 0
tiros = 0
cerebros = 0
passos = 0
if jogadorAtual > numeroJogadores:
print("Finalizing the game prototype")
else:
print("Starting another round of the current turn")
dadossorteados = []
print("======================================================")
print("===================== END OF THE GAME ====================")
print("======================================================")
Does anyone know what I'm doing wrong?
I'm new as a programmer. If anyone knows how to help me with this problem, I would be grateful.
EDIT: Well now the code just works. I can switch players just fine, but if you go through all the characters it crashes again since jogadorAtual gets too big for listaJogadores. I don't quite understand the game, but assuming you want to start back with the first player, an elegant way you can accomplish that is by doing modulus with the % operator, which divides two numbers but returns the remainder. If you divide the number of players by the size of listaJogadores, you'll always get a number inside listaJogadores's range.
# Change this...
print("PLAYER TURN: ", listaJogadores[jogadorAtual])
# ...to this
print("PLAYER TURN: ", listaJogadores[jogadorAtual % len(listaJogadores)])
If that's not what you need for your game, let me know.
Original answer: Is the game ending or is it crashing? When I run the game, it always crashes with:
File "C:\Users\me\Desktop\Untitled-1.py", line 56, in <module>
diceDrawns.append(diceDrawn)
AttributeError: 'int' object has no attribute 'append'
This is because after looping, you try to do diceDrawns.append(), but you've already replaced the diceDrawns list with an integer on line 87. I'm not sure if you meant to replace diceDrawn instead, but that's definitely the source of the problem.
An unrelated note: You can do += as a shorthand way to increment a variable by a certain amount, so you can replace a lot of instances of things like currentPlayer = currentPlayer + 1 with currentPlayer += 1, and the same can be done with any operator, so you could also do things like -= or *=

Menu-driven collection of non-negative integers

I'm attempting to create a menu-driven program where python will accept a collection of non-negative integers. It will calculate the mean and median and display the values on the screen. I want my first option to be "Add a number to the list/array", I want my second option to be "Display the mean", the third to be "Display the median", the fourth "Print the list/array to the screen", the fifth "Print the list/array in reverse order" and the last option "Quit". So far I have gotten:
def main():
myList = [ ]
addOne(myList)
choice = displayMenu()
while choice != '6':
if choice == '1':
addOne(myList)
elif choice == '2':
mean(myList)
elif choice == '3':
median(myList)
elif choice == '4':
print(myList)
elif choice == '5':
print(myList)
choice = displayMenu()
print ("\nThanks for playing!\n\n")
def displayMenu():
myChoice = '0'
while myChoice != '1' and myChoice != '2' \
and myChoice != '3' \
and myChoice != '4' and myChoice != '5':
print("""\n\nPlease choose
1. Add a number to the list/array
2. Display the mean
3. Display the median
4. Print the list/array to the screen
5. Print the list/array in reverse order
6. Quit
""")
myChoice = input("Enter option---> ")
if myChoice != '1' and myChoice != '2' and \
myChoice != '3' and myChoice != '4' and myChoice != '5':
print("Invalid option. Please select again.")
return myChoice
#This should make sure that the user puts in a correct input
def getNum():
num = -1
while num < 0:
num = int(input("\n\nEnter a non-negative integer: "))
if num < 0:
print("Invalid value. Please re-enter.")
return num
#This is to take care of number one on the list: Add number
def addOne(myList):
while True:
try:
num = (int(input("Give me a number:")))
num = int(num)
if num < 0:
raise exception
print("Thank you!")
break
except:
print("Invalid. Try again...")
myList.append(num)
#This should take care of the second on the list: Mean
def mean(myList):
myList = [ ]
listSum = sum(myList)
listLength = len(myList)
listMean = listSum / listLength
print("The mean is", listMean)
#This will take care of number three on the list: Median
def median(myList):
median = 0
sortedlist = sorted(myList)
lengthofthelist = len(sortedlist)
centerofthelist = lengthofthelist / 2
if len(sortedlist) % 2 ==0:
return sum(num[center - 1:center + 1]) / 2.0
else:
return num[center]
print("The mean is", centerofthelist)
#This will take care of the fourth thing on the list: Print the list (In order)
def sort(myList):
theList.sort(mylist)
print(myList)
#This will take care of the fifth thing on the list
def reversesort(myList):
theList.sort(reverse=True)
print(myList)
main()
After I run the program I can't get past creating the list.
Corrected code with minimum changes:
def main():
myList = []
choice = 1
while choice != 6:
if choice == 1:
option1(myList)
elif choice == 2:
option2(myList)
elif choice == 3:
option3(myList)
elif choice == 4:
option4(myList)
elif choice == 5:
option5(myList)
choice = displayMenu()
print ("\nThanks for playing!\n\n")
def displayMenu():
myChoice = 0
while myChoice not in [1, 2, 3, 4, 5]:
print("""\n\nPlease choose
1. Add a number to the list/array
2. Display the mean
3. Display the median
4. Print the list/array
5. Print the list/array in reverse order
6. Quit
""")
myChoice = int(input("Enter option---> "))
if myChoice not in [1, 2, 3, 4, 5]:
print("Invalid option. Please select again.")
return myChoice
# Option 1: Add a number to the list/array
def option1(myList):
num = -1
while num < 0:
num = int(input("\n\nEnter a non-negative integer: "))
if num < 0:
print("Invalid value. Please re-enter.")
myList.append(num)
# Option 2: Display the mean
def option2(myList):
print("The mean is ", sum(myList) / len(myList))
# Option 3: Display the median
def option3(myList):
sortedlist = sorted(myList)
if len(sortedlist) % 2:
median = myList[int(len(sortedlist) / 2)]
else:
center = int(len(sortedlist) / 2)
median = sum(myList[center-1:center+1]) / 2
print("The median is", median)
# Option 4: Print the list/array
def option4(myList):
print(sorted(myList))
# Option 5: Print the list/array in reverse order
def option5(myList):
print(sorted(myList, reverse=True))
main()
How I would do this:
The first part of the following code are a set of constants to customize the style of the menu. Then a set of functions representing each option are defined. The following 3 functions should not be modified, they generate the menu, display it and close the application. Then the main section starts, where you need to pass every option as an argument to setOptions(). The rest should not be modified either as it is the main loop.
# Menu formatting constants
MENU_HEADER = "Please choose an option:"
MENU_FORMAT = " * {:2}. {}"
MENU_QUIT_S = "Quit"
MENU_ASK_IN = "Enter option: "
MENU_INT_ER = "ERROR: Invalid integer. Please select again."
MENU_OPT_ER = "ERROR: Invalid option. Please select again."
END_MESSAGE = "Thanks for playing!"
# OPTIONS FUNCTIONS START HERE
def addElement(l):
""" Add a number to the list/array. """
n = -1
while n < 0:
try:
n = int(input("Enter a non-negative integer: "))
except ValueError:
print("It needs to be an integer.")
n = -1
else:
if n < 0:
print("It needs to be a non-negative integer.")
l.append(n)
def mean(l):
""" Calculate the mean. """
print("Mean: {:7.2}".format(sum(l) / len(l)))
def median(l):
""" Calculate the median. """
l = sorted(l)
p = int(len(l) / 2)
print("Median: {:7.2}".format(l[p] if len(l)%2 else sum(l[p-1:p+1])/2))
def oprint(l):
""" Print the list/array. """
print(sorted(l))
def rprint(l):
""" Print the list/array in reverse order. """
print(sorted(l, reverse=True))
# OPTIONS FUNCTIONS END HERE
def onQuit(l):
""" Function to execute when quitting the application. """
global quit
quit = True
print(END_MESSAGE)
def setOptions(*args):
""" Generates the menu and the options list. """
# Menu header and quit option (option 0)
menu = [MENU_HEADER]
options = [onQuit]
# Passed arguments represent texts and functions of additional options
for i, f in enumerate(args, start=1):
menu.append(MENU_FORMAT.format(i, f.__doc__.strip()))
options.append(f)
# We print the option 0 the last one
menu.append(MENU_FORMAT.format(0, MENU_QUIT_S))
# Returning both the menu and the options lists
return tuple(menu), tuple(options)
def displayMenu(menu):
""" Display the menu and get an option that is an int. """
while True:
for line in menu:
print(line)
try:
choice = int(input(MENU_ASK_IN))
except ValueError:
print(MENU_INT_ER)
else:
return choice
if __name__ == '__main__':
# Pass the option functions to the setOptions function as arguments
menu, options = setOptions(
addElement,
mean,
median,
oprint,
rprint
)
# Initiate the needed variables and start the loop
l = []
quit = False
while not quit:
c = displayMenu(menu)
try:
f = options[c]
except IndexError:
print(MENU_OPT_ER)
else:
f(l)
There is an indentation error inside your function addOne.
myList.append(num) is inside the while loop, and just before that you have a break, so the number is never appended to the list because we have left the loop already.

Issue setting matplot points color and shape

Whenever I run the display_data function (when there is data to be run after successfully answering at least one calculation_game question) I get an error that says:
"ValueError: to_rgba: Invalid rgba arg "o"
to_rgb: Invalid rgb arg "o"
could not convert string to float: 'o'"
When I run the code without the "o" to define the shape of the points it works fine and displays blue points. Only thing is that I want to be able to define shapes such as "o" and "v" because the plot will be showing data from multiple list when it is done. Any ideas?
NOTE:
There are missing functions below. I removed them here because they are not needed for the question.
import random
from random import randint
import time
import math
import matplotlib.pyplot as plt
# Number of problems for each practice/real round
practice_round = 0
real_round = 3
main_record = []
CALC_RECORD = []
# (1) Calculation Game ---------------------------------------------------------
'''Calculation game is a math game'''
def calculation():
response_time = None
# Determine the min and max calculation values
min_calculation_value = 1
max_calculation_value = 10
# Generate the problems
print('\nSolve the following problem:')
a = random.randint(min_calculation_value, max_calculation_value)
b = random.randint(min_calculation_value, max_calculation_value)
problem_type = random.randint(1,2)
if problem_type == 1:
answer = a * b
print(a, '*', b)
elif problem_type == 2:
answer = a % b
print(a, '%', b)
# Get the user's answer determine what to do if correct
start_time = time.time()
user_answer = input('\nEnter your answer: ')
end_time = time.time()
if user_answer == str(answer):
response_time = end_time - start_time
print('You are correct!')
elif user_answer != str(answer):
print('Oops, you are incorrect.')
# Return game id, start time, and response time
return("calculation", start_time, response_time)
def calculation_game():
record = []
# Generate two problems for a practice round
print("\nLet's begin with 2 practice problems.")
for i in range (practice_round):
print('\nPractice Problem', i + 1, 'of', practice_round)
calculation()
# Generate 10 problems for a real, recorded round
print("\nNow let's try it for real this time.")
for i in range (real_round):
print('\nProblem', i + 1, 'of', real_round)
# Append records for each iteration
record.append(calculation())
main_record.extend(record)
CALC_RECORD.extend(record)
return record
# (5) Display Data -------------------------------------------------------------
def display_data():
plt.ylabel('Time Per Question')
plt.xlabel('Round Played')
CALC_RECORD.sort(key=lambda record:record[1])
calc_time = [t[2] for t in CALC_RECORD if t[0] =='calculation' and t[2] != None]
alist=[i for i in range (len(calc_time))]
if len(calc_time) >0:
print (calc_time)
x = alist
y = calc_time
plt.scatter(x, y, c="bo")
plt.show(block=True)
main_menu()
# (6) Save Progress ------------------------------------------------------------
# (7) Load Data ----------------------------------------------------------------
# (8) Quit Game ----------------------------------------------------------------
def quit_game():
print('\nThank you for playing!')
# Main Menu --------------------------------------------------------------------
def menu():
print("\nEnter 1 to play 'Calculation'")
print("Enter 2 to play 'Binary Reader'")
print("Enter 3 to play 'Trifacto'")
print("Enter 4 to view your statistics")
print("Enter 5 to display data")
print("Enter 6 to save your progress")
print("Enter 7 to load data")
print("Enter 8 to quit the game")
def main_menu():
print('Welcome!')
user_input = ''
while user_input != '8':
menu()
user_input = input('\nWhat would you like to do? ')
if user_input == '1':
calculation_game()
if user_input == '2':
binary_reader_game()
if user_input == '3':
trifacto_game()
if user_input == '4':
display_statistics()
if user_input == '5':
display_data()
if user_input == '8':
quit_game()
main_menu()
Got it, just had to remove the c= part from plt.scatter(x, y, c="bo")

Why is this python "War" card game freezing after only a few games?

Basically, I'm trying to test how the order of the cards in a players hand affects how often they win, but I run the program and the score will sometimes get stuck at player one alternating between 27 & 26 cards in hand, while player two alternates between 25 & 26 cards in hand and it just sticks like that.
import random
import sys
class Card:
def __init__(self, rank, suit, value):
self.rank = rank
self.suit = suit
self.value = value
self.name = str(self.rank) + " of " + self.suit
def create_deck():
suit = ['Spades', 'Hearts', 'Clubs', 'Diamonds']
rank = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace']
deck = []
num = 2
for i in suit:
for x in rank:
deck.append(Card(x, i, num))
num = num + 1
num = 2
return sorted(deck, key=lambda k: random.random())
def deal_cards(deck):
x = 0
i = 0
player1 = []
player2 = []
while i < len(deck):
if x == 0:
player1.append(deck[i])
x = 1
else:
player2.append(deck[i])
x = 0
i += 1
return player1, player2
def game():
pl1wins = 0
pl2wins = 0
while (pl1wins + pl2wins) <= 50:
deck = create_deck()
players = deal_cards(deck)
player1 = players[0]
player2 = players[1]
player1 = sorted(player1, key=lambda card: card.value)
war = []
turns = 0
while len(player1) > 0 and len(player2) > 0:
turns = turns + 1
#print turns
#print str(len(player1))+ " : " + str(len(player2))
if (len(player1) + len(player2)) > 52:
print "Oh NO!"
sys.exit()
war = []
war.append(player1[0])
war.append(player2[0])
player1.remove(player1[0])
player2.remove(player2[0])
if war[0].value > war[1].value:
#print "Player 1 wins the " + war[1].name
i = 0
n = len(war)
while i < n:
player1.append(war[0])
war.remove(war[0])
i = i + 1
elif war[0].value < war[1].value:
#print "Player 2 wins the " + war[0].name
i = 0
n = len(war)
while i < n:
player2.append(war[0])
war.remove(war[0])
i = i + 1
elif war[0].value == war[1].value:
if len(player1) == 0:
player1.append(war[0])
war.remove(war[0])
if player1[0].value == player2[0].value:
player1[0].value = 0
if len(player2) == 0:
player2.append(war[1])
war.remove(war[1])
if player1[0].value == player2[0].value:
player2[0].value = 0
while len(war) > 0:
#print "The cards have tied, war will commence"
i = 0
for i in range(3):
if len(player1) > 1:
war.append(player1[0])
player1.remove(player1[0])
if len(player2) > 1:
war.append(player2[0])
player2.remove(player2[0])
if player1[0].value > player2[0].value:
war.append(player1[0])
war.append(player2[0])
player1.remove(player1[0])
player2.remove(player2[0])
i = 0
n = len(war)
while i < n:
player1.append(war[0])
war.remove(war[0])
i = i + 1
elif player1[0].value < player2[0].value:
war.append(player1[0])
war.append(player2[0])
player1.remove(player1[0])
player2.remove(player2[0])
i = 0
n = len(war)
while i < n:
player2.append(war[0])
war.remove(war[0])
i = i + 1
#print turns
if len(player1) != 0:
print "Player1 wins!"
pl1wins = pl1wins + 1
elif len(player2) != 0:
print "Player2 wins!"
pl1wins = pl2wins + 1
print pl1wins + " versus " + pl2wins
game()
Thanks to #Engineero for your comment:
There are possible infinite games in War, provided you do not switch the order in which player's cards are added to the bottom of the winning player's deck (i.e. always opponent's card first, then yours or vice versa). See this MathOverflow discussion. Basically for some deals, the game never ends. You could add occasional switching to the order that cards are returned to the bottom of the deck to make it finite. – Engineero
That led me to this solution:
Basically, I randomized which card was put in the pile first as such:
if random.randint(1,2) == 1:
war.append(player2[0])
war.append(player1[0])
else:
war.append(player1[0])
war.append(player2[0])
And this fixed the problem perfectly.

List object occurrence checker python

I was working on a small project, and I've run across a little error in my programming. It's a basic battleship game, and so far I have two "ships" set, and I have the game to end when both on either my side or the enemy side is hit.
def enemy_board():
global enemy_grid
enemy_grid = []
for i in range (0,10):
enemy_grid.append(["="] * 10)
def random_row_one(enemy_grid):
return randint(0, len(enemy_grid) - 1)
def random_col_one(enemy_grid):
return randint(0, len(enemy_grid) - 1)
def random_row_two(enemy_grid):
return randint(0, len(enemy_grid) - 1)
def random_col_two(enemy_grid):
return randint(0, len(enemy_grid) - 1)
global x_one
x_one = random_row_one(enemy_grid)
global y_one
y_one = random_col_one(enemy_grid)
global x_two
x_two = random_row_two(enemy_grid)
global y_two
y_two = random_col_two(enemy_grid)
print(x_one)
print(y_one)
print(x_two)
print(y_two)
So that's the basis of my list, but later on in the code is where it's giving me a little trouble.
elif enemy_grid.count("H") == 2:
print("\nYou got them all!\n")
break
Update
Sorry I was a little unclear about what I meant.
def my_board():
global my_grid
my_grid = []
for i in range (0,10):
my_grid.append(["O"] * 10)
def my_row_one(my_grid):
int(input("Where do you wish to position your first ship on the x-axis? "))
def my_col_one(my_grid):
int(input("Where do you wish to position your first ship on the y-axis? "))
global x_mio
x_mio = my_row_one(my_grid)
global y_mio
y_mio = my_col_one(my_grid)
def my_row_two(my_grid):
int(input("\nWhere do you wish to position your other ship on the x-axis? "))
def my_col_two(my_grid):
int(input("Where do you wish to position your other ship on the y-axis? "))
global x_mit
x_mit = my_row_two(my_grid)
global y_mit
y_mit = my_col_two(my_grid)
def enemy_board():
global enemy_grid
enemy_grid = []
for i in range (0,10):
enemy_grid.append(["="] * 10)
def random_row_one(enemy_grid):
return randint(0, len(enemy_grid) - 1)
def random_col_one(enemy_grid):
return randint(0, len(enemy_grid) - 1)
def random_row_two(enemy_grid):
return randint(0, len(enemy_grid) - 1)
def random_col_two(enemy_grid):
return randint(0, len(enemy_grid) - 1)
global x_one
x_one = random_row_one(enemy_grid)
global y_one
y_one = random_col_one(enemy_grid)
global x_two
x_two = random_row_two(enemy_grid)
global y_two
y_two = random_col_two(enemy_grid)
print(x_one)
print(y_one)
print(x_two)
print(y_two)
title()
my_board()
enemy_board()
m = 20
guesses = m
while guesses > 0:
def printmi_board(my_grid):
for row in my_grid:
print(" ".join(row))
def printyu_board(enemy_grid):
for row in enemy_grid:
print (" ".join(row))
print(printmi_board(my_grid))
print(printyu_board(enemy_grid))
try:
guess_x = int(input("Take aim at the x-xalue: "))
except ValueError:
print("\nI SAID TAKE AIM!\n")
guess_x = int(input("Take aim at the x-xalue: "))
try:
guess_y = int(input("Take aim at the y-value: "))
except ValueError:
print("\nDo you have wax in your ears?? AIM!\n")
guess_y = int(input("Take aim at the y-value: "))
comp_x = randint(0, len(my_grid) - 1)
comp_y = randint(0, len(my_grid) - 1)
if x_one == guess_x and y_one == guess_y:
print("\nYou hit one! \n")
enemy_grid[guess_x - 1][guess_y - 1] = "H"
continue
elif x_two == guess_x and y_two == guess_y:
enemy_grid[guess_x - 1][guess_y - 1] = "H"
print("\nYou hit one! \n")
continue
elif enemy_grid[guess_x - 1][guess_y - 1] == "O":
print("\nYou've tried there before! Here's another round.\n")
print("You have " + str(guesses) + " rounds left, cadet.\n\n")
continue
elif enemy_grid.count("H") == 2:
print("\nYou got them all!\n")
break
else:
if guess_x not in range(10) or guess_y not in range(10):
print("\nThat's not even in the OCEAN!! Take another free round then.\n")
print("You have " + str(guesses) + " rounds left, cadet.\n\n")
continue
elif enemy_grid[guess_x][guess_y] == "O":
print("\nYou've tried there before! Here's another round.\n")
print("You have " + str(guesses) + " rounds left, cadet.\n\n")
continue
else:
print("\nYou missed, soldier!\n")
guesses = guesses - 1
print("You have " + str(guesses) + " rounds left, cadet.\n\n")
enemy_grid[guess_x - 1][guess_y - 1] = "O"
if comp_x == x_mio and comp_y == y_mio:
my_grid[comp_x - 1][comp_y - 1] = "H"
print("\nThe enemy hit you! \n")
continue
elif comp_x == x_mit and comp_y == y_mit:
my_grid[comp_x - 1][comp_y - 1] = "H"
print("\nThe enemy hit you! \n")
continue
elif my_grid.count("H") == 2:
print("We have to retreat! They've sunken all of your ships...")
break
else:
my_grid[comp_x - 1][comp_y - 1] = "="
continue
I'm using python 3 if that makes any difference. So it's that if the player hits the correct spot on the grid, then it'll show as "H" and not as "=" or "O". So I was just wondering about if I could count those "H"'s to use to end the IF loop.
You haven't really explained the problem, and so much of the code is missing that it's very hard to tell you what's wrong, I'm going to guess at it though.
My guess is that you create an '=' grid to represent a player's board, and then if their ship is 'hit' you replace the '=' in that position with an 'H'.
The structure you create (enemy_grid) seems to look something like:
[[====]
[====]
[====]
[....]]
in which case your test, enemy_grid.count("H") doesn't make sense as enemy_grid is a list that contains other lists (so the count of Hs will always be 0 - they're deeper down in the 2nd layer of lists).
You probably want a test more along the lines of:
[cell for row in enemy_grid for cell in row].count('H')

Categories

Resources