Python battleship, double the trouble - python

Why does it ask you twice where you want to put you battleship?
I have no clue way is does what it does.
Anyway in this link you can see the full code, because I don't know if that is necessary. http://speedy.sh/QYJWp/battleship-goed.txt
I think that the problem occurs before the //_________________________________________________________// part
board1 = []
board2 = []
for x in range(10):
board1.append(["O"] * 10)
for x in range(10):
board2.append(["O"] * 10)
def print_board1(board):
for row in board:
print " ".join(row)
def print_board2(board):
for row in board:
print " ".join(row)
print "Board User 1"
print_board1(board1)
print "----------------------------------------------"
print "Board User 2"
print_board2(board2)
print "Let's play Battleship!"
print "Try to destroy all your opponents battleship!"
print"Good luck!"
print " "
print " "
def U1_Input_row1(board1):
x = float(raw_input("User 1, in what row do you want to place your first ship?"))
if x > 0 and x < 11 and x%1 == 0:
return x - 1
else:
print "Please enter an integer and a number between 1 and 10"
U1_Input_row1(board1)
def U1_Input_col1(board1):
x = float(raw_input("User 1, in what col do you want to place your first ship?"))
if x > 0 and x < 11 and x%1 == 0:
return x - 1
else:
print "Please enter an integer and a number between 1 and 10"
U1_Input_col1(board1)
ship1 = [U1_Input_row1(board1), U1_Input_col1(board1)]
def U1_Input_row2(board1):
x = float(raw_input("User 1, in what row do you want to place your second ship?"))
if x > 0 and x < 11 and x%1 == 0:
return x - 1
else:
print "Please enter an integer and a number between 1 and 10"
U1_Input_row2(board1)
def U1_Input_col2(board1):
x = float(raw_input("User 1, in what col do you want to place your second ship?"))
if x > 0 and x < 11 and x%1 == 0:
return x - 1
else:
print "Please enter an integer and a number between 1 and 10"
U1_Input_col2(board1)
ship2 = [U1_Input_row2(board1), U1_Input_col2(board1)]
def U1_Input_row3(board1):
x = float(raw_input("User 1, in what row do you want to place your third ship?"))
if x > 0 and x < 11 and x%1 == 0:
return x - 1
else:
print "Please enter an integer and a number between 1 and 10"
U1_Input_row3(board1)
def U1_Input_col3(board1):
x = float(raw_input("User 1, in what col do you want to place your third ship?"))
if x > 0 and x < 11 and x%1 == 0:
return x - 1
else:
print "Please enter an integer and a number between 1 and 10"
U1_Input_col3(board1)
ship3 = [U1_Input_row3(board1), U1_Input_col3(board1)]
def U1_Input_row4(board1):
x = float(raw_input("User 1, in what row do you want to place your fourth ship?"))
if x > 0 and x < 11 and x%1 == 0:
return x - 1
else:
print "Please enter an integer and a number between 1 and 10"
U1_Input_row4(board1)
def U1_Input_col4(board1):
x = float(raw_input("User 1, in what col do you want to place your fourth ship?"))
if x > 0 and x < 11 and x%1 == 0:
return x - 1
else:
print "Please enter an integer and a number between 1 and 10"
U1_Input_col4(board1)
ship4 = [U1_Input_row4(board1), U1_Input_col4(board1)]
if ship1 == ship2 or ship1 == ship3 or ship1 == ship4 or ship2 == ship3 or ship2 == ship4 or ship3 == ship4:
print "YOU CANT PLACE 2 SHIPS IN THE SAME SPOT"
U1_Input_row1(board1)
U1_Input_col1(board1)
U1_Input_row2(board1)
U1_Input_col2(board1)
U1_Input_row3(board1)
U1_Input_col3(board1)
U1_Input_row4(board1)
U1_Input_col4(board1)
def U2_Input_row1(board2):
x = float(raw_input("User 2, in what row do you want to place your first ship?"))
if x > 0 and x < 11 and x%1 == 0:
return x - 1
else:
print "Please enter an integer and a number between 1 and 10"
U2_Input_row1(board2)
def U2_Input_col1(board2):
x = float(raw_input("User 2, in what col do you want to place your first ship?"))
if x > 0 and x < 11 and x%1 == 0:
return x - 1
else:
print "Please enter an integer and a number between 1 and 10"
U2_Input_col1(board2)
ship1u2 = [U2_Input_row1(board1), U2_Input_col1(board1)]
def U2_Input_row2(board2):
x = float(raw_input("User 2, in what row do you want to place your second ship?"))
if x > 0 and x < 11 and x%1 == 0:
return x - 1
else:
print "Please enter an integer and a number between 1 and 10"
U2_Input_row2(board2)
def U2_Input_col2(board2):
x = float(raw_input("User 2, in what col do you want to place your second ship?"))
if x > 0 and x < 11 and x%1 == 0:
return x - 1
else:
print "Please enter an integer and a number between 1 and 10"
U2_Input_col2(board2)
ship2u2 = [U2_Input_row2(board1), U2_Input_col2(board1)]
def U2_Input_row3(board2):
x = float(raw_input("User 2, in what row do you want to place your third ship?"))
if x > 0 and x < 11 and x%1 == 0:
return x - 1
else:
print "Please enter an integer and a number between 1 and 10"
U2_Input_row3(board2)
def U2_Input_col3(board2):
x = float(raw_input("User 2, in what col do you want to place your third ship?"))
if x > 0 and x < 11 and x%1 == 0:
return x - 1
else:
print "Please enter an integer and a number between 1 and 10"
U2_Input_col3(board2)
ship3u2 = [U2_Input_row3(board1), U2_Input_col3(board1)]
def U2_Input_row4(board2):
x = float(raw_input("User 2, in what row do you want to place your fourth ship?"))
if x > 0 and x < 11 and x%1 == 0:
return x - 1
else:
print "Please enter an integer and a number between 1 and 10"
U2_Input_row4(board2)
def U2_Input_col4(board2):
x = float(raw_input("User 2, in what col do you want to place your fourth ship?"))
if x > 0 and x < 11 and x%1 == 0:
return x - 1
else:
print "Please enter an integer and a number between 1 and 10"
U2_Input_col4(board2)
ship4u2 = [U2_Input_row4(board1), U2_Input_col4(board1)]
if ship1u2 == ship2u2 or ship1u2 == ship3u2 or ship1u2 == ship4u2 or ship2u2 == ship3u2 or ship2u2 == ship4u2 or ship3u2 == ship4u2:
print "YOU CANT PLACE 2 SHIPS IN THE SAME SPOT"
U2_Input_row1(board2)
U2_Input_col1(board2)
U2_Input_row2(board2)
U2_Input_col2(board2)
U2_Input_row3(board2)
U2_Input_col3(board2)
U2_Input_row4(board2)
U2_Input_col4(board2)
U1_Input_row1 = U1_Input_row1(board1)
U1_Input_col1 = U1_Input_col1(board1)
U1_Input_row2 = U1_Input_row2(board1)
U1_Input_col2 = U1_Input_col2(board1)
U1_Input_row3 = U1_Input_row3(board1)
U1_Input_col3 = U1_Input_col3(board1)
U1_Input_row4 = U1_Input_row4(board1)
U1_Input_col4 = U1_Input_col4(board1)
U2_Input_row1 = U2_Input_row1(board2)
U2_Input_col1 = U2_Input_col1(board2)
U2_Input_row2 = U2_Input_row2(board2)
U2_Input_col2 = U2_Input_col2(board2)
U2_Input_row3 = U2_Input_row3(board2)
U2_Input_col3 = U2_Input_col3(board2)
U2_Input_row4 = U2_Input_row4(board2)
U2_Input_col4 = U2_Input_col4(board2)

