Execute code whenever the space bar is pressed? - python

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)

Related

Move an image to a specific location

How to make it so the inserted image moves to a specific location and ends the program?
I tried using a counter loop but I still can't figure it out.
mr_krabs2.draw(win3)
key = win3.getKey()
counter = 0
while True:
counter +=1
if key == "w":
mr_krabs2.move(0,-10)
counter = count - 1
time.sleep(0.1)
if key == "s":
mr_krabs2.move(0,10)
time.sleep(0.1)
if key == "a":
mr_krabs2.move(-10,0)
time.sleep(0.1)
if key == "d":
mr_krabs2.move(10,0)
time.sleep(0.1)
for count in range (10):
print("a")
time.sleep(10)
win3.close
I solved my question.
# Variables for x and y to have a precise location.
x = 0.0
y = 0.0
while True:
key = win3.getKey()
# Key Movement.
if key == "w":
mr_krabs2.move(0,-10)
y = y + 10
print("\nx =",x,"y =",y,"\n")
if key == "s":
mr_krabs2.move(0,10)
y = y - 10
print("\nx =",x,"y =",y,"\n")
if key == "a":
mr_krabs2.move(-10,0)
x = x + 10
print("\nx =",x,"y =",y,"\n")
if key == "d":
mr_krabs2.move(10,0)
x = x - 10
print("\nx =",x,"y =",y,"\n")
# Making a hitbox
if (x < (59) and
x > (52) and
y < (4) and
y > (-6)):
time.sleep(5)
win3.close()
break

I'm having trouble with a Python Snake game using curses

Update:
I have fixed some parts of my code and now the snake game starts up :)
Its only when the snake eats the food that the score doesn't go up and the food does not appear in a random location
The guide that I have been using: https://www.youtube.com/watch?v=M_npdRYD4K0
snake = [(4, 12), (4, 11), (4, 10)]
food = [10, 30]
stdscr.addch(food[0], food[1], '%')
# game code or game logic
ESC = 27
key = KEY_RIGHT
score = 0
while key != ESC:
stdscr.addstr(0, 2, 'Score ' + str(score) + ' ')
stdscr.timeout(150 - (len(snake))//5 + len(snake)//10 % 120)
prevKey = key
event = stdscr.getch()
key = event if event != -1 else prevKey
if key not in [KEY_LEFT, KEY_DOWN, KEY_RIGHT, KEY_UP, ESC]:
key = prevKey
y = snake[0][0]
x = snake[0][1]
if key == KEY_UP:
y -= 1
if key == KEY_LEFT:
x -= 1
if key == KEY_RIGHT:
x += 1
if key == KEY_DOWN:
y += 1
snake.insert(0, (y, x))
# The snek will go through the boundaries, and out to the other side
if y == 0: y = 18
if y == 19: y = 1
if x == 0: x = 58
if x == 59: x = 1
# if the snek hits itself it will break the program
if snake[0] in snake[1:]:
print("You hit yourself...")
break
if snake[0] == food:
score += 1
food = ()
while food == ():
food = (randint(1, 18), randint(1, 58))
if food in snake:
food = ()
stdscr.addch(food[0], food[1], '%')
else:
last = snake.pop()
stdscr.addch(last[0], last[1], ' ')
stdscr.addch(snake[0][0], snake[0][1], '*')
curses.endwin()
print("\nYour final score: %s" % score)

All cells in Conway's game of life are alive

I tried to implement Conway's game of life in Python-3.6 with this code:
import numpy as np
import time
screen = np.zeros((25,25),dtype=np.int)
while True:
print(screen)
command = input('command?')
if command[0] == 'x':
command = command.split(' ')
x = int(command[0][1:])
y = int(command[1][1:])
if screen[x][y] == 0:
screen[x][y] = 1
else:
screen[x][y] = 0
elif command == 'start':
break
while True:
for x in range(len(screen)):
for y in range(len(screen[x])):
neighbors = 0
if x != len(screen)-1:
neighbors += screen[x+1][y]
if x != 0:
neighbors += screen[x-1][y]
if y != len(screen[x])-1:
neighbors += screen[x][y+1]
if y != 0:
neighbors += screen[x][y-1]
if x != len(screen)-1 and y != len(screen[x])-1:
neighbors += screen[x+1][y+1]
if x != 0 and y != 0:
neighbors += screen[x-1][y-1]
if 0 and y != len(screen[x])-1:
neighbors += screen[x-1][y+1]
if x != len(screen)-1 and y != 0:
neighbors += screen[x+1][y-1]
if screen[x][y] == 0 and neighbors == 3:
screen[x][y] = 1
elif screen[x][y] == 1 and neighbors < 2:
screen[x][y] == 0
elif screen[x][y] == 1 and neighbors > 3:
screen[x][y] == 0
elif screen[x][y] == 1 and neighbors == 2 or 3:
screen[x][y] = 1
print(screen)
time.sleep(0.1)
The Problem is that when I try to run this code with any figure, all the cells are immediately set to 1 in the first generation and won't die off.
Can someone tell me were the issue in my code is and how to solve it?
Your problem seems to be here:
elif screen[x][y] == 1 and neighbors == 2 or 3:
You can't do that (well, you can, but it doesn't do what you expect). Instead try:
elif screen[x][y] == 1 and neighbors in (2 , 3):
(or in {2, 3}).
Check this question for more information.

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()

Python battleship, double the trouble

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.

Categories