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
Related
I am simply wondering how I can make my game of Mastermind work, more specifically how I would go about making "finish" global, how I would call these functions so that the program works correctly, and overall tips that would help enhance my code. I would also like to know how to make it so the program doesn't 'reroll' the computer-generated number every single loop. This was just a difficult problem for me and I can't seem to understand how to close it out with the correct function calls and niche aspects such as that. Thank you.
run = True
def get_guess():
while run:
guess = input("Provide four unique numbers: ")
count = 0
if len(guess) == 4:
guessdupe = guess[0] == guess[1] or guess[0] == guess[2] or guess[0] == guess[3] or guess[1] == guess[2] or guess[1] == guess[3] or guess[2] == guess[3]
else:
guessdupe = False
try:
try:
for i in range(4):
if int(guess[i]) <= 7 and int(guess[i]) >= 1 and len(guess) == 4:
count += 1
if len(guess) != 4:
print "Your guess must consist of 4 numbers!"
if guessdupe:
count -= 1
print "You can only use each number once!"
except ValueError:
print "You can only use numbers 1-7 as guesses"
except IndexError:
print "You can only use numbers 1-7 as guesses"
if count == 4:
break
return guess
def check_values(computer_list, user_list):
final_list = [''] * 4
for i in range(4):
if user_list[i] in computer_list:
if user_list[i] == computer_list[i]:
final_list[i] = "RED"
else:
final_list[i] = "WHITE"
else:
final_list[i] = "BLACK"
random.shuffle(final_list)
print final_list
return final_list
def check_win(response_list):
if response_list[0] == "RED" and response_list[1] == "RED" and response_list[2] == "RED" and response_list[3] == "RED":
print "Congratulations! You've won the game!"
global finish
finish = True
def create_comp_list():
while run:
compList = [random.randint(1, 7), random.randint(1, 7), random.randint(1, 7), random.randint(1, 7)]
listBool = compList[0] == compList[1] or compList[0] == compList[2] or compList[0] == compList[3] or compList[1] == compList[2] or compList[1] == compList[3] or compList[2] == compList[3]
if listBool:
continue
else:
return compList
def play_game():
for i in range(5):
print create_comp_list()
print get_guess()
check_win(check_values(create_comp_list(), get_guess()))
if finish:
break
play_game()```
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 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'
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'
Newbie python here. How can I break out of the second while loop if a user selects "Q" for "Quit?"
If I hit "m," it goes to the main menu and there I can quit hitting the "Q" key.
while loop == 1:
choice = main_menu()
if choice == "1":
os.system("clear")
while loop == 1:
choice = app_menu()
if choice == "1":
source = '%s/%s/external' % (app_help_path,app_version_10)
target = '%s/%s' % (target_app_help_path,app_version_10)
elif choice == "2":
source = '%s/%s/external' % (app_help_path,app_version_8)
target = '%s/%s' % (target_app_help_path,app_version_8)
elif choice.lower() == "m":
break
loop = 0
elif choice.lower() == "q":
break
loop = 0
sendfiles(source, target)
# Internal files
elif choice == "q":
loop = 0
App menu method:
def app_menu()
print "Select APP version"
print "-------------------"
print "1) 11"
print "2) 10"
print "3) 8"
print "m) Main Menu"
print "q) Quit"
print
return raw_input("Select an option: ")
You nearly have it; you just need to swap these two lines.
elif choice.lower() == "m":
break
loop = 0
elif choice.lower() == "m":
loop = 0
break
You break out of the nested loop before setting loop. :)
Change
break
loop = 0
to
loop = 0
break
in your elif blocks.
Use an exception.
class Quit( Exception ): pass
running= True
while running:
choice = main_menu()
if choice == "1":
os.system("clear")
try:
while True:
choice = app_menu()
if choice == "1":
elif choice == "2":
elif choice.lower() == "m":
break
# No statement after break is ever executed.
elif choice.lower() == "q":
raise Quit
sendfiles(source, target)
except Quit:
running= False
elif choice == "q":
running= False
Use two distinct variables for both loops, eg loop1 and loop2.
When you first press m in the inner loop you just break outside, and then you can handle q separately.
By the way you shouldn't need the inner variable to keep looping, just go with an infinite loop until key 'm' is pressed. Then you break out from inner loop while keeping first one.
Rename your top loop to something like mainloop, and set mainloop = 0 when q is received.
while mainloop == 1:
choice = main_menu()
if choice == "1":
os.system("clear")
while loop == 1:
choice = app_menu()
if choice == "1":
source = '%s/%s/external' % (app_help_path,app_version_10)
target = '%s/%s' % (target_app_help_path,app_version_10)
elif choice == "2":
source = '%s/%s/external' % (app_help_path,app_version_8)
target = '%s/%s' % (target_app_help_path,app_version_8)
elif choice.lower() == "m":
loop = 0
break
elif choice.lower() == "q":
mainloop = 0break
break
sendfiles(source, target)
# Internal files
elif choice == "q":
mainloop = 0
You could put this into a function and return:
import os.path
def do_whatever():
while True:
choice = main_menu()
if choice == "1":
os.system("clear")
while True:
choice = app_menu()
if choice in ("1", "2"):
app_version = app_version_10 if choice == "1" else app_version_8
source = os.path.join(app_help_path, app_version, "external")
target = os.path.join(target_app_help_path, app_version)
sendfiles(source, target)
elif choice.lower() == "m":
break
elif choice.lower() == "q":
return
Admittedly, I don't quite get when you want to break the inner loop and when you want to quit both loops, but this will give you the idea.