Sublime Forum

Run code with user input

#1

Beginner programmer here.

I’ve created a game of battleships in python (with the help of code academy) and it requires a user input to guess the row and column of your attack. Is there a way of running the code in sublime text in order to input or do I have to open the file in a command line. If I have to open it in a command line, is there an easy way to open it from sublime text?

1 Like

#2

Here an simple example, howto ask the user:

class YourOwnCommand(sublime_plugin.WindowCommand):  # maybe also .TextCommand or .ApplicationCommand
    def run(self):
		# call the methode with user input panel
        self.question_one()

    def question_one(self):
        self.window.show_input_panel("This is question one",  # caption, initial_text, on_done, on_change, on_cancel
            "Initial text", self.on_answer_one, None, None)      

    def on_answer_one(self, user_input):
        if user_input != '':
            # user_input is the given answer, you can use it now
        
		self.question_two()
		
	def question_two(self):
		self.window.show_input_panel("This is question two", 
			"Initial text", self.on_answer_two, None, None)

    def on_answer_two(self, user_input):
        if user_input != '':
            # user_input is the given answer, you can use it now
			
	# and so on ....

For row and column you need only one interaction with user. Comma seperated answer for both.

0 Likes

#3

In this example, how could i print the user inputted value?

0 Likes

#4

user_input holds the value from input, so you can use this so: print(user_input)

0 Likes

#5

You can make a new build system for Running python program which will execute the program in a terminal and you will be able to give input to the program.
Go to Tools>>Build System>>New Build System
You can make a new Python build system for sublime-text to give input.
Go to Tools >>Build System>>New Build System

{
   "shell_cmd": "gnome-terminal -- bash -c \"python3 -u $file;echo;echo Press Enter to exit...;read\"",
   "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
   "selector": "source.python",
   
}

Save the file with name Run or python-run
Select your build using CTRL+Shift+B.

0 Likes