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
Related
The program should ask what its first coordinates are. Then movement is asked and its answer should be with
r,R,l,L,u,U,d,D.
Coordinate are input with a comma (x,y), and then again if 'u','d','l','r' are input then the x or y axis will increase or decrease.
'u' and 'd' for the y-axis; 'r' and 'l' for the x-axis.
def program_for_grid(x,y,where):
if where == 'r' or where == 'R':
# move x upp +
for r in range(len(where)):
r == 'r' or r == 'R'
x + 1
elif where == 'l' or where == 'L':
# move x down -
for l in range(len(where)):
l == 'l' or l == 'L'
x - 1
elif where == 'u' or where == 'U':
# move y up +
for u in range(len(where)):
u == 'u' or u == 'U'
y + 1
elif where == 'd' or where == 'D':
# move y down -
for d in range(len(where)):
d == 'd' or d == 'D'
y - 1
x_axis,y_axis = input('Initial position: ').split(',')
int_x_axix = int(x_axis)
int_y_axix = int(x_axis)
movement = input('Movement: ')
grid = program_for_grid(int_x_axix,int_y_axix,movement)
print(grid)
Something like this?
def delta(movement):
"""
Parse the string for movement instructions and
return resulting relative coordinates
"""
x = 0
y = 0
for letter in movement.lower():
if letter == "d": y -= 1
elif letter == "u": y += 1
elif letter == "l": x -= 1
elif letter == "r": x += 1
else:
print("warning: skipping undefined", letter)
return x, y
x_axis,y_axis = input('Initial position: ').split(',')
int_x_axix = int(x_axis)
int_y_axix = int(y_axis)
while True:
movement = input('Movement: ')
xdelta, ydelta = delta(movement)
int_x_axix += xdelta
int_y_axix += ydelta
print(f"resulting position: ({int_x_axix},{int_y_axix})")
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)
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.
I'm building out Battleships game in Python. I have a list and I'm trying to build a validation tool in Python to catch user inputs that are outside the 10x10 range of my list.
Here is the code:
from random import randint
player = "User"
board = []
board_size = 10
ships = {"Aircraft Carrier":5,
"Battleship":4,
"Submarine":3,
"Destroyer":3,
"Patrol Boat":2}
def print_board(player, board): # to print joined board
print("Here is " + player + "'s board")
for row in board:
print(" ".join(row))
def switch_user(player): # to switch users
if player == "User":
player = "Computer"
elif player == "Computer":
player = "User"
else:
print("Error with user switching")
for x in range(0, board_size): # to create a board
board.append(["O"] * board_size)
print_board(player,board)
def random_row(board): # generate random row
return randint(0, len(board) - 1)
def random_col(board): # generate random column
return randint(0, len(board[0]) - 1)
def user_places_ships(board, ships): # user choses to place its ships by providing starting co-ordinate and direction.
for ship in ships:
valid = False
while(not valid):
user_input_coordinates = input("Please enter row & column number for your " + str(ship) + ", which is " + str(ships[ship]) + "-cells long (row, column).")
ship_row, ship_col = user_input_coordinates.split(",")
ship_row = int(ship_row)
ship_col = int(ship_col)
user_input_dir = input("Please enter direction for your " + str(ship) + ", which is " + str(ships[ship]) + "-cells long (h for horizontal or v for vertical).")
valid = validate_coordinates(board, ships[ship], ship_row, ship_col, user_input_dir)
if not valid:
print("The ship coordinates either outside of" , board_size, "X" , board_size, "range, overlap with or too close to another ship.")
place_ship(board, ships[ship], ship_row, ship_col, user_input_dir)
print("You have finished placing all your ships.")
def validate_coordinates(board, ship_len, row, col, dir): # validates if the co-ordinates entered by a player are within the board and don't overlap with other ships
if dir == "h" or dir == "H":
for x in range(ship_len):
if row-1 > board_size or col-1+x > board_size:
return False
elif row-1 < 0 or col-1+x < 0:
return False
elif board[row-1][col-1+x] == "S":
return False
elif dir == "v" or dir == "V":
for x in range(ship_len):
if row-1+x > board_size or col-1 > board_size:
return False
elif row-1+x < 0 or col-1 < 0:
return False
elif board[row-1+x][col-1] == "S":
return False
return True
def place_ship(board, ship_len, row, col, dir): # to actually place ships and mark them as "S"
if dir == "h" or dir == "H":
for x in range(ship_len):
board[row-1][col-1+x] = "S"
elif dir == "v" or dir == "V":
for x in range(ship_len):
board[row-1+x][col-1] = "S"
else:
print("Error with direction.")
print_board(player,board)
user_places_ships(board,ships)
If a user enters "10,10" for ship coordinates and "h" for horizontal direction, then Python generates the following error message:
Traceback (most recent call last): File "C:/Users/Elchin's PC/Downloads/battleships game.py", line 85, in <module>
user_places_ships(board,ships) File "C:/Users/Elchin's PC/Downloads/battleships game.py", line 49, in user_places_ships
valid = validate_coordinates(board, ships[ship], ship_row, ship_col, user_input_dir) File "C:/Users/Elchin's PC/Downloads/battleships game.py", line 62, in validate_coordinates
elif board[row-1][col-1+x] == "S": IndexError: list index out of range
I know that the error is in this line:
elif board[row-1][col-1+x] == "S":
return False
But I don't know how to fix it. Could you please help me figure out the solution?
If a list has length n, you can access indices from 0 to n-1 (both inclusive).
Your if statements however check:
if row-1+x > board_size or col-1 > board_size: # greater than n
return False
elif row-1+x < 0 or col-1 < 0: # less than 0
return False
elif board[row-1+x][col-1] == "S":
return False
So as a result, if we reach the last elif part, we have guarantees that the indices are 0 < i <= n. But these should be 0 < i < n.
So you should change the first if statement to:
if row-1+x >= board_size or col-1 >= board_size: # greater than or equal n
return False
elif row-1+x < 0 or col-1 < 0: # less than 0
return False
elif board[row-1+x][col-1] == "S":
return False
You can make the code more elegant by writing:
if not (0 < row-1+x < board_size and 0 < col-1 < board_size) or \
board[row-1+x][col-1] == "S":
return False
I am trying to make a program:
simulates a random walk
animates the walk using cs1graphics
starts on center block which is black
takes random steps, never been stepped on turns red, repeat step turns blue.
import random
from cs1graphics import *
from time import sleep
def animationWalk(walk):
print("Animation of Random Walk: ", end = "\n")
window = Canvas(250, 250)
window.setTitle('Random Walk in Manhattan')
for y in range(10) :
for x in range(10) :
cue = Square()
cue.setSize(50)
cue.moveTo(x*25, y*25)
window.add(cue)
(x,y)= (6,6)
squares = Square()
squares.setSize(25)
squares.moveTo((x*25)-14, (y*25)-13)
squares.setFillColor('black')
window.add(squares)
been = Square()
been.setSize(25)
been.moveTo((x*25)-14, (y*25)-13)
window.add(been)
for direction in range (len(walk)):
if walk[direction] == 'N':
#y -= 1
(x,y)=(x,y-1)
elif walk[direction] == 'E':
#x += 1
(x,y)=(x+1,y)
elif walk[direction] == 'S':
#y += 1
(x,y) =(x,y+1)
elif walk[direction] == 'W':
#x -= 1
(x,y) = (x-1,y)
been.setSize(25)
been.moveTo((x*25)-14, (y*25)-13)
been.setFillColor('red')
cue.setSize(25)
sleep(0.25)
cue.moveTo((x*25)-14, (y*25)-13)
cue.setFillColor('blue')
def randomWalk(x,y):
block = []
for i in range (x):
block.append([])
for i in block:
for j in range(y):
i.append(0)
position = (x//2, y//2)
h = position[0]
v = position[1]
walk = ''
block[h][v] += 1
while (h != -1) and (h != (x-1)) and (v != -1) and (v != (y-1)):
directions = random.randrange(1,5)
if directions == 1:
v += 1
walk = walk + 'E'
elif directions == 2:
h += 1
walk = walk + 'S'
elif directions == 3:
v -= 1
walk = walk + 'W'
elif directions == 4:
h -= 1
walk = walk + 'N'
block[h][v] += 1
print("Starting at Center (", x//2, ",", y//2, ")")
print("Walking Directions: ", walk)
print("Track of Random Walk:", end = "\n")
for entry in block:
print(entry)
animationWalk(walk)
def main(): ## define main program
x = 10
y = 10
randomWalk(x,y)
main()
The color of a square is supposed to change to red when it is visited, blue when it is revisited and is changed back to red when it is passed. I cant get the blocks to maintain the color after it has been stepped off of.