My code runs until the last line, input is needed - python-3.x

print("Welcome to my calorie counter program")def disp_menu():choice_list = ["a", "d", "m", "q"]
initial loop
while True:
print("What do you want to do?")
print("a = add an item")
print("d = delete an item")
print("q = quit")
choice = input("make a selection>")
if choice in choice_list:
return choice
else:
print("not a valid selection, try again")
while True:
choice = disp_menu()
if choice == "a":
tot_cals, item_cnt = add_process(tot_cals, item_cnt)
elif choice == "d":
del_item()
elif choice == "q":
break
disp_meal()
#create lists
item_list = [] #list of items ordered
cals_list = [] #
#create variables
cont = str("y")
item_cnt = int(0)
tot_cals = int(0)
#define functions here
#calculates calories per grams
def calc_cals(g_type, grams):
if g_type =="f":
return grams * 9
else:
return grams * 4
#first loop
while cont.lower() =="y":
valid_data = False #this is the boolean flag for data validation
#Capture input
while not valid_data:
item_name = input("please enter the item> ")
if len(item_name) > 20:
print("not a valid food name")
elif len(item_name) == 0:
print("you need to enter a name")
else:
valid_data = True
#reset the flag for the next data item
valid_data = False
while not valid_data:
try:g_carbs = int(input("enter grams of carbs> "))
except Exception is detail:
print("carbs error: ", detail)
else:
valid_data = True
#reset the flag for the next data item
valid_data = False
while not valid_data:
try:g_fats = int(input("enter grams of fats> "))
except Exception is detail:
print("fats error: ", detail)
else:
valid_data = True
valid_data = False
while not valid_data:
try:g_protein = int(input("enter grams of protein> "))
except Exception is detail:
print("protein error: ", detail)
else:
valid_data = True
new function
def add_process(tot_cals, item_cnt):
item_name = input_name()
g_carbs = input_grams("carbs")
g_fats = input_grams("fats")`
g_prot = input_grams("protein")
#Do the math
cals = calc_cals("c", g_carbs) + calc_cals("f", g_fats) + calc_cals("p", g_prot)
#output
print("total calories for {} are {}".format(item_name, cals))
incl = input("do you want to include {}? (y/n)>".format(item_name))
if incl.lower() == "y":
add_item(item_name, cals)
#accumulate totals
tot_cals = tot_cals + cals
item_cnt += 1 #shortcut method
print("item {} entered.".format(item_name))
else:
print("Item {} not entered.".format(item_name))
return tot_cals, item_cnt
#new function
def del_item():
if len(item_list == 0):
print("you have no items to delete")
else:
print("\nDelete an item")
disp_meal()
valid_data = False
while not valid_data:
try:
choice = int(input("Enter the item number you want to delete>"))
if 1<= choice <= len(item_list):
choice = choice - 1
print("Item {}. {} with {} calories will be deleted".format(choice + 1,
item_list[choice],
cals_list[choice]))
del item_list[choice]
del cals_list[choice]
valid_data = True
except Exception as detail:
print("error: ",detail)
print("try again")
#new function
def disp_meal():
print("\nMeal Calorie Counter")
print("Num\tItem\t\tcals")
print("---\t----\t\----")
meal_cals = 0
for c in range(len(item_list)):
meal_cals += cals_list[c]
print("{}.\t{}\t\t{}".format(c+1,item_list[c],
print("\nYour meal has {} items for a total of {} calories\n".format(len(item_list), meal_cals)
print("-" * 20)
#this last line gives me an eof error

Related

Looking for general feedback + a few small errors

So as the title states I'm simply looking for general feedback on the overall structure of the script, where I could do better (don't have to tell me how, where would be plenty) and things like that. Any feedback, advice, tips or help in general is always greatly appreciated as I'm real keen to learn deeper!
As for the errors...
Errors:
It doesn't seem to save any of the contacts after closing, if the only method of saving it, to save it to a file?
Updating claims to be out of range, which if I'm correct it shouldn't be, unless I'm just not seeing something?
Not exactly an issue but something I've been playing with, with no good result...is it possible to have a for loop w/if statement in a comprehension format without being in a print statement?
My code so far:
"""
This is project that lets the user pretty much create and edit a contact book by giving them options and using their
input to complete the data needed for the contact book.
"""
import sys
contacts = []
lst = []
def ContactBook():
rows, cols = int(input("Please enter the amount of people you want in the contact book: ")), 5
print(contacts)
for i in range(rows):
print(f"All mandatory fields will include *")
for a in range(cols):
if a == 0:
lst.append(input("Enter a name*: "))
if lst[a] == '' or lst[a] == "": sys.exit(f"Failed to provide a name...Exiting the contact book!")
if a == 1: lst.append(input("Enter a number*: "))
if a == 2:
lst.append(input("Enter an email: "))
if lst[a] == '' or lst[a] == "": lst[a] = None
if a == 3:
lst.append(input("Enter a D.O.B (mm/dd/yy): "))
if lst[a] == '' or lst[a] == "": lst[a] = None
if a == 4:
lst.append(input("What category (Family/Friends/Work/Others): "))
if lst[a] == '' or lst[a] == "": lst[a] = None
contacts.append(lst)
print(f"Your contacts are:\n{contacts}")
return contacts
def Menu():
print(f"\t\t\t{'Contact Book':*^70}", flush=False)
print(f"Your options are:\n1. Add a Contact\n2. Searching Contacts\n3. Edit Contacts\n4. Delete Contacts\n"
f"5. View Contacts\n6. Delete Everything\n7. Exit the book")
choice = int(input("Please select an option: "))
return choice
def AddingContacts(cb):
for i in range(len(cb[0])):
if i == 0: contacts.append(input("Enter a name: "))
elif i == 1: contacts.append(int(input("Enter a number: ")))
elif i == 2: contacts.append(input("Enter a email: "))
elif i == 3: contacts.append(input("Enter a d.o.b (mm/dd/yy): "))
elif i == 4: contacts.append(input("Enter a category: "))
cb.append(contacts)
return cb
def SearchContacts(cb):
s = int(input("Select an option:\n1. Name\n2. Number\n3. Email\n4. D.O.B\n5. Category"))
t, c = [], -1
if s == 1:
q = input("Enter who you want to search: ")
for i in range(len(cb)):
if q == cb[i][0]: c = i, t.append(cb[i])
elif s == 2:
q = int(input("Enter the number you want to find: "))
for i in range(len(cb)):
if q == cb[i][1]: c = i, t.append(cb[i])
elif s == 3:
q = input("Enter the email you want to search: ")
for i in range(len(cb)):
if q == cb[i][2]: c = i, t.append(cb[i])
elif s == 4:
q = input("Enter the date you want to search in mm/dd/yy format: ")
for i in range(len(cb)):
if q == cb[i][3]: c = i, t.append(cb[i])
elif s == 5:
q = input("Enter a category you want to search: ")
for i in range(len(cb)):
if q == cb[i][4]: c = i, t.append(cb[i])
else:
print(f"Invalid search inquiry...")
return -1
if c == -1: return -1
elif c != -1:
ShowContent(t)
return c
def ShowContent(cb):
if not cb: print(f"List has nothing in it...: []")
else: print(f"{[cb[i] for i in range(len(cb))]}")
return cb
def UpdateContacts(cb):
for i in range(len(cb[0])):
if i == 0: contacts[0] = (input("Enter a name: "))
elif i == 1: contacts[1] = (int(input("Enter a number: ")))
elif i == 2: contacts[2] = (input("Enter a email: "))
elif i == 3: contacts[3] = (input("Enter a d.o.b: "))
elif i == 4: contacts[4] = (input("Enter a category: "))
cb.append(contacts)
return cb
def RemovingContacts(cb):
q = input("Enter the person you want to remove: ")
x = 0
for i in range(len(cb)):
if q == cb[i][0]: x += 1, print(f"This contact has now been removed: {cb.pop(i)}")
return cb
if x == 0: print(f"Person doesn't exist. Please check the name and try again....")
return cb
def DeleteBook(cb):
return cb.clear()
if __name__ == "__main__":
print(f"Welcome to your new Contact Book! Hope you find it easy to navigate!")
ch = 1
cb = ContactBook()
while ch in (1, 2, 3, 4, 5, 6):
ch = Menu()
if ch == 1: cb = AddingContacts(cb)
elif ch == 2: cb = SearchContacts(cb)
elif ch == 3: cb = UpdateContacts(cb)
elif ch == 4: cb = RemovingContacts(cb)
elif ch == 5: cb = ShowContent(cb)
elif ch == 6: cb = DeleteBook(cb)
else: sys.exit(f"Thank you for using this contact book! Have a great day!")
I plan on using the Pandas module to display the data in table format, is it possible without mySQL?

Why the "stop" input doesnt stop the hitorstop() and run the code for the condition elif todo == "stop"

import random
class Player:
deck = ["A♣", "2♣", "3♣", "4♣", "5♣", "6♣", "7♣", "8♣", "9♣", "10♣", "J♣", "K♣", "Q♣", "A♦", "2♦", "3♦", "4♦", "5♦",
"6♦", "7♦", "8♦", "9♦", "10♦", "J♦", "K♦", "Q♦", "A♥", "2♥", "3♥", "4♥", "5♥", "6♥", "7♥", "8♥", "9♥",
"10♥", "J♥", "K♥", "Q♥", "A♠", "2♠", "3♠", "4♠", "5♠", "6♠", "7♠", "8♠", "9♠", "10♠", "J♠", "K♠", "Q♠"]
total = 0
run = True
def __init__(self):
self.name = input("Enter your name : ")
self.Bet = inputs.bet(self)
self.Aceval = inputs.Aval(self)
class Dealer:
deck = ["A♣", "2♣", "3♣", "4♣", "5♣", "6♣", "7♣", "8♣", "9♣", "10♣", "J♣", "K♣", "Q♣", "A♦", "2♦", "3♦", "4♦", "5♦",
"6♦", "7♦", "8♦", "9♦", "10♦", "J♦", "K♦", "Q♦", "A♥", "2♥", "3♥", "4♥", "5♥", "6♥", "7♥", "8♥", "9♥",
"10♥", "J♥", "K♥", "Q♥", "A♠", "2♠", "3♠", "4♠", "5♠", "6♠", "7♠", "8♠", "9♠", "10♠", "J♠", "K♠", "Q♠"]
total = 0
class inputs:
def bet(self):
"""
takes in the bet from the user and stores it in the player class
:return: output
"""
self.bet = input("Enter the amount for your bet : ")
output = self.bet
if self.bet.isnumeric() == False:
print("Use your monke brains and enter correct input")
return inputs.bet(self)
else:
return int(output)
def Aval(self):
"""
Takes the value for ace and stores it in the player class
:return: output
"""
self.aval = input("Enter the value for ACE (1 or 10) : ")
output = self.aval
if self.aval.isnumeric() == False:
print("Use your monke brains and enter correct input")
return inputs.Aval(self)
elif self.aval.isnumeric() == True:
if self.aval in ["1", "10"]:
return int(output)
else:
print("I understand you suffer braincell deficiency but I need you to fire up those 2 braincells you have and enter the proper number")
return inputs.Aval(self)
def valcalc(card):
"""
takes the card for player.deck and returns the value of that card
:return: card value
"""
if card[0] in ("K", "Q", "J"):
return 10
elif card[0] == "A":
return p.Aceval
else:
if len(card) > 2:
return int(card[0:2])
else:
return int(card[0])
def hitorstop(todo):
if todo.lower() == ("hit" or "stop"):
if todo.lower() == "hit":
pcard = random.choice(Player.deck)
dcard = random.choice(Dealer.deck)
print("\nYour card is : ", pcard)
Player.deck.remove(pcard)
Dealer.deck.remove(dcard)
p.total += inputs.valcalc(pcard)
d.total += inputs.valcalc(dcard)
print("Your total is : ", p.total)
if p.total > 21:
print("You lost lol")
return
elif d.total > 21:
print("You won , sheeesh")
return
elif (p.total == d.total) == 21:
print("Its a tie")
return
else:
hitorstop(input("\n\nDo you want to hit or stop : "))
else:
if todo.lower() == "stop":
pnum = 21 - p.total
dnum = 21 - d.total
if dnum > pnum:
print(p.name, "wins")
return
elif pnum > dnum:
print("You lost against a dealer bot , such a shame")
return
else:
print("Its a tie , you didnt win shit , lol")
return
else:
hitorstop(input("\n\nDo you want to hit or stop : "))
else:
hitorstop(input("\n\nDo you want to hit or stop : "))
p = Player()
d = Dealer()
pcard = random.choice(Player.deck)
dcard = random.choice(Dealer.deck)
print("\nYour card is : ", pcard)
print("Dealer's card is :" + str(dcard) + "+")
Player.deck.remove(pcard)
Dealer.deck.remove(dcard)
p.total += inputs.valcalc(pcard)
d.total += inputs.valcalc(dcard)
print("Your total is : ", p.total)
hitorstop(input("Do you want to hit or stop : "))
Why does the code below todo == "stop" run when i put in stop as input , it just keeps looping asking for the input again and again if i put "stop" for hitorstop() function
.................................................................................................................................................................................................................................................................................................................................................
You need to replace the line todo.lower() == ("hit" or "stop"): with todo.lower() in ("hit", "stop"): to make it work.
However, this entire condition is redundant in the first place and you can remove it.
You don't need it since you compare the input with "hit" and "stop" later, so it is useless to compare twice.
Here is the replace:
def hitorstop(todo):
if todo.lower() == "hit":
pcard = random.choice(Player.deck)
dcard = random.choice(Dealer.deck)
print("\nYour card is : ", pcard)
Player.deck.remove(pcard)
Dealer.deck.remove(dcard)
p.total += inputs.valcalc(pcard)
d.total += inputs.valcalc(dcard)
print("Your total is : ", p.total)
if p.total > 21:
print("You lost lol")
return
elif d.total > 21:
print("You won , sheeesh")
return
elif (p.total == d.total) == 21:
print("Its a tie")
return
else:
hitorstop(input("\n\nDo you want to hit or stop : "))
elif todo.lower() == "stop":
pnum = 21 - p.total
dnum = 21 - d.total
if dnum > pnum:
print(p.name, "wins")
return
elif pnum > dnum:
print("You lost against a dealer bot , such a shame")
return
else:
print("Its a tie , you didnt win shit , lol")
else:
hitorstop(input("\n\nDo you want to hit or stop : "))

How to implement a timer for a math quiz in python?

import random
import time
import pathlib
import hashlib
import operator
level = 1
score = 1
def sign_up():
username = input("Enter a username: ")
while True:
password = input("Enter a password (6 character long): ")
if len(password) < 6:
password = input("Enter a password (6 character long): ")
else:
break
hashed_password = hashlib.sha1(password.encode("utf-8")).hexdigest()
# print(hashed_password)
with open("credentials.txt", mode="w") as writable_password:
writable_password.write(username+"\n")
writable_password.write(hashed_password+"\n")
log_in()
def log_in():
print("Please, enter your usarname and password to sign in")
username = input("Username: ")+"\n"
while True:
password = input("Password (6 character long): ")
if len(password) < 6:
password = input("Password (6 character long): ")
else:
break
with open(".credentials.txt", mode="r") as credentials:
user_data = credentials.readlines()
for i in user_data:
# print(i)
if i == username and hashlib.sha1(password.encode("utf-8")).hexdigest()+"\n" == user_data[user_data.index(i)+1]:
print("You have succesfully signed in")
start_game()
break
def start_game():
start = "ll"
start = input("Please press any key to start the game")
# print(start)
if start != "ll" and level == 1:
level_one()
overall = 0
def level_one():
global score
global overall
if score <= 0:
return print("Haha, You lost")
answer = 0
first_number = random.randint(1, 100)
second_number = random.randint(1, 100)
random_operator = random.choice(["+", "-"])
if random_operator == "+":
response = input(f"{first_number} + {second_number}: ")
answer = first_number + second_number
if int(response) == answer:
score += 10
overall += 10
print(score)
level_one()
else:
score -= 10
print(score)
level_one()
else:
response = input(f"{first_number} - {second_number}: ")
answer = first_number - second_number
if int(response) == answer:
score += 10
print(score)
level_one()
else:
score -= 10
print(score)
level_one()
# print(first_number, second_number, answer)
# def main():
# if __name__ = "__main__":
# main()
# sign_up()
# log_in()
start_game()
I want to implement a timer for my math quiz. The user should have 2 minutes at the beginning and for each correct answer 10 seconds will be added. For wrong answers 6 sec will be removed. How can I do this with Python 3.8?
I would add a new methode and using the threading.Timer modul (https://docs.python.org/3/library/threading.html#timer-objects):
from threading import Timer
global time_to_play
time_to_play=2*60 # in seconds
....
def check_for_end:
if time_to_play == 0: # time runs out
print("You lose")
exit(0) # exit program
else: # still playing
t = Timer(2.0, check_for_end) # start Timer wich runs the check methode in 2 sec
t.start()
and now you just have to adjust the global variable time_to_play accordingly.
The Timer will check all 2 seconds, if time_to_play is 0

I keep getting this error: AttributeError: module 'admin' has no attribute 'run_admin_options'

I keep on getting this error when I run my program. In the bank_system file, an option is given to type the number 5 so it loads the run_admin_options function in the admin.py option. But everytime I run the program it comes with this error:
AttributeError: module 'admin' has no attribute 'run_admin_options'
The code from my admin.py module:
class Admin:
def __init__(self, fname, lname, address, house_number, road_name, town_city, postcode, user_name, password, full_rights):
self.fname = fname
self.lname = lname
self.address = address
self.house_number = house_number
self.road_name = road_name
self.town_city = town_city
self.postcode = postcode
self.user_name = user_name
self.password = password
self.full_admin_rights = full_rights
def update_first_name(self, fname):
self.fname = fname
def update_last_name(self, lname):
self.lname = lname
def get_first_name(self):
return self.fname
def get_last_name(self):
return self.lname
def update_address(self, addr):
self.address = addr
def set_username(self, uname):
self.user_name = uname
def get_username(self):
return self.user_name
def get_address(self):
return self.address
# new
def get_house_number(self):
return self.house_number
# new
def update_house_number(self, house_number):
self.house_number = house_number
def get_road_name(self):
return self.road_name
def update_road_name(self, road_name):
self.road_name = road_name
# new
def get_town_city(self):
return self.town_city
def update_town_name(self, town_city):
self.town_city = town_city
# new
def get_postcode(self):
return self.postcode
def update_postcode(self, postcode):
self.postcode = postcode
def update_password(self, password):
self.password = password
def get_password(self):
return self.password
def set_full_admin_right(self, admin_right):
self.full_admin_rights = admin_right
def has_full_admin_right(self):
return self.full_admin_rights
def admin_account_menu(self):
# print the options you have
print()
print()
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("Your admin options are:")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("1) Update name")
print("2) Update address")
print(" ")
option = int(input("Choose your option: "))
return option
def run_admin_options(self):
loop = 1
while loop == 1:
choice = self.admin_account_menu()
if choice == 1:
fname = input("\n Enter new admin first name: ")
self.update_first_name(fname)
sname = input("\n Enter new admin last name: ")
self.update_last_name(sname)
elif choice == 2:
house_number = input("\n Enter new admin house number: ")
self.update_house_number(house_number)
road_name = input("\n Enter new admin road name: ")
self.update_road_name(road_name)
town_city = input("\n Enter new admin town or city: ")
self.update_town_name(town_city)
postcode = input("\n Enter new admin postcode: ")
self.update_postcode(postcode)
print("Admin details successfully updated")
The code from my bank_system module:
class BankSystem(object):
def __init__(self):
self.accounts_list = []
self.admins_list = []
self.load_bank_data()
def load_bank_data(self):
# create customers
account_no = 1234
customer_1 = CustomerAccount("Adam", "Smith", ["14", "Wilcot Street", "Bath", "B5 5RT"], account_no, 5000.00)
self.accounts_list.append(customer_1)
account_no += 5678
customer_2 = CustomerAccount("David", "White", ["60", "Holborn Viaduct", "London", "EC1A 2FD"], account_no,
3200.00)
self.accounts_list.append(customer_2)
account_no += 3456
customer_3 = CustomerAccount("Alice", "Churchil", ["5", "Cardigan Street", "Birmingham", "B4 7BD"], account_no,
18000.00)
self.accounts_list.append(customer_3)
account_no += 6789
customer_4 = CustomerAccount("Ali", "Abdallah", ["44", "Churchill Way West", "Basingstoke", "RG21 6YR"],
account_no, 40.00)
self.accounts_list.append(customer_4)
# create admins
admin_1 = Admin("Taran", "Basi", ["224", "Kenpas Highway", "Coventry", "CV3 6PB"], 224, "Kenpas Highway", "Coventry", "CV3 6PB", "1", "pass", True)
self.admins_list.append(admin_1)
def search_admins_by_name(self, admin_username):
# STEP A.2
found_admin = None
for a in self.admins_list:
username = a.get_username()
if username == admin_username:
found_admin = a
break
if found_admin == None:
print("\n ❌❌ The Admin %s does not exist! Please try again.\n" % admin_username)
return found_admin
def search_customers_by_name(self, customer_lname):
# STEP A.3
found_customer = None
for c in self.accounts_list:
lastname = c.get_last_name()
if lastname == customer_lname:
found_customer = c
break
if found_customer == None:
print("\n The customer %s does not exist! Try again...\n" % customer_lname)
return found_customer
def main_menu(self):
# print the options you have
print()
print()
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("Welcome to the Python Bank System")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("1) Admin login")
print("2) Quit Python Bank System")
print(" ")
option = int(input("Choose your option: "))
return option
def run_main_options(self):
loop = 1
while loop == 1:
choice = self.main_menu()
if choice == 1:
username = input("\n Please input admin username: ")
password = input("\n Please input admin password: ")
msg, admin_obj = self.admin_login(username, password)
print(msg)
if admin_obj != None:
self.run_admin_options(admin_obj)
elif choice == 2:
loop = 0
print("\n Thank-You for stopping by the bank!")
def transferMoney(self, sender_lname, receiver_lname, receiver_account_no, amount):
# ToDo
pass
def admin_login(self, username, password):
# STEP A.1
found_admin = self.search_admins_by_name(username)
msg = "\n ❌ Login failed"
if found_admin != None:
if found_admin.get_password() == password:
msg = "\n ✔ Login successful"
return msg, found_admin
def admin_menu(self, admin_obj):
# print the options you have
print(" ")
print("Welcome Admin %s %s! Available options are:" % (admin_obj.get_first_name(), admin_obj.get_last_name()))
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("1) Transfer money")
print("2) Customer account operations & profile settings")
print("3) Delete customer")
print("4) Print all customers detail")
print("5) Update admin information")
print("6) Sign out")
print(" ")
option = int(input("Choose your option: "))
return option
def run_admin_options(self, admin_obj):
loop = 1
while loop == 1:
choice = self.admin_menu(admin_obj)
if choice == 1:
sender_lname = input("\n Please input sender surname: ")
amount = float(input("\n Please input the amount to be transferred: "))
receiver_lname = input("\n Please input receiver surname: ")
receiver_account_no = input("\n Please input receiver account number: ")
self.transferMoney(sender_lname, receiver_lname, receiver_account_no, amount)
elif choice == 2:
# STEP A.4
customer_name = input("\n Please input customer surname :\n")
customer_account = self.search_customers_by_name(customer_name)
if customer_account != None:
customer_account.run_account_options()
elif choice == 3:
# STEP A.5
customer_name = input("\n input customer surname you want to delete: ")
customer_account = self.search_customers_by_name(customer_name)
if customer_account != None:
self.accounts_list.remove(customer_account)
print("%s was successfully deleted!" % customer_name)
elif choice == 4:
# STEP A.6
self.print_all_accounts_details()
elif choice == 5:
admin.run_admin_options()
elif choice == 6:
loop = 0
print("\n You have successfully logged out")
def print_all_accounts_details(self):
# list related operation - move to main.py
i = 0
for c in self.accounts_list:
i += 1
print('\n %d. ' % i, end=' ')
c.print_details()
print("------------------------")
app = BankSystem()
app.run_main_options()
Can anyone please help me with this error, I've tried so many times to fix this myself but I'm having no luck at all and I don't understand what this error means. All this code is getting me so confused.
Thank you.
The line
admin.run_admin_options()
in BankSystem.run_admin_options should probably be
admin_obj.run_admin_options()

Python Tic Toc Toe | GAME is Failing to RESTAR

Everything is running smoothly up until the while loop breaks and the else statement runs and asks the players if they want to play again.
else:
if input("Do you want to play again? Type Yes or No: ").lower() != 'no':
game_tic()
When I call game_tic() again the board doesn't refresh. The old moves are still displaying. I thought if I call the game_tic() the game was suppose to restart fresh.
Please check out my code:
import os
x_moves = [None, None, None, None, None, None, None, None, None]
o_moves = [None, None, None, None, None, None, None, None, None]
numeros= [1,2,3,
4,5,6,
7,8,9]
def clear_screen():
os.system("cls" if os.name == "nt" else "clear")
def draw_map_choices():
print("#" * 7)
tile = "|{}"
both_set = set(x_moves) | set(o_moves)
for num in numeros:
if num in both_set:
if num == 3:
if num in x_moves:
print(tile.format("X") + '|', end='\n')
else:
print(tile.format("O") + '|', end='\n')
elif num == 6:
if num in x_moves:
print(tile.format("X") + '|', end='\n')
else:
print(tile.format("O") + '|', end='\n')
elif num == 9:
if num in x_moves:
print(tile.format("X") + '|', end='\n')
else:
print(tile.format("O") + '|', end='\n')
print("#" * 7)
else:
if num in x_moves:
print(tile.format("X"), end='')
else:
print(tile.format("O"), end='')
else:
if num == 3:
print(tile.format(num)+'|',end='\n')
elif num == 6:
print(tile.format(num) + '|', end='\n')
elif num == 9:
print(tile.format(num) + '|')
print("#" * 7)
else:
print(tile.format(num),end="")
def return_open():
return sorted(set(numeros) - (set(x_moves) | set(o_moves)))
def player_X():
clear_screen()
draw_map_choices()
print("You can pick from the following number positions: {}.\n".format(", ".join(str(x) for x in return_open())))
x = int(input("Player X's turn: "))
if x not in x_moves and x not in o_moves:
x_moves[x-1] = x
else:
print("Pick a location that is open")
def player_O():
clear_screen()
draw_map_choices()
print("You can pick from the following number positions: {}.\n".format(", ".join(str(x) for x in return_open())))
o = int(input("Player O's turn: "))
if o not in o_moves and o not in x_moves:
o_moves[o-1] = o
else:
print("Pick a location that is open")
def check_if_won(xo_list):
#Horizontal MAtch
for n in range(0, 9, 3):
if (numeros[n], numeros[n+1], numeros[n+2]) == (xo_list[n], xo_list[n+1], xo_list[n+2]):
return True
# Vertical MAtch
for n in range(0, 3):
if(numeros[n],numeros[n+3], numeros[n+6]) == (xo_list[n], xo_list[n+3], xo_list[n+6]):
return True
#Diagonal Check
if (numeros[0], numeros[4], numeros[8]) == (xo_list[0], xo_list[4], xo_list[8]):
return True
if (numeros[2], numeros[4], numeros[6]) == (xo_list[2], xo_list[4], xo_list[6]):
return True
else:
return False
def game_tic():
juego = True
num_turn = 1
while juego:
player_X()
if check_if_won(x_moves):
clear_screen()
draw_map_choices()
print("Player X Won! Congratulations!\n")
juego = False
elif num_turn == 5:
clear_screen()
draw_map_choices()
print("Is a DRAW!\n")
juego = False
if juego:
player_O()
if check_if_won(o_moves):
clear_screen()
draw_map_choices()
print("Player O Won! Congratulations!\n")
juego = False
num_turn += 1
else:
if input("Do you want to play again? Type Yes or No: ").lower() != 'no':
game_tic()
clear_screen()
print("Let's Start Our Game of Tic Toc Toe!")
input("Press ENTER when you are ready!")
game_tic()
A quick solution would be to reset x_moves and o_moves in game_tic(), like this:
def game_tic():
juego = True
num_turn = 1
global x_moves, o_moves
x_moves = [None for i in range(0, 9)]
o_moves = [None for i in range(0, 9)]
...

Resources