It's asking it twice because it goes through the script and hits these between the functions:
ship1 = [U1_Input_row1(board1), U1_Input_col1(board1)]
ship2 = [U1_Input_row2(board1), U1_Input_col2(board1)]
ship3 = [U1_Input_row3(board1), U1_Input_col3(board1)]
ship4 = [U1_Input_row4(board1), U1_Input_col4(board1)]
ship1u2 = [U2_Input_row1(board1), U2_Input_col1(board1)]
ship2u2 = [U2_Input_row2(board1), U2_Input_col2(board1)]
ship3u2 = [U2_Input_row3(board1), U2_Input_col3(board1)]
ship4u2 = [U2_Input_row4(board1), U2_Input_col4(board1)]
Then at the end it asks for input again with these calls:
U1_Input_row1 = U1_Input_row1(board1)
U1_Input_col1 = U1_Input_col1(board1)
U1_Input_row2 = U1_Input_row2(board1)
U1_Input_col2 = U1_Input_col2(board1)
U1_Input_row3 = U1_Input_row3(board1)
U1_Input_col3 = U1_Input_col3(board1)
U1_Input_row4 = U1_Input_row4(board1)
U1_Input_col4 = U1_Input_col4(board1)
U2_Input_row1 = U2_Input_row1(board2)
U2_Input_col1 = U2_Input_col1(board2)
U2_Input_row2 = U2_Input_row2(board2)
U2_Input_col2 = U2_Input_col2(board2)
U2_Input_row3 = U2_Input_row3(board2)
U2_Input_col3 = U2_Input_col3(board2)
U2_Input_row4 = U2_Input_row4(board2)
U2_Input_col4 = U2_Input_col4(board2)
The script is poorly thought out though, as most of these functions could have just been stuffed into a single function to save fewer lines of code.
This would be annoying for the user since he would have to go through the whole process of inputting ship positions even though 7/8 of them were ok.
if ship1u2 == ship2u2 or ship1u2 == ship3u2 or ship1u2 == ship4u2 or ship2u2 == ship3u2 or ship2u2 == ship4u2 or ship3u2 == ship4u2:
You can also use while statement to keep asking a question if the user inputs something wrong. The way it's being done now is a bit weird.
If the user inputs a bunch of letters or whatnot the script will crash right away because there's no error checking there. The use of isdigit() can help determine if the input is an integer before converting to int, and a try except can be use if the field is simply left empty.
Hope this helps out :)

