0

i am trying to have a loop that keeps functioning until something is inputted which will break the loop. However if i put in 'stop = input()' in the loop then it has to go through that first before doing anything else. my code is like this: (it uses some minecraft commands. basically im trying to make a block move down a 20X20 square and have it be able to stop in the middle on command)

from mcpi import minecraft
mc=minecraft.Minecraft.create()
from time import sleep
pos=mc.player.getTilePos
x=pos.x
y=pos.y
z=pos.z
mc.setBlocks(x-10,y,z+30,x+10,y+20,z+30,49)
BB=0
while BB<20:
    BB=BB+1
    sleep(.7)
    mc.setBlock(x,y+(20-BB),z+30,35)
    mc.setBlock(x,y+(21-BB),z+30,49)
    stop=input()
    if stop=='stp':
        break

how do i keep the loop going until someone inputs 'stp'? because currently it will move one block then stop and wait until i input something. The loop works if i take out the last three lines.

Unihedron
  • 10,601
  • 13
  • 59
  • 69
  • Possible duplicate of [What's the simplest way of detecting keyboard input in python from the terminal?](http://stackoverflow.com/questions/13207678/whats-the-simplest-way-of-detecting-keyboard-input-in-python-from-the-terminal) – Pynchia Oct 17 '15 at 06:34

2 Answers2

0

Whenever you run into input() in your code, Python will stop until it receives an input. If you're running the script in your console, then pressing Ctrl+C will stop execution of the program. (I'll assume you are, because how else would you be able to input 'stp'?)

eyqs
  • 196
  • 4
  • 7
0

You can run your logic in a different thread and signal this thread whenever you get an input.

from mcpi import minecraft
import threading

mc=minecraft.Minecraft.create()
from time import sleep
pos=mc.player.getTilePos
stop = False

def play():
    x=pos.x
    y=pos.y
    z=pos.z
    mc.setBlocks(x-10,y,z+30,x+10,y+20,z+30,49)
    BB=0
    while BB<20:
        BB=BB+1
        sleep(.7)
        mc.setBlock(x,y+(20-BB),z+30,35)
        mc.setBlock(x,y+(21-BB),z+30,49)
        if stop:
            break

t = threading.Thread(target=play)
t.start()
while True:
    s = input()
    if s == 'stp':
        stop = True # the thread will see that and act appropriately
glglgl
  • 85,390
  • 12
  • 140
  • 213