GUI in python programing - python

the fallowing is a tic tak toe game code in python, can some one show me how i can make it in GUI form with a reset option and shows who wins at the end. like X win or O win?
board = " 1 | 2 | 3\n-----------\n 4 | 5 | 6\n-----------\n 7 | 8 | 9"
.
checkboard=[1,2,3,4,5,6,7,8,9,1,4,7,2,5,8,3,6,9,1,5,9,3,5,7]
spaces=range(1,10)
def moveHandler(board,spaces,checkboard,player,n):
if player==1:
check="X"
else:
check="O"
while spaces.count(n)==0:
print "\nInvalid Space"
n=playerinput(player)
spaces=spaces.remove(n)
board=board.replace(str(n),check)
for c in range(len(checkboard)):
if checkboard[c]==n:
checkboard[c]=check
status = checkwinner(checkboard,check)
return board,status
def checkwinner(checkboard,check):
a,b,c=0,1,2
while a<=21:
combo = [checkboard[a],checkboard[b],checkboard[c]]
if combo.count(check) == 3:
status =1
break
else:
status =0
a+=3
b+=3
c+=3
return status
def playerinput(player):
try:
key = int(raw_input('\n\nPlayer ' + str(player) + ': Please select a space '))
except ValueError:
print "Invalid Space"
key = playerinput(player)
return key
while True:
player = len(spaces)%2 +1
if player == 1:
player = 2
else:
player =1
print "\n\n" + board
key = playerinput(player)
board,status =moveHandler(board,spaces,checkboard,player,key)
if status == 1:
print '\n\nPlayer ' + str(player) + ' is the winner!!!'
print board
break
elif len(spaces)==0:
print "No more spaces left. Game ends in a TIE!!!"
print board
break
else:
continue

Clearly you need to choose a GUI toolkit (Python supports many of them), use it to paint the board as a 3 x 3 grid of squares, and change the playerinput function to accept input by (e.g.) the current player double clicking on the empty square he or she wants to play in.
Then, you need to change the print statements to show information on the GUI surface.
The game however would be much better if it didn't try to control the flow of events but rather responded to events initiated by the players -- that's how real GUI apps should be done, rather than by minimal retrofitting of some interface on top of what's intrinsically designed as a command-line interactive procedure.
Each of these tasks is a substantial one, especially the overall refactoring I recommend in the last paragraph, and entirely depends in its details on what GUI toolkit you choose -- so you might want to start with that, and then generally break the question up into the various subtasks ("one question per question", since many of the latter may arise;-).
There are several SO questions on the subject of GUI choice for Python, so I recommend you study them rather than asking a new one. My personal favorite is PyQt (though more and more often I just do a simple browser-based interface with a local-only server powering it), but other popular ones include wxPython, Tkinter, PyGtk, and others listed here -- happy hunting!

Check out the python wiki for info about different GUI toolkits. I would recommend looking at wxPython, and going from there

Related

itertools.cycle(['eng', 'rus']).__next__ not works properly

Ayo, guys
Im started to learn python 2 days ago and started with simple Translator
My problem is:
I wanted to write "#" to the console, my values change, but I don't know how to achieve that "Toggle" effect, when when writing "#" is chekcing if language number 1 is enabled and I change it to language number 2 and vice versa, if Language number 2 is enabled then switch to Language number 1
I found a solution on the Internet by:
var = itertools.cycle(['1', '2']).__next__
However, I can't get langtoggle to give me values one by one
At the moment, I'm stuck on this moment, which gives me value number 2 and does not want to change it to value 1
Please tell me what am I doing wrong?
Thank you :)
import itertools
langtoggle = itertools.cycle(['eng', 'rus']).__next__
engstroke = 'ENGLISH > RUSSIAN'
russtroke = 'RUSSIAN > ENGLISH'
lstroke = engstroke
while True:
print (lstroke)
word = input('Введите слово: ')
if word == '#':
while True:
langtoggle()
if langtoggle() == 'eng':
lstroke = engstroke
if langtoggle() == 'rus':
lstroke = russtroke
break
to be honest, I need a solution what let me change to 1,2,3 and more values by same action so thats why I dont want to use boolean value for that problem
Also, I notice that "var()" cycling to next value even if im just checking this var in "if var() = 1"
that looks strange, but I dont understand a huge things in coding right now, so..
In your while block you're calling langtoggle() three times. Change this to be called only once.
Something like this:
import itertools
langtoggle = itertools.cycle(['eng', 'rus']).__next__
engstroke = 'ENGLISH > RUSSIAN'
russtroke = 'RUSSIAN > ENGLISH'
lstroke = eng
while True:
print (lstroke)
word = input('Введите слово: ')
if word == '#':
while True:
toggled = langtoggle()
if toggled == 'eng':
lstroke = engstroke
if toggled == 'rus':
lstroke = russtroke
break
This is your code but modified by setting toggled to the result of the first call to langtoggle(). Then the tests are looking at the value of toggled instead of separate calls they were making previously.