I don't see where it would do what you described, but I think you should use an array instead of doing ship1u1... It would make it a lot easier to read your code and it would save you a couple lines.

Related

Execute code whenever the space bar is pressed?

I am making this kind of a game but it isn't really a game so basically I want this to run every time I hit space but it doesn't work no matter what I try so I would be really thankful if somebody could have helped me out on this.
import random
import keyboard
food = 5
x = 0
y = 0
if keyboard.is_pressed('space'):
bobsDecision = random.randint(0,1)
if bobsDecision == 1:
print ('bob ate')
food = 5
else:
xoy = random.randint(1,4)
if xoy == 1:
x = x + 1
elif xoy == 2:
x = x - 1
elif xoy == 3:
y = y + 1
elif xoy == 4:
y = y - 1
food = food - 1
print ('the cords are ', x, " ", y)
print ('The food supply is ', food)
Your code runs once and immediately skips over keyboard.is_pressed("space"), and then exits.
What you want to do instead is to loop forever, and use the keyboard module's read_key functionality to make it wait for a keypress.
An example of this is this - I also added support for exiting the loop/game with esc.
import random
import keyboard
food = 5
x = 0
y = 0
while True:
keyboard.read_key()
if keyboard.is_pressed("esc"):
print("Stopping play...")
break
elif keyboard.is_pressed("space"):
bobsDecision = random.randint(0,1)
if bobsDecision == 1:
print ('bob ate')
food = 5
else:
xoy = random.randint(1,4)
if xoy == 1:
x = x + 1
elif xoy == 2:
x = x - 1
elif xoy == 3:
y = y + 1
elif xoy == 4:
y = y - 1
food = food - 1
print ('the cords are ', x, " ", y)
print ('The food supply is ', food)
You need to put the if statement in a while loop. But ALSO be sure to have some kind of exit code. Below, I used the keypress esc to stop the while loop:
import random
import keyboard
food = 5
x = 0
y = 0
while True:
keyboard.read_key() # an important inclusion thanks to #wkl
if keyboard.is_pressed('esc'):
break
elif keyboard.is_pressed('space'):
bobsDecision = random.randint(0,1)
if bobsDecision == 1:
print ('bob ate')
food = 5
else:
xoy = random.randint(1,4)
if xoy == 1:
x = x + 1
elif xoy == 2:
x = x - 1
elif xoy == 3:
y = y + 1
elif xoy == 4:
y = y - 1
food = food - 1
print ('the cords are ', x, " ", y)
print ('The food supply is ', food)

