I am writing a quiz in python tkinter and when the user click on the answers if the answer is wrong the correct answer text color is changed to green I got that working but when I add the disable function so the user can't answer the question again it's not showing the correct answer in green.
def check(self, guess):
#compares the guess to the correct answer
print ("guess " + guess)
correct = self.problems[self.counter].correct
print ("correct " + correct)
self.btnA.config(state='disabled')
self.btnB.config(state='disabled')
self.btnC.config(state='disabled')
self.btnD.config(state='disabled')
if guess == correct:
#update ans
if guess == "A":
self.astatus["text"] = "✓"
elif guess == "B":
self.bstatus["text"] = "✓"
elif guess == "C":
self.cstatus["text"] = "✓"
else:
self.dstatus["text"] = "✓"
self.marks+=10
else:
if guess == "A":
self.astatus["text"] = "x"
elif guess == "B":
self.bstatus["text"] = "x"
elif guess == "C":
self.cstatus["text"] = "x"
else:
self.dstatus["text"] = "x"
if correct == "A":
self.btnA["fg"] = 'green'
elif correct == "B":
self.btnB["fg"] = 'green'
elif correct == "C":
self.btnC["fg"] = 'green'
else:
self.btnD["fg"] = 'green'
Related
Im not sure why but my code does not display the contents of the variable for each colour selected when I ask it to print it after the loop has concluded. When the program runs, all it outputs is a blank line which no text outputted.
If anyone could give a pointer that'd be vert helpful, thanks.
def inputs(): firstColour = "" #Variables for each of the three colours determined by entered letters in for loop secondColour = "" thirdColour = "" patchSize = "" #States the number of patches in the grid
for i in range(3):
patchColour = input ("Please choose a colour: r, g, b, m, c, o: ").lower()
if patchColour == "r":
colour = "red"
print (colour)
elif patchColour == "g":
colour = "green"
print (colour)
elif patchColour == "b":
colour = "blue"
print (colour)
elif patchColour == "m":
colour = "magneta"
print (colour)
elif patchColour == "c":
colour = "cyan"
print (colour)
elif patchColour == "o":
colour = "orange"
else:
print("No valid input has been entered")
break
if i == 0:
colour == firstColour
elif i == 1:
colour == secondColour
elif i == 2:
colour == thirdColour
print(firstColour, secondColour, thirdColour)
This section:
if i == 0:
colour == firstColour
elif i == 1:
colour == secondColour
elif i == 2:
colour == thirdColour
Should be:
if i == 0:
firstColour = colour
elif i == 1:
secondColour = colour
elif i == 2:
thirdColour = colour
"==" is used for comparing if items are the same, "=" is used to assign a value to a variable. Additionally colour and firstColour etc... were the wrong way round. As You later print out firstColour you need to asign a value to it first
I have this problem in my python code which is a coinflip game, the problem is that when It asks, "Heads or Tails?" and I just say 1 or Heads(same for 2 and Tails) without quotation marks and with quotation marks, it does not give me an answer that I am looking for.
I've Tried using quotation marks in my answer which didn't seem to work either.
import random
money = 100
#Write your game of chance functions here
def coin_flip(choice, bet):
choice = input("Heads or Tails?")
coinnum = random.randint(1, 2)
if coinnum == 1:
return 1
elif coinnum == 2:
return 2
win = bet*2
if choice == "Heads" or "1":
return 1
elif choice == "Tails" or "2":
return 2
if choice == coinnum:
print("Well done! You have won " + str(win) + " Dollars!")
elif choice != coinnum:
print("Sorry, you lost " + str(bet) + " Dollars!")
coin_flip("Heads", 100)
The expected output was either "Well done! You have won 200 Dollars!" or "Sorry, you lost 100 Dollars!"
The first thing to note here is that your usage of return seems to be wrong. Please look up tutorials about how to write a function and how to use return.
I think this is what you were trying to do:
import random
money = 100
#Write your game of chance functions here
def coin_flip(choice, bet):
choice = input("Heads or Tails? ")
coinnum = random.randint(1, 2)
win = bet*2
if choice == "Heads" or choice == "1":
choicenum = 1
elif choice == "Tails" or choice == "2":
choicenum = 2
else:
raise ValueError("Invalid choice: " + choice)
if choicenum == coinnum:
print("Well done! You have won " + str(win) + " Dollars!")
else:
print("Sorry, you lost " + str(bet) + " Dollars!")
coin_flip("Heads", 100)
Now, lets go through the mistakes I found in your code:
return was totally out of place, I wasn't sure what you were intending here.
if choice == "Heads" or "1" is invalid, "1" always evaluates to true. Correct is: if choice == "Heads" or choice == "1":
elif choice != coinnum: is unnecessary, if it doesn't run into if choice == coinnum: a simple else: would suffice.
I am new to Pycharm, and Python as a whole, and for my first project I decided to do a random name/object selector which chooses a name from a pre-made variable of letters and prints that result.
I wanted to expand on this and have the user either use the default names in the code or add their own names to be used.
I gave it my best effort but when it came to the script running 1 of two functions I was unable to figure out how to do that.
Any help?
import string
import random
import os
letters = 'wjsdc' #*Default letters*
choice = random.choice(letters)
decision = input("Hello, use default? y/n")
print("You have chosen " + decision + ", Running function.")
def generator():
if decision == "y": #*Default function*
choice = random.choice(letters)
print("Name chosen is " + generator())
elif decision == "n": #*Attempted new function*
new_name1 = input("Please add a name")
new_name2 = input("Please add a name")
new_name3 = input("Please add a name")
new_name4 = input("Please add a name")
new_name5 = input("Please add a name")
if choice == "w":
finalname = new_name1
elif choice == "j":
finalname = new_name2
elif choice == "s":
finalname = new_name3
elif choice == "c":
finalname = new_name4
elif choice == "d":
finalname = new_name5
name = finalname
return name
print("Name chosen is " + name)
def generator(): #*Default function script*
if choice == "w":
finalname = "Wade"
elif choice == "j":
finalname = "Jack"
elif choice == "s":
finalname = "Scott"
elif choice == "d":
finalname = "Dan"
elif choice == "c":
finalname = "Conall"
name = finalname
return name
print("Name chosen is " + generator())
Your code is pretty weird, and I'm not sure what you are trying to achieve.
you define two functions generator; you should give them different names
instead of chosing from one of the letters and then selecting the "long" name accordingly, just chose from the list of names in the first place
you can use a list for the different user-inputted names
I'd suggest using something like this:
import random
def generate_name():
names = "Wade", "Jack", "Scott", "Dan", "Conall"
decision = input("Use default names? Y/n ")
if decision == "n":
print("Please enter 5 names")
names = [input() for _ in range(5)]
return random.choice(names)
print("Name chosen is " + generate_name())
I'm quite confused at why the option "B" or "C" doesn't work. You are supposed to be able to navigate the story by choosing any of the 3 options. The only option that works is "A". It's probably the smallest thing I have overlooked.
Click to See the Code Window
The program executes (From the Fuctions.py, SplashScreens()):
...
print(SplashScreen.Splash_Screen19)
cls()
Story_1_to_4(Text.Story_1,2,3,4)
Which runs this... (Located in Functions.py){Through = True}{Key = False}
def Story_1_to_4(Story_Num, Path1, Path2, Path3):
global Through
global Key
if Path1 == 3 and Path2 == 4 and Path3 == 10:
Key = True
while Through == True:
Choice = input(Story_Num)
if Choice == "A":
Choice = Path1
Through = False
elif Choice == "B":
Choice = Path2
Through == False
elif Choice == "C":
Choice = Path3
Through == False
else:
cls()
print(Text.Invalid_Syntax)
time.sleep(2)
cls()
ResetThrough()
Decision(Choice)
Story_1: (From Text.py)
Image of the Variable Story_1
And then Decision is... (Located in Functions.py)
def Decision(Choice):
cls()
if Choice == 1:
Story_1_to_4(Text.Story_1,2,3,4)
elif Choice == 2:
Story_1_to_4(Text.Story_2,3,4,10)
elif Choice == 3:
Story_1_to_4(Text.Story_3,5,6,4)
elif Choice == 4:
Story_1_to_4(Text.Story_4,7,8,9)
elif Choice == 5:
Story_Ending(Text.Story_5)
elif Choice == 6:
Story_Ending(Text.Story_6)
elif Choice == 7 and Key == True:
Story_Ending(Text.Story_7_With_Key)
elif Choice == 7 and Key == False:
Story_Ending(Text.Story_7_Without_Key)
elif Choice == 8:
Story_Ending(Text.Story_8)
elif Choice == 9:
Story_Ending(Text.Story_9)
elif Choice == 10:
Story_Ending(Text.Story_10)
For A, you set Through = False. For B and C you wrote Through == False which just evaluates an expression but doesn't assign Through.
I am following Charles Dierbach's book, Introduction to Computer Science using Python.
I am on chapter 5. I am trying to do this exercise on tic-tac-toe automate play.
I am having difficulties creating a function for the pc to select an empty box ([]).
Here is my code
import re
import random
def template():
mylst = list()
for i in range(0, 3):
my_temp = []
for j in range(0, 3):
my_temp.append([])
mylst.append(my_temp)
return mylst
def template_2(alst):
print()
al = ("A", "B", "C")
for a in al:
if a == "A":
print (format(a, ">6"), end="")
if a == "B":
print (format(a, ">5"), end="")
if a == "C":
print (format(a, ">5"), end="")
print()
for j in range(len(alst)):
print(str(j + 1), format( " ", ">1"), end="")
print(alst[j])
print()
def print_template(alst):
print()
al = ("A", "B", "C")
for a in al:
if a == "A":
print (format(a, ">6"), end="")
if a == "B":
print (format(a, ">4"), end="")
if a == "C":
print (format(a, ">3"), end="")
print()
for j in range(len(alst)):
print(str(j + 1), format( " ", ">1"), end="")
print(alst[j])
print()
def first_player(lst):
print()
print ("Your symbol is 'X'. ")
alpha = ("A", "B", "C")
#check it was entered correctly
check = True
temp_lst1 = []
while check:
correct_entry = False
while not correct_entry:
coord = input("Please enter your coordinates ")
player_regex = re.compile(r'(\w)(\d)')
aSearch = player_regex.search(coord)
if aSearch == None:
correct_entry = False
if aSearch.group(1) != "A" or aSearch.group(1) != "B" or aSearch.group(1) != "C" or aSearch.group(2) != 1 or aSearch.group(2) == 2 or aSearch.group(3) != 3:
correct_entry = False
if aSearch.group(1) == "A" or aSearch.group(1) == "B" or aSearch.group(1) == "C" or aSearch.group(2) == 1 or aSearch.group(2) == 2 or aSearch.group(3) == 3:
correct_entry = True
else:
correct_entry = True
blank = False
while not blank:
if lst[(int(coord[-1])) - 1][alpha.index(coord[0])] == []:
lst[(int(coord[-1])) - 1][alpha.index(coord[0])] = "X"
temp_lst1.append((int(coord[-1])-1))
temp_lst1.append((alpha.index(coord[0])))
blank = True
else:
blank = True
correct_entry = False
if blank == True and correct_entry == True:
check = False
return True
def pc_player(lst):
print()
print ("PC symbol is 'O'. ")
alpha = ("A", "B", "C")
num_list = (0, 1, 2)
for i in range(0, len(lst)):
for j in range(0, len(lst[i])):
if lst[i][j] ==[]:
lst[i][j] = "O"
break
break
return True
def check_1st_player(lst):
if lst[0][0] == "X" and lst[0][1] == "X" and lst[0][2] == "X":
return True
elif lst[1][0] == "X" and lst[1][1] == "X" and lst[1][2] == "X":
return True
elif lst[2][0] == "X" and lst[2][1] == "X" and lst[2][2] == "X":
return True
elif lst[0][0] == "X" and lst[1][0] == "X" and lst[2][0] == "X":
return True
elif lst[0][1] == "X" and lst[1][1] == "X" and lst[2][1] == "X":
return True
elif lst[0][2] == "X" and lst[1][2] == "X" and lst[2][2] == "X":
return True
elif lst[0][0] == "X" and lst[1][1] == "X" and lst[2][2] == "X":
return True
elif lst[2][0] == "X" and lst[1][1] == "X" and lst[0][2] == "X":
return True
else:
return False
def check_pc_player(lst):
if lst[0][0] == "O" and lst[0][1] == "O" and lst[0][2] == "O":
return True
elif lst[1][0] == "O" and lst[1][1] == "O" and lst[1][2] == "O":
return True
elif lst[2][0] == "O" and lst[2][1] == "O" and lst[2][2] == "O":
return True
elif lst[0][0] == "O" and lst[1][0] == "O" and lst[2][0] == "O":
return True
elif lst[0][1] == "O" and lst[1][1] == "O" and lst[2][1] == "O":
return True
elif lst[0][2] == "O" and lst[1][2] == "O" and lst[2][2] == "O":
return True
elif lst[0][0] == "O" and lst[1][1] == "O" and lst[2][2] == "O":
return True
elif lst[2][0] == "O" and lst[1][1] == "O" and lst[0][2] == "O":
return True
else:
return False
def play_game():
ask = input("Do you want to play a two player game of Tic-Tac-Toe game? (y/n) ")
if ask in yes_response:
# contruct the template for tic-tac-toe
print()
print("How many rounds do you want to play? " )
print("Please enter only odd integers" )
print("Please enter your coordinates", end="")
print(" using format A1 or B2")
print("New Round")
return True
def play_again():
tell_me = input("Do you want you play a game ? (y/n)")
if tell_me == "Y" or "y":
return True
else:
return False
def is_full(lst):
count = 0
for i in lst:
for j in i:
if j != []:
count += 1
if count == 9:
return True
#
#-- main
print("Welcome to Awesome 2 Player Tic-Tac-Toe Game? ")
print()
answer = False
yes_response =("Y", "y")
no_response = ("N", "n")
while not answer:
print("Enter an even integer to exit")
ask = int(input("How many matches do you want to play? (odd integers only)? " ))
game = play_game()
structure = template()
print_template(structure)
if ask % 2 == 1:
score_player1 = 0
score_pc = 0
count = 0
while count < ask:
pc_lst = []
if count >= 1:
structure = template()
print_template(structure)
while game:
check_pc = True
while check_pc:
pc_player(structure)
template_2(structure)
check_pc = False
check_pc_winner = True
while check_pc_winner:
game_pc = check_pc_player(structure)
check_pc_winner = False
if game_pc == True:
print("Congratulations PC won")
score_pc += 1
game = False
break
check_player1 = True
while check_player1:
first_player(structure)
template_2(structure)
check_player1 = False
check_first_winner = True
while check_first_winner:
game_first = check_1st_player(structure)
check_first_winner = False
if game_first == True:
print("Congratulations Player 1 won")
score_player1 += 1
game = False
break
board_full = False
while not board_full:
check_board = is_full(structure)
board_full = True
if check_board == True:
print("This round was a tie.")
game = False
print("Player 1 : ", score_player1, " PC : ", score_pc)
count += 1
game = True
if score_player1 > score_pc:
print("Player 1 won")
elif score_player1 < score_pc:
print("PC won")
if play_again() == False:
answer = True
else:
answer = False
The problem I have is at def pc_player():
I would like to know how to loop the list and sublists so that AI can select an empty box as its choice to place an "O"
My current for loop does not work. AI only selects the first box.
My current for loop does not work. AI only selects the first box.
I suppose you refer to this part:
def pc_player(lst):
print()
print ("PC symbol is 'O'. ")
alpha = ("A", "B", "C")
num_list = (0, 1, 2)
for i in range(0, len(lst)):
for j in range(0, len(lst[i])):
if lst[i][j] ==[]:
lst[i][j] = "O"
break
break
return True
The break instructions together with the way you initialize the for loops will only attempt to set lst[0][0]. Other cells are not considered.
To make an evenly distributed random choice, it is essential to gather the possibilities first. For this, it is convenient to have all cells in a plain list first:
from itertools import chain
all_cells = list(chain.from_iterable(lst))
Then, you can filter out non-empty cells:
empty_cells = filter(lambda l: len(l) == 0, all_cells)
# empty_cells = filter(lambda l: not l, all_cells)
# empty_cells = [cell for cell in all_cells if not cell]
Based on this you can now trigger your random selection and symbol placement:
import random
cell_to_place = random.choice(empty_cells)
cell_to_place.append('O')
If you need the index of the cell being modified, you can do the following:
import itertools
indices = list(itertools.product(range(3), range(3)))
indexed_cells = zip(indices, map(lambda (i, j): lst[i][j], indices))
indexed_cells = filter(lambda (_, l): not l, indexed_cells) # filter non-empty
(i,j), cell_to_place = random.choice(indexed_cells)
# ...
These code samples do not take into account that there could be no empty cell left. Also, your code has some general design issues. For example:
Why do you use lists as cell items in the first place? You could simply use None, 'X' and 'O' as the elements of the 2-dimensional list.
check_pc_player and check_1st_player can be easily generalized by making the symbol to check for a parameter of the function.
Why is this a while-loop?
while check_first_winner:
game_first = check_1st_player(structure)
check_first_winner = False
Start by finding all empty boxes:
empty= [(i,j) for i in range(len(lst)) for j in range(len(lst[i])) if lst[i][j]==[]]
Then choose a random one:
import random
chosen_i, chosen_j= random.choice(empty)
And finally put an O there:
lst[chosen_i][chosen_j]= 'O'