Creating Decision Tree for Simple Game

I am currently a new student learning python. This is my first real experience doing much computer coding. For my project I must create a fill in the blank quiz with three different levels of difficulty. Once the user chooses a difficulty the game should print a different paragraph based on the difficulty. Each section of the game works fine but I am having trouble creating the "difficulty chooser." No matter the difficulty I choose, the game rolls through the easy, medium, and the hard level in order and then crashes.
Below I have included the introductory text and the difficulty chooser. I would love some help. I am sure there are really obvious things I don't see. Thank you!
def introduction():
print '''Welcome to Kevin's European Geography Quizzes.
Test your knowledge of European geography. \n'''
difficulty = raw_input('''Do you want to play an easy, medium, or hard game?
Please type the number 1 for easy, 2 for medium, or 3 for hard.\n''' )
game_chooser(difficulty)
def game_chooser(difficulty):
cursor = 0
difficulty_choice = [easy_game(), medium_game(), hard_game()]
#each element of the above list links to a procedure and starts one of the
#mini-games.
while cursor < len(difficulty_choice):
if difficulty != cursor:
cursor += 1
else:
difficulty_choice[cursor]
break
You can do with if else if you only want to print something but if you have separate code block for each level then define a function for each level and use this pattern :
You can define the function blocks and call them basis on user input something like:
# define the function blocks
def hard():
print ("Hard mode code goes here.\n")
def medium():
print ("medium mode code goes here\n")
def easy():
print ("easy mode code goes here\n")
def lazy():
print ("i don't want to play\n")
# Now map the function to user input
difficulty_choice = {0 : hard,
1 : medium,
4 : lazy,
9 : easy,
}
user_input=int(input("which mode do you want to choose : \n press 0 for hard \n press 1 for medium \n press 4 for lazy \n press 9 for easy "))
difficulty_choice[user_input]()
Then invocation of function block will be:
difficulty_choice[num]()
Add a conditional for the input.
if difficulty == 'easy':
print("here is an easy game")
elif difficulty == 'medium':
print('here is a medium game')
elif difficulty == 'hard':
print('here is hard')
else:
print('Please enter valid input (easy, medium, hard)')
Under each if statement put your game code.
The reason your code goes through all the difficulties is because of this line:
difficulty_choice = [easy_game(), medium_game(), hard_game()]
When Python sees something like easy_game(), it calls the easy_game function and replaces it with the result. You don't want to call the function yet though, so you can take off the parenthesis to store just the function instead:
difficulty_choice = [easy_game, medium_game, hard_game]
This will mean you have to call the function after you take it out of the array.
As for the crash, when you use raw_input() you get a string back. That means when you type in the 1 to decide for an easy game, you get the character 1, which is represented by the number 49. That's why your code goes through everything and crashes: Your 1 is really a 49. In fact, if you type 1 < '1' into the interpreter, you'll get True back.
To fix that, you can pass the result of raw_input() to the int() function, which will parse it and give you the proper integer (or throw an exception if it can't be parsed). The last line of introduction would then look like game_chooser(int(difficulty)).
You could also skip most of the code of game_chooser by just indexing into the array (that's what they're for, after all):
def game_chooser(difficulty):
# the lack of parens here means you get the function itself, not what it returns
difficulty_choice = [easy_game, medium_game, hard_game]
#each element of the above list links to a procedure and starts one of the
#mini-games.
# note the parens to actually call the retrieved function now
difficulty_choice[difficulty]()

chatbot: how to correctly determine intents?

What are the usual techniques to determine the difference between the following intents, for example?
What is the current temperature?
In this case, the straight-up response will be the current temperature.
Is current temperature 22 degrees?
In this case, the appropriate response would be yes or no.
I am building a closed-domain chatbot (eg Siri) and am wondering if there are any techniques in Python that I can read about.
I once got into programming trying to understand how bots work. What a little world. I barely remember how I did mine but let's assume you build the chat based on events that your bot can read. A very basic way to determine what to answer to each event would be a huge list of IF ELIF stuff with nested behaviours (ideally split into methods).
def handleevent (message, user, date, font, whatever):
if "current temperature" in message:
send_text_to_chat("The temperature is 22 degrees")
elif "is current temperature" in message and "?" in message:
specific_temp_asked(message)
elif "potato" in message: # you could do hundred of behaviours, and nested ones.
if user == "apple":
send_text_to_chat("Hi apple!")
else:
send_text_to_chat("I am a potato bot")
elif "who am I?" in message: # example using the event data
send_text_to_chat("you are " + user)
else:
send_text_to_chat("Be more specific")
And then you would have to code each of the specific situations like this:
def specific_temp_asked(message):
temperature = None
split_message = message.split(" ")
for i in split_message:
try:
int(i)
temperature = i
break
except:
pass
if not temperature == None:
real_temperature = check_temp(somehow)
if real_temperature == temperature:
send_text_to_chat("Yes")
else:
send_text_to_chat("Nope")
Final note: This is by no means the best way to do it, but if you are learning I'll get the work done without being too complicated, and then you improve the code slowly.

My variable is not updating after changing another variable affecting it

So I'm working a quiz on Python as a project for an Intro to Programming course.
My quiz works as intended except in the case that the quiz variable is not being affected by the new values of the blank array. On the run_quiz function I want to make the quiz variable update itself by changing the blanks to the correct answer after the user has provided it.
Here's my code:
#Declaration of variables
blank = ["___1___", "___2___", "___3___", "___4___"]
answers = []
tries = 5
difficulty = ""
quiz = ""
#Level 1: Easy
quiz1 = "Python is intended to be a highly " + blank[0] + " language. It is designed to have an uncluttered " + blank[1] + " layout, often using English " + blank[2] + " where other languages use " + blank[3] + ".\n"
#Level 2: Medium
quiz2 = "Python interpreters are available for many " + blank[0] + " allowing Python code to run on a wide variety of systems. " + blank[1] + " the reference implementation of Python, is " + blank[2] + " software and has a community-based development model, as do nearly all of its variant implementations. " + blank[1] + " is managed by the non-profit " + blank[3] + ".\n"
#Level 3: Hard
quiz3 = "Python features a " + blank[0] + " system and automatic " + blank[1] + " and supports multiple " + blank[2] + " including object-oriented, imperative, functional programming, and " + blank[3] + " styles. It has a large and comprehensive standard library.\n"
#Answer and quiz assignment
def assign():
global difficulty
global quiz
x = 0
while x == 0:
user_input = raw_input("Select a difficulty, Press 1 for Easy, 2 for Medium or 3 for Hard.\n")
if user_input == "1":
answers.extend(["readable", "visual", "keywords", "punctuation"])
difficulty = "Easy"
quiz = quiz1
x = 1
elif user_input == "2":
answers.extend(["operating systems", "cpython", "open source", "python software foundation"])
difficulty = "Medium"
quiz = quiz2
x = 1
elif user_input == "3":
answers.extend(["dynamic type", "memory management", "programming paradigms", "procedural"])
difficulty = "Hard"
quiz = quiz3
x = 1
else:
print "Error: You must select 1, 2 or 3.\n"
x = 0
def run_quiz():
n = 0
global tries
global blank
print "Welcome to the Python Quiz! This quiz follows a fill in the blank structure. You will have 5 tries to replace the 4 blanks on the difficulty you select. Let's begin!\n"
assign()
print "You have slected " + difficulty + ".\n"
print "Read the paragraph carefully and prepare to provide your answers.\n"
while n < 4 and tries > 0:
print quiz
user_input = raw_input("What is your answer for " + blank[n] + "? Remember, you have " + str(tries) + " tries left.\n")
if user_input.lower() == answers[n]:
print "That is correct!\n"
blank[n] = answers[n]
n += 1
else:
print "That is the wrong answer. Try again!\n"
tries -= 1
if n == 4 or tries == 0:
if n == 4:
print "Congratulations! You are an expert on Python!"
else:
print "You have no more tries left! You can always come back and play again!"
run_quiz()
I know my code has many areas of improvement but this is my first Python project so I guess that's expected.
The problem is that your variable, quiz, is just a fixed string, and although it looks like it has something to do with blanks, it actually doesn't. What you want is 'string interpolation'. Python allows this with the .format method of str objects. This is really the crux of your question, and using string interpolation it's easy to do. I'd advise you to take some time to learn .format, it's an incredibly helpful function in almost any script.
I've also updated your code a bit not to use global variables, as this is generally bad practice and can lead to confusing, difficult to track bugs. It may also impair the uncluttered visual layout :). Here is your modified code, which should be working now:
quizzes = [
("""\
Python is intended to be a highly {} language.\
It is designed to have an uncluttered {} layout,\
often using English {} where other languages use {}
""", ["readable", "visual", "keywords", "punctuation"], "Easy"),
("""\
Python interpreters are available for many {}\
allowing Python code to run on a wide variety of systems.\
{} the reference implementation of Python, is {}\
software and has a community-based development model, as\
do nearly all of its variant implementations. {} is managed by the non-profit {}
""", ["operating systems", "cpython", "open source", "python software foundation"], "Medium"),
("""\
Python features a {} system and automatic {} and\
supports multiple {} including object-oriented,\
imperative, functional programming, and\
{} styles. It has a large and comprehensive standard library.
""", ["dynamic type", "memory management", "programming paradigms", "procedural"], "Hard")
]
#Answer and quiz assignment
def assign():
while True:
user_input = raw_input("Select a difficulty, Press 1 for Easy, 2 for Medium or 3 for Hard.\n")
if user_input == "1":
return quizzes[0]
elif user_input == "2":
return quizzes[1]
elif user_input == "3":
return quizzes[2]
else:
print "Error: You must select 1, 2 or 3.\n"
continue
break
def run_quiz():
n = 0
#Declaration of variables
blank = ["___1___", "___2___", "___3___", "___4___"]
tries = 5
print "Welcome to the Python Quiz! This quiz follows a fill in the blank structure. You will have 5 tries to replace the 4 blanks on the difficulty you select. Let's begin!\n"
quiz, answers, difficulty = assign()
print "You have selected {}.\n".format(difficulty)
print "Read the paragraph carefully and prepare to provide your answers.\n"
while n < 4 and tries > 0:
print quiz.format(*blank)
user_input = raw_input("What is your answer for {}? Remember, you have {} tries left.\n".format(blank[n], tries))
if user_input.lower() == answers[n]:
print "That is correct!\n"
blank[n] = answers[n]
n += 1
else:
print "That is the wrong answer. Try again!\n"
tries -= 1
if n == 4 or tries == 0:
if n == 4:
print "Congratulations! You are an expert on Python!"
else:
print "You have no more tries left! You can always come back and play again!"
run_quiz()
A little more on string interpolation:
You're doing a lot of "start of string " + str(var) + " end of string". This can be achieved quite simply with "start of string {} end of string".format(var)" - it even automatically does the str conversion. I've changed your quiz variables to have "{}" where either "__1__" etc should be displayed or the user's answer. You can then do quiz.format(*blank*) to print the 'most recent' version of the quiz. * here 'unpacks' the elements of blank into separate arguments for format.
If you find it more easy to learn with example usage, here are two usages of format in a simpler context:
>>> "the value of 2 + 3 is {}".format(2 + 3)
'the value of 2 + 3 is 5'
>>> a = 10
>>> "a is {}".format(a)
'a is 10'
I've also stored the information about each quiz in a list of tuples, and assign now has a return value, rather than causing side effects. Apart from that, your code is still pretty much intact. Your original logic hasn't changed at all.
Regarding your comment about objects:
Technically, yes, quizzes is an object. However, as Python is a 'pure object oriented language', everything in Python is an object. 2 is an object. "abc" is an object. [1, 2, 3] is an object. Even functions are objects. You may be thinking in terms of JavaScript - with all of the brackets and parentheses, it kind of resembles a JS Object. However, quizzes is nothing more than a list (of tuples). You might also be thinking of instances of custom classes, but it's not one of those either. Instances require you to define a class first, using class ....
A bit more on what quizzes actually is - it's a list of tuples of strings, lists of strings and strings. This is a kind of complicated type signature, but it's just a lot of nested container types really. It firstly means that each element of quizzes is a 'tuple'. A tuples is pretty similar to a list, except that it can't be changed in place. Really, you could almost always use a list instead of a tuple, but my rule of thumb is that a heterogenous collection (meaning stuff of different types) should generally be a tuple. Each tuple has the quiz text, the answers, and the difficulty. I've put it in an object like this as it means it can be accessed by indexing (using quiz[n]), rather than by a bunch of if statements which then refer to quiz1, quiz2, etc. Generally, if you find yourself naming more than about two variables which are semantically similar like this, it would be a good idea to put them in a list, so you can index, and iterate etc.
Only now have I read your question properly.
You first make your strings quiz1, quiz2 an quiz3.
You only do that once.
After that you change your blanks array.
But you don't reconstruct your strings.
So they still have the old values.
Note that a copy of elements of the blanks array is made into e.g. quiz1.
That copy doesn't change automagically after the fact.
If you want to program it like this, you'll have to rebuild your quiz1, quiz2 and quiz3 strings explicitly each time you change your blanks array.
General advice: Don't use so many globals. Use function parameters instead. But for a first attempt I guess it's OK.
[edit]
A simple modification would be:
Replace your quiz, quiz1, quiz2 and quiz3 by functions get_quiz (), get_quiz1 () etc. that get the most recent version, including the altered elements of blanks.
This modification doesn't make this an elegant program. But you'll come to that with a bit more experience.
A long shot in case you wonder (but don't try to bridge that gap in one step):
In the end Quiz will probably be a class with methods and attributes, of which you have instances.
To be sure: I think that experimenting like this will make you a good programmer, more than copying some ready to go code!

Any reason why my Python code is not showing up?

I am learning how to code in Python and using the IDLE, I have put in this code, however when I hit F5, nothing happens... no output occurs.
Is this due to maybe the fact that the code I have put in doesn't need an output? Or maybe I am saving it wrongly. Would love to know the reason as it is slightly upsetting.
X = "X" #This is to indicate one piece of the game
O = "O" #this is to indicate another piece of the game
EMPTY = "" # an empty square on the board.
TIE = "TIE" #represents a tie game
NUM_SQUARES = "9" #number of squares on the board
def display_instruct(): #this is a function with the name display_instruct.
"""display game instructions."""
print \
""" Welcome to the greatest challenge of all time: Tic-tac toe. This would be a showdown betweene your human brain
and my silcon processor You will mkae your move known by entering a number
0 | 1 | 2
---------
3 | 4 | 5
---------
6 | 7 |8
Prepare yourself, human. The ultimate battle is about to begin. \n """
def ask_yes__no(question):
"""Ask a yes or no question"""
response = None
while response not in ("y", "n"):
response = raw_input(question).lower()
return response
#this produces a function. It receives a question and thenn responds with an answer which is either yes or not
def ask_number(question, low, high):
"""Ask for a number within the range"""
response = None
while response not in range(low, high):
response - int(raw_input(question))
return response
#remember that when defining the functions, you have to put in colons. The user recieves a question and then has to give an answer.
def pieces():
"""Determine if player or computer goes first""" #docstrings are used to name the functions.
go_first = ask_yes_no("Do you requre the first move?y/n: ")
if go_first == "y": #important to have two equal signs because you are giving a variable a name. Notice that one function callled another.
print "\n Then take the first move, you will need it."
human = X
computer = 0
else:
print "\n Your bravery will beyour undoing .... I will go first."
computer = X
human = O
return computer, human
You need to define and call a main function
def main():
display_instruct()
#the rest of the code
if __name__ == "__main__":
main()
The reason your code doesn't run is because what you have is function definitions
def func() ...
and value assignments
x=5
To actually run something you will either need to define a main function that takes all the things you have defined and combines them in a meaningful way or append to the bottom of the code something similar to what you would write in the main function.

Categories