Skips Elif Condition

during the execution of the code the program skips all ELIF conditions, going directly to ELSE, even if the ELIF condition is TRUE
a = 0
b = 0
c = 0
r = 0
soma = 1
sub = 2
div = 3
mult = 4
print('enter the number corresponding to the operation you want to do:\n')
print('Sum [1]')
print('Subtraction[2]')
print('Divisao [3]')
print('Multiplication [4]')
r = int(1)
while (r == 1):
operacao = 0
operacao = input('\n>')
if operacao == soma:
a = int(input('Enter the value of a:'))
b = int(input('Enter the value of b:'))
c = a + b
print ('\n A Soma de {} mais {} equivale a: {}'.format(a,b,c))
elif operacao == sub:
a = int(input('Enter the value of a:'))
b = int(input('Enter the value of b:'))
c = a - b
print ('\n A subtracao de {} menos {} equivale a: {}'.format(a,b,c))
elif operacao == div:
a = int(input('Enter the value of a:'))
b = int(input('Enter the value of b:'))
c = a / b
print ('\n A divisao de {} de {} equivale a: {}'.format(a,b,c))
elif operacao == mult:
a = int(input('Enter the value of a:'))
b = int(input('Enter the value of b:'))
c = a * b
print ('\n The multiplication of {} by {} is equivalent to: {}'.format(a,b,c))
else: #going direct to here...
print('\n Unrecognized operation')
EXPECTED that the ELIF conditions would work when true,but not working.
input returns a string, so you'll need to do operacao = int(input('\n>')), otherwise str == int will always be False:
x = input("\n>") # I've input 5
x
# '5'
# returns False because x is a string
x == 5
# False
# converts x to int, so returns True
int(x) == 5
# True
# returns True because we are comparing to a string
x == '5'
# True
So for your code:
# convert the return of input to int for comparing against other ints
operacao = int(input('\n>')) # I'll put 3
if operacao == 1:
print('got one')
elif operacao == 3:
print('got three')
# got three

I need to make a EAN-13 number validity checker in Python2. I don't see why this doesn't work

inp = raw_input("Input a EAN-13 number.")
aaa = False
bbb = False
if len(inp) == 13:
bbb = True
else:
print "Error input"
exit
ean_number = int(inp)
def ean13(value_1):
mult_of_ten = 0
sum_of_digits = 0
done = False
for z in len(value_1):
if not z == 0:
if z % 2 == 0:
value_1[z] *= 3
elif not z % 2 == 0:
value_1[z] *= 1
for a in len(value_1):
sum_of_digits += value_1[a]
if sum_of_digits % 10 == 0:
result = 0
elif not sum_of_digits % 10 == 0:
while done == False:
mult_of_ten = sum_of_digits
for d in True:
mult_of_ten += d
if sum_of_digits % 10 == 0:
done == True
result = mult_of_ten - sum_of_digits
if result == value_1[12]:
print "True"
if bbb == True:
ean13(ean_number)
I really don't see why teacher can't help either.
I need to make a EAN-13 number validity checker in Python2. I don't see why this doesn't work. Can anyone help?
I have made an EAN 13 Number Validity Checker in Python2.
Hope it helps you out.
# ean = '9780201379624'
ean = raw_input("Input a EAN-13 number:\n")
err = 0
even = 0
odd = 0
check_bit = ean[len(ean)-1]#get check bit(last bit)
check_val = ean[:-1]#Get all vals except check bit
if len(ean) != 13:#Check the input length
print "Invalid EAN 13"
else:
for index,num in enumerate(check_val):#Gather Odd and Even Bits
if index%2 == 0:
even += int(num)
else:
odd += int(num)
if ((3*odd)+even+int(check_bit)) % 10 == 0:# Check if the algorithm 3 * odd parity + even parity + check bit matches
print "Valid EAN 13"
else:
print "Invalid EAN 13"

Python input statement

