The while loop only runs once and exits as though the condition has been met, however, when debugging for whether the condition has been met externally (after the loop) it has not.
Here is my code:
iFile = open("snakein.txt")
line = iFile.readline()
finXStr,finYStr = line.split()
finX = int(finXStr)
finY = int(finYStr)
moves = []
snkX = 0
snkY = 0
while snkX != finX and snkY != finY:
if finX > 0 and finX != snkX:
moves.append("R")
snkX += 1
print("x moves")
elif finX < 0 and finX != snkX:
moves.append("L")
snkX -= 1
print("x moves")
elif finX == snkX:
moves.append("L")
snkX -= 1
print("x moves")
if finY < 0 and moves[-1] == "R":
moves.append("R")
snkY -= 1
print("y moves")
elif finY < 0 and moves[-1] == "L":
moves.append("L")
snkY -= 1
print("y moves")
elif finY > 0 and moves[-1] == "R":
moves.append("L")
snkY += 1
print("y moves")
elif finY > 0 and moves[-1] == "L":
moves.append("R")
snkY += 1
print("y moves")
elif finY == snkY:
moves.appebd("L")
snakeY -= 1
print("y moves")
output = moves
oFile = open("snakeout.txt", "w")
oFile.write(str(output))
The program is trying to make a "snake" move in the most efficient way to a specific target via certain moves, on a "cartesian plane" like setting.
It looks like while snkX != finX or snkY != finY: might make more sense in your context...
Related
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'm doing an interactive map and after reading on the Internet, I'm trying to develop my learn towards an efficient way of programming. I wonder, is there a way to write more efficient this kinds of if_elif tree's ? I've read that one way is to make every conditions a def and store the conditions in a tuple ( 'cause is more efficiente than a list, and the values won't change). I've considered using ternary operator but don't know if is gonna be more efficient.
if direction == "w":
point[POS_Y] -= 1
elif direction == "s":
point[POS_Y] += 1
elif direction == "a":
point[POS_X] -= 1
elif direction == "d":
point[POS_X] += 1
Here's the code:
POS_X = 0
POS_Y = 1
MAP_WIDTH = 20
MAP_HEIGHT = 15
point = [3,7]
while 1: # i've read that Python is more efficient using a 1 instead of a True
# def player_movement(point):
print('+' + '-' * MAP_WIDTH * 3 + '+')
for coordinate_y in range(MAP_HEIGHT):
print('|',end='')
for coordinate_x in range(MAP_WIDTH):
if point[POS_X] == coordinate_x and point[POS_Y] == coordinate_y:
print(' #',end='') # it works with ' # ' as well, but in Visual Code doesn't see though
else:
print(' ',end='')
print('|')
print('+' + '-' * MAP_WIDTH * 3 + '+')
# player_movement([3,8])
direction = readchar.readchar().decode()
if direction == "w":
point[POS_Y] -= 1
elif direction == "s":
point[POS_Y] += 1
elif direction == "a":
point[POS_X] -= 1
elif direction == "d":
point[POS_X] += 1
If you have python 3.10 and above you can use the switch statement.
Here is an example:
status = 404
def http_error(status):
match status:
case 400:
return "Bad request"
case 404:
return "Not found"
case 418:
return "I'm a teapot"
case _:
return "Something's wrong with the internet"
This is called structural pattern matching and the link to the docs are here: https://docs.python.org/3.10/whatsnew/3.10.html#pep-634-structural-pattern-matching
As mentioned in the comments, this is no faster that if, elif statements from previous versions. So is important to mention.
After doing a quick test (python version 3.10.0) it seems that elif takes the most time, match comes second and using a dict is the fastest way.
test_elif
def test_elif():
direction = random.choice(['w','a','s','d'])
if direction == "w":
point[1] -= 1
elif direction == "s":
point[1] += 1
elif direction == "a":
point[0] -= 1
elif direction == "d":
point[0] += 1
return
test_match
def test_match():
direction = random.choice(['w','a','s','d'])
match direction:
case "w":
point[1] -= 1
case "s":
point[1] += 1
case "a":
point[0] -= 1
case "d":
point[0] += 1
return
test_dict
def test_dict():
direction = random.choice(['w','a','s','d'])
md = modifiers[direction]
point[md[0]] += md[1]
return
setup
import random
modifiers = {
"w": (1, -1),
"s": (1, +1),
"a": (0, -1),
"d": (0, +1)
}
point = [0,0]
Tested with timeit.timeit(funcntion_call, setup=setup, number=1000000)
test_elif: 0.1586214000126347 seconds
test_match: 0.1482315000030212 seconds
test_dict: 0.13923519995296374 seconds
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
Simple football simulation for my class project. I simplified a lot of the rules and aspects of the game, so everything isn't very accurate compared to an actual football game. However, When I try running my function, only the line of code which prints the name of the QB throwing to the receiver prints. For example when I run it only, "Jared Goff throws to Brandin Cooks for 33 yards!" shows up in the display. How can I get the whole function to run/print? Not sure where I went wrong.
import random
rams_qb = ["Jared Goff"]
patriots_qb = ["Tom Brady"]
rams_receivers = ["Cooper Kupp", "Brandin Cooks"]
patriots_receivers = ["Julian Edelman", "Josh Gordon"]
rams_score = 0
patriots_score = 0
quarter_time = 900
def remaining_time():
global quarter_time
global rams_score
global patriots_score
if quarter_time > 0:
if random.randint(0,100) < 50:
return rams_possesion()
else:
return patriots_possesion()
elif quarter_time == 0:
if rams_score > patriots_score:
print ("Rams Win!")
else:
print ("Patriots Win!")
def rams_possesion():
global quarter_time
global rams_score
rams_ball_position = 50
rams_downs = 1
if rams_ball_position == rams_ball_position + 10:
rams_downs = 1
else:
rams_downs += 1
if rams_ball_position == 100:
rams_score == rams_score + 6
print ("RAMS TOUCHDOWN!")
return rams_fieldgoal
if rams_downs <= 4:
rams_yardage_gained = random.randint(0,50)
print ((random.choice(rams_qb)),("throws to"),
(random.choice(rams_receivers)),("for"),(str(rams_yardage_gained)),
("yards!"))
rams_ball_position == rams_ball_position + rams_yardage_gained
quarter_time -= random.randint(0,30)
if rams_downs >= 5:
return patriots_possesion
def rams_fieldgoal():
global rams_score
if random.randint(0,100) < 83:
rams_score == rams_score + 1
print ("RAMS SCORE FIELDGOAL!")
else:
print ("RAMS MISS FIELDGOAL")
return patriots_possesion
def patriots_possesion():
global patriots_score
patriots_ball_position = 50
patriots_downs = 1
if patriots_ball_position == patriots_ball_position + 10:
patriots_downs = 1
else:
patriots_downs += 1
if patriots_ball_position == 100:
patriots_score == patriots_score + 6
print ("PATRIOTS TOUCHDOWN!")
return patriots_fieldgoal
if patriots_downs <= 4:
patriots_yardage_gained = random.randint(0,50)
print ((random.choice(patriots_qb)),("throws to"),
(random.choice(patriots_receivers)),("for"),(str(patriots_yardage_gained)),
("yards!"))
patriots_ball_position == patriots_ball_position +
patriots_yardage_gained
if patriots_downs >= 5:
return rams_possesion()
def patriots_fieldgoal():
global patriots_score
if random.randint(0,100) < 87:
patriots_score == patriots_score + 1
print ("PATRIOTS SCORE FIELDGOAL!")
else:
print ("PATRIOTS MISS FIELDGOAL")
return rams_possesion()
remaining_time()
My best guess here is that your comparisons are not taking into account the fact that the values can go over the target. For example, when checking yardage, you're checking for equality to 100, but you aren't guaranteeing that the value won't go over 100. You have a similar bug with checking if the quarter_time == 0 when it should be <= 0 to make sure it triggers.
I can't tell you if changing these comparisons will fix your program, but try these changes and comment how the behavior changes.
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.