clearing the terminal for my python text adventure - python

working with the current version of python after a quick google search and a perusal of stack overflow I'm not seeing what I'm looking for. I'm trying to find a way to clear the screen with every new print to the screen. So you would get the intro text for a room and there is a monster in the room so when you press a to attack it would delete the intro text and the new text saying what weapon you used and how much damage you did would be printed. then when the monster dies you the damage prompts would go away and you would get the dead enemy empty room text with the press these keys to go a direction text. the current version of my game is here https://github.com/GusRobins60/AdventureGame.git hopefully that will give you an idea of the text i'd be displaying. thanks for any help.

For windows you can use a lambda function to easily create an anonymous function which you can use to clear the terminal again and again:
clear = lambda: os.system('cls')
clear()
Or if you're on Linux then swap 'cls' with 'clear'.

Are you using windows? If so, you can try:
import os
os.system('cls')
Or something similar after each page is complete and needs to be cleared.

To clear the terminal using ANSI escape codes:
import sys
sys.stdout.write("\33[H\33[2J") #"\33" is the ESC character
sys.stdout.flush()
\33[H moves the cursor to the top left of the terminal, and \33[2J clears the screen. Using sys.stdout.write here instead of print avoids writing a newline, so the cursor stays on the first line of the screen, instead of being on the second line when using print().

Related

Left click detection with ursina

I'm using ursina to make a game, and I want to detect a left click so that I can shoot. So, here's my code :
def update(self):
if held_keys['t']:
print("it works !")
Whenever I press 't', it prints 'it works !', and if I hold it, as long as it's held, the message is printed. Great ! But now, if I try with 'left mouse down' for my key, it doesn't work anymore !
My code would then be :
def update(self):
if held_keys['left mouse down']:
print("it works !")
So, the problem here is clearly the 'left mouse down' argument. But I'm sure it is the correct syntax :
according to the documentation (https://www.ursinaengine.org/cheat_sheet.html#Keys)
and according to another test I made with it, where it worked (in another situation)
So, the syntax of my argument is correct, my code is correct. Where is the error located then ? Is there a specific way to handle the mouse, different than the keyboard ? I really don't think so, that's why I'm kinda confused here.
The way to debug this would be to print the held_keys dict to see what it contains. The correct name is 'left mouse'. It is that way because the mouse button names are named differently than other keys and are mostly there to make code changes easier. Mouse buttons aren't keys after all.
However, what you could do is check mouse.left instead.

Getting input in python via the same window?

I would like to know how to get user input in python without using the command line or an input box.
Let me explain. I do not want to do this
#All code is python 3
name=input("What is your name?")
Why? When running scripts, the command line is not auto-focused. Furthermore, it pops up another window, something I do not want because I can't hit escape to close it in a hurry (Something which you may want to do if you're playing a game).
What have I tried?
I looked at WX and it's dialog function, something like this:
import wx
app=wx.App()
def text_entry(title,message):
result=None
dlg=wx.TextEntryDialog(None, message,title)
if dlg.ShowModal()==wx.ID_OK: result=dlg.GetValue()
dlg.Destroy()
return result
text_entry("Text entry","Enter something here")
While this works, it pops up another window which again, I do not want. However, it is closer to what I am ultimately looking for, because I can hit escape to make it go away.
I have tried using pygame and it's key.get_pressed() function, but it inserts a lot of the same letter into the entry, even if I gently tap the key. Also, when I implemented it into the project, it can only pick up on normal letters. Writing 26 if statements to detect key presses for a single letter with or without the shift key seems a little counter intuitive.
Finally, I am a bit hesitant to try tkinter. I happen to be blind, and from what I read, tk is very visual, which makes me concerned that it won't play nicely with my screen reader (NVDA).
So, I'm here. After searching on google for "getting input without using command line in python 3", "input in the same window", and "input without using input()" yielded nothing.
To recap, I want to accept user input without using the input() function, and without any additional windows popping up for the duration of me doing so.
Thank you.
What about this solution using the msvcrt module. At any time if you press escape then the program will exit. Python sys.exit(), and built-ins exit() and quit() all call raise SystemExit so this is just one less call to perform. If you press the enter or return key then the while loop ends and you can use the keys that were pressed later in your program as they are stored in the variable user_input. The print at the end just proves that the pressed keys are stored in user_input variable and the input() function simply to leave the window open so you can see it working.
import msvcrt
user_input = b''
while True:
pressed_key = msvcrt.getche() # getch() will not echo key to window if that is what you want
if pressed_key == b'\x1b': # b'\x1b' is escape
raise SystemExit
elif pressed_key == b'\r': # b'\r' is enter or return
break
else:
user_input += pressed_key
print('\n' + user_input.decode('utf-8')) # this just shows you that user_input variable can be used now somewhere else in your code
input() # input just leaves the window open so you can see before it exits you may want to remove
So after doing some more research, I found this:
https://codeload.github.com/Nearoo/pygame-text-input/zip/master
I think this is what I am looking for, though it still needs to be slightly modified. Thank you for the assistance

how do I print a title for the top of my running program to continuously be visible for a code that prints and runs an endless amount of data?

Example: (to stay visible on the running program, able to view it at anytime if needed to scroll to the top)
print("this is my title")
print("here is my sub title")
count = 0
while count < 5000:
print("hello")
count = count + 1 # or count += 1
My code runs for as long as I set it too, that's not the problem. But when the program runs, it never shows the top printed title, or if I were to stop the program for a moment and physically scroll to the top, that printed title and other various text isn't visible.
How do I fix this to where, even if I wanted to print a million items, I could still see the printed title and printed information at the top?
First a useful non python way:
If you run a script (say my_long_print_script.py) from the terminal you can use less (in linux and osx for sure):
python my_long_print_script.py | less
then use enter to scroll down and q to quit.
Writing to stdout in python
In python you can directly write to stdout and 'overwrite' your previous output. This can lead to some sort of progress bar behaviour, I'm not sure this is what you want, here is an example:
# content of my_long_print_script.py:
import sys
from time import sleep
sys.stdout.write('This title should stay\n')
sys.stdout.write('this subtitle too\n')
for count in xrange(100):
sleep(0.1)
sys.stdout.write('{0}\r'.format(count))
sys.stdout.flush()
When you run this as a script (so you type python my_very_long_print_script.py in the terminal) the two title lines will persist and below a single line will continuously be updated.
FYI: I added the sleep because the count changes too quickly otherwise.
Hope this was somehow useful.
You'll probably want to use python's curses library. This is how you create "windows" that can be redrawn in-place.
I wrote a CLI version of 2048 that would scroll the terminal every time I output the game's board after a move. Using curses, I can now just overwrite the previous board without any scrolling.
Basically you'll want to initialize a new curses window object, set your output string to "My Title Here" and issue a window.redraw() command at (0,0) every time your program iterates.

Tkinter, help a noob understand Tk's loops

I am Python 3 noob creating a checkers game, I have a bunch of functions... and my game's loop is as follows:
while EndGame==0:
PrintBoard()
PrintBoardGui()
print("################","\n","Player 1","\n","################","\n")
Player=1
PlayerSelectPiece()
MovePiece()
PrintBoard()
PrintBoardGui()
print("################","\n","Player 2","\n","################","\n")
Player=2
if NbrPlayer==2:
PlayerSelectPiece()
else:
AiSelectPiece()
MovePiece()
PrintBoardGui() that I run at the beggining of each turn and creates a Tkinter window and draws the board on a new Canvas in a Tkinter Frame.
After that, I have to close the window in order for the program to continue.
I know this is a sub-optimal solution.
I have looked around trying to understand Tkinter's loops and read a bit about the after() function but i really don't know how I could implement it in my code.
Ultimatly I would like my Tkinter window to stay open (mabye disabled or something) while I input stuff in the console to move the pieces. Can you help me?
At first, how do you want to interact with your game ?
With text in the console ?
With buttons ?
With keyboard/mouse event ?
The "after" method is used to refresh your screen after an amount of time.
It will call the method that you pass through the parameters.
You shouldn't have to put an infinite loop in it. But you will have to check with a simple condition the game ending, to display another screen.
If you have to use the console entry, it can be a bit hard for a beginner to manage the GUI update and the console.
I am not sure what ur question was but, If you would want to run the code forever (until you stop it). you would have to use the while loop like this:
while "thing" == True:
PrintBoard()
PrintBoardGui()
print("################","\n","Player 1","\n","################","\n")
Player=1
PlayerSelectPiece()
MovePiece()
PrintBoard()
PrintBoardGui()
print("################","\n","Player 2","\n","################","\n")
Player=2
if NbrPlayer==2:
PlayerSelectPiece()
else:
AiSelectPiece()
MovePiece()
thing = False
at the end you change thing to False otherwise it would be infinite and it would bug.

Unwanted output in simple python script

Hello i'm starting with python on a RPI B+, i made a simple while loop but i'm getting weird output.
#!/usr/bin/python
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(3,GPIO.OUT)
while 1:
print "LED OFF"
GPIO.output(3,GPIO.LOW)
time.sleep(1)
print "LED ON"
GPIO.output(3,GPIO.HIGH)
time.sleep(1)
When GPIO3 is LOW it repeatedly outputs ^[[B until it's HIGH again.
The letter B changes depending on the pin i'm using.
Why is this happening? It looks like it is registering a button press, but i'm certainly not pressing any buttons nor do i have any input on the GPIO.
I tried another keyboard but it didn't make a difference.
This is the output i'm getting from this :
LED OFF
^[[B^[[B^[[B^[[B^[[B^[[B^[[B^[[B^[[B^[[B^[[B^[[B^[[B^[[B^[[B^[[B^[[BLED ON
^[[BLED OFF
^[[B^[[B^[[B^[[B^[[B^[[B^[[B^[[B^[[B^[[B^[[B^[[B^[[B^[[B^[[B^[[B^[[BLED ON
^[[BLED OFF
^[[B^[[B^[[B^[[B^[[B^[[B^[[B^[[B^[[B^[[B^[[B^[[B^[[B^[[B^[[B^[[B^[[BLED ON
^[[BLED OFF
I should note that the LED's do blink correctly.
EDIT :
When i switch focus to the text editor while the program runs, the output is normal but the down button gets pressed which causes the cursor inside the text editor to go down.
I'm starting to think this is a OS problem, i'm using the Porta Pi image, i use that img for my arcade cabinet so i thought i might aswell use it for this.
I'm starting with Python on a RPI B++ too. Lots of fun!! But anyway: this won't solve your problem I guess, but I was asking myself while looking at your script: shouldn't you put tabs before all lines after the while?
Me again, looking over a few of my scripts for RPi, I think your output syntax is off. As in:
GPIO.output(3,GPIO.LOW)
Should be:
GPIO.output(3,LOW)
I think that's why my suggestion of 1,0,True,False wasn't working. These shouldn't have "GPIO." In front of them.
Let me know if that works
-Cheers

Categories