I have created a battleship like game, and have it all completed except for one detail.
I have the following input statement:
x, y = input("Enter two numbers here: ").split()
with the 2 numbers being entered corresponding to the players chosen coordinates. I also need to be able to handle the entry of 'q' or 'h' for the quit or help options. However, since i am taking two variables from this statement when only a q or h is entered i get the error that the statement needs 2 elements to unpack, which makes sense. Any pointers on how to get around this?
import random, math
class oceanTreasure:
def __init__(self):
self.board = self.board()
self.found = 0
self.left = 3
self.sonarsLeft = 20
self.chests= []
self.chest()
def board(self):
board = []
for x in range(16): # the main list is a list of 60 lists
board.append([])
for y in range(61): # each list in the main list has 15 single-character strings.
board[x].append('~')
return board
def chest(self):
chest1 = [random.randint(0,60), random.randint(0,15)]
chest2 = [random.randint(0,60), random.randint(0,15)]
chest3 = [random.randint(0,60), random.randint(0,15)]
self.chests = [chest1, chest2, chest3]
def getChestsLeft(self):
return self.found
def getChests(self):
return self.chests
def getTreasuresLeft(self):
return self.left
def getSonarsLeft(self):
return self.sonarsLeft
def dropSonar(self,x,y):
ySonar = ['a','b','c','d','e','f','g']
whichAxis, axis = self.checkDistance(x,y)
if whichAxis == True:
sonar = axis
if whichAxis == 'xaxis':
sonar = axis
elif whichAxis == 'yaxis':
sonar = ySonar[axis-1]
elif whichAxis == None:
sonar = axis
self.board[int(y)][int(x)] = sonar
self.sonarsLeft -=1
return axis
def checkDistance(self,x,y):
closest = self.chests[0]
distance = 100
for chest in self.chests:
temp = math.sqrt(math.pow((chest[0]-int(x)),2) + math.pow((chest[1]-int(y)),2))
if temp < distance:
closest = chest
distance = temp
xaxis =math.fabs((closest[0] - int(x)))
yaxis = math.fabs((closest[1]-int(y)))
if yaxis == 0 and xaxis == 0:
self.chests.remove(closest)
self.found +=1
self.left -=1
return True, 'X'
elif xaxis <= 9 and yaxis <=5 :
if yaxis == 0 :
return 'xaxis',int(math.fabs(xaxis))
if xaxis == 0 :
return 'yaxis',int(math.fabs(yaxis))
if min(xaxis//2,yaxis) ==(xaxis//2) :
return 'xaxis', int(math.fabs(xaxis))
elif min(xaxis//2,yaxis) == (yaxis) or xaxis == 0 :
return 'yaxis', int(math.fabs(yaxis))
else: return None,0
def drawBoard(self):
firstLine = ' '
for i in range(1,7):
firstLine += (' '*9) + str(i)
print(firstLine)
secondLine = ' '
secondLine += ('0123456789' *6)
print(secondLine)
print()
i = 0
for i in range(0,16):
boardRow = ''
for x in range(0,61):
boardRow += str(self.board[i][x])
if i < 10:
print(str(i) +' ' + str(boardRow) + str(i))
if i >= 10:
print(str(i) +' ' + str(boardRow) + str(i))
print()
print(secondLine)
print(firstLine)
device = 'devices'
if self.sonarsLeft ==1:
device = 'device'
print('You have %s sonar %s availabe. You have found %s treasures and have %s left' %(self.sonarsLeft, device, self.found, self.left))
ocean = oceanTreasure()
ocean.drawBoard()
gameOver = False
instructionsList = ['This is a treasure hunting game.' , 'You begin the game with 20 sonar devices available (each device has a range of 9 units in the x axis and 5 in the y axis).','When you place a device, if an "O" is displayed that means there are no chests in range.', 'If a number from 1-9 is displayed, the closest chest is within n units away on the X axis.', 'If a letter from a-e is displayed, the closest chest is n units away on the Y axis (a =1, b =2 and so on...).', 'The game ends when you run out of sonar devices, all the treasure is found or you enter "q" to quit.', 'Thanks for playing and happy hunting!']
while ocean.getTreasuresLeft() != 0 and ocean.getSonarsLeft() >0 and gameOver == False:
response = False
coordinate = False
while response == False:
inputString = input("Enter two numbers seperated by a space (X Y): ")
if inputString == 'q':
gameOver = True
response = True
elif inputString == 'h':
for instruction in instructionsList:
print(instruction)
response = True
else:
try:
x,y = inputString.split()
assert int(x) <=60 and int(y) <=15
response = True
coordinate = True
except AssertionError:
print('Please enter a valid move')
if gameOver == True:
break
#whichAxis, axis =ocean.checkDistance(x,y)
#print(axis)
if coordinate == True:
axis = ocean.dropSonar(x,y)
ocean.drawBoard()
if axis == 'X':
print('Congratulations, you have found a treasure!')
if ocean.getTreasuresLeft() == 0:
print('Congratulations, you found all the treasure')
elif ocean.getSonarsLeft() == 0:
print('Sorry, you ran out of sonar devices, the remaining chests were: %s ' % str(ocean.getChests()))
How about separating the tests to be a little clearer:
input_string = input("Enter two numbers here: ")
if input_string == 'q':
do_quit()
elif input_string == 'h':
do_help()
else:
x,y = input_string.split()
That way you can test for your special cases, and process the x and y if they are not found.
may be this, for example:
a = input("text")
b = a.split()
if len(b) == 1:
if b[0] == 'q':
return
elif b[0] == 'h':
print 'it is help ... '
elif len(b) == 2:
# process for two inputted numbers
You can just separate the input:
# get the input
ipt = input("Enter two numbers here: ")
# check if your option is entered
if ipt == 'q' or ipt == 'h':
# do something
else:
x,y = ipt.split()

How can i make infite loop to ask user if he wants to input another number?

how can i make my code to ask user if wants to input another number? I could barely make my code run without errors, i am a toddler at python. I struggled a lot to write the code below. I know that stackoverflow is not a code writing service. But my little brain hurts now and i can't continue without help. I want to say simply "Do you want to convert another number?"
import math
# Global definition
#Base = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F]
Base = [str (x) for x in range (10)] + [chr (x) for x in range (ord ('A'), ord ('A') +6)]
h=[str(i) for i in range(10)]+["A","B","C","D","E","F"]
def BIN2DEC (string_num):
num = string_num
if num == 0:
return '0'
bin_str = ''
while num > 0:
bin_str = str(num % 2) + bin_str
num = num / 2
return bin_str
def HEX2DEC (string_num):
return str (int (string_num.upper (), 16))
# Dec2bin
# Decimal to binary
def dec2bin (string_num):
num = int (string_num)
mid = []
while True:
if num == 0: break
num, rem = divmod (num, 2)
mid.append (Base [rem])
return''. join ([str (x) for x in mid [:: -1]])
# Dec2hex
# Decimal to hexadecimal
def DEC2HEX (number):
n = long(number ,16)
if (n < 0):
print(0)
elif (n<=1):
print n,
else:
DEC2HEX( n / 16 )
x =(n%16)
if (x < 10):
print(x),
if (x == 10):
print("A"),
if (x == 11):
print("B"),
if (x == 12):
print("C"),
if (x == 13):
print("D"),
if (x == 14):
print("E"),
if (x == 15):
print ("F"),
# Hex2tobin
#The hexadecimal to bry
def HEX2BIN (hex_string):
s = int(hex_string, 16)
num_digits = int(math.ceil(math.log(s) / math.log(2)))
digit_lst = ['0'] * num_digits
idx = num_digits
while s > 0:
idx -= 1
if s % 2 == 1: digit_lst[idx] = '1'
s = s / 2
return ''.join(digit_lst)
# Bin2hex
# Binary to hexadecimal
def BIN2HEX (string_num):
return DEC2HEX (BIN2DEC (string_num))
my_num = 0
my_num = raw_input("Insert binary,decimal or hexadecimal:")
while(my_num != 0):
if my_num[0:2] == "0x" or my_num[0] == "x":
print HEX2BIN(my_num)
print HEX2DEC(my_num)
break
elif my_num[0:2] == "0b" or my_num[0] == "b" and all(x in "01" for x in my_num):
print""
print BIN2HEX(my_num)
print BIN2DEC(my_num)
break
else:
print dec2bin(my_num)
print HEX2BIN(my_num)
print long(my_num)
break
my_num = 0
my_num = raw_input(":")
print list(iter(lambda:raw_input("Enter Value, or 'q' to quit:"),"q"))
is my personal favorite way
iter makes an iterator (you need to look it up)
it takes an optional no-argument function that it will continually call until it receives the second argument

Categories