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)]
...
Related
from typing import List
# You are given an integer n, denoting the no of people who needs to be seated, and a list of m integer seats, where 0 represents a vacant seat. Find whether all people can be seated, provided that no two people can sit together
When I run this code in geeks for geeks for submission I get a error that List index is out of range.
but seems to work fine when I run it as a script.
class Solution:
def is_possible_to_get_seats(self, n: int, m: int, seats: List[int]) -> bool:
vacant_seats = 0
if len(seats) == 2:
if seats[0] or seats[1] == 1:
print(seats)
return False
else:
print(seats)
return True
else:
for x in range(len(seats)):
if x == 0:
if seats[x] == 0 and seats[x+1] == 0:
seats[x] = 1
vacant_seats += 1
elif x == len(seats)-1:
if seats[x] == 0 and seats[x-1] == 0:
seats[x] = 1
vacant_seats += 1
else:
if seats[x] == 0:
if seats[x+1] == 0 and seats[x-1] == 0:
seats[x] = 1
vacant_seats += 1
if vacant_seats < n:
return False
else:
return True
# {
# Driver Code Starts
class IntArray:
def __init__(self) -> None:
pass
def Input(self, n):
arr = [int(i) for i in input().strip().split()] # array input
return arr
def Print(self, arr):
for i in arr:
print(i, end=" ")
print()
if __name__ == "__main__":
t = int(input())
for _ in range(t):
n = int(input())
m = int(input())
seats = IntArray().Input(m)
obj = Solution()
res = obj.is_possible_to_get_seats(n, m, seats)
result_val = "Yes" if res else "No"
print(result_val)
# } Driver Code Ends
i have wrote two program, one is tic tac toe,one is guest number, and it is fine when run separately and when i combine them( my aim is when to people win in the guest number game, the people can pick a box in tic tac toe)
It work normally and when it start to select to second box, the error occur
it is show asz follow
Traceback (most recent call last):
File "C:\Users\User\Desktop\try3.py", line 207, in
winner = single_game(options[choice-1])
File "C:\Users\User\Desktop\try3.py", line 125, in single_game
player_pos[cur_player].append(move)
KeyError: <main.Player object at 0x000001D6C01CC730>
can anyone see what wrong with my program. Thanks
import random
from random import randint
class Player():
def __init__(self, player_name):
self.name = player_name
self.score = 0
self.guess = 0
def enterGuess(self,rand, play):
if play == True:
self.guess = int(input(self.name+ " enter a guess 1-100:"))
if self.guess == rand:
print ("Correct Guess")
play = False
self.score = self.score + 1
elif self.guess < rand:
print ("Too low")
else:
print ("Too high")
return play
def playGame():
player1.score = 0
player1.guess = 0
player2.score = 0
player2.guess = 0
randNum = randint(1,100)
play = True
print ("\nNew game")
while play:
play=player1.enterGuess(randNum, play)
play=player2.enterGuess(randNum, play)
def coinToss():
flip = random.randint(0, 1)
if (flip == 0):
return("Head")
else:
return("Tail")
print(coinToss)
def print_tic_tac_toe(values):
print("\n")
print("\t | |")
print("\t {} | {} | {}".format(values[0], values[1], values[2]))
print('\t_____|_____|_____')
print("\t | |")
print("\t {} | {} | {}".format(values[3], values[4], values[5]))
print('\t_____|_____|_____')
print("\t | |")
print("\t {} | {} | {}".format(values[6], values[7], values[8]))
print("\t | |")
print("\n")
def print_scoreboard(score_board):
print("\t--------------------------------")
print("\t SCOREBOARD ")
print("\t--------------------------------")
players = list(score_board.keys())
print("\t ", players[0], "\t ", score_board[players[0]])
print("\t ", players[1], "\t ", score_board[players[1]])
print("\t--------------------------------\n")
def check_win(player_pos, cur_player):
soln = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9], [1, 5, 9], [3, 5, 7]]
for x in soln:
if all(y in player_pos[cur_player] for y in x):
return True
return False
def check_draw(player_pos):
if len(player_pos['X']) + len(player_pos['O']) == 9:
return True
return False
def single_game(cur_player):
values = [' ' for x in range(9)]
player_pos = {'X':[], 'O':[]}
while True:
print_tic_tac_toe(values)
try:
print("The player ", cur_player, " turn. Which box? : ", end="")
move = int(input())
except ValueError:
print("Wrong Input!!! Try Again")
continue
if move < 1 or move > 9:
print("Wrong Input!!! Try Again")
continue
if values[move-1] != ' ':
print("Place already filled. Try again!!")
continue
values[move-1] = cur_player
player_pos[cur_player].append(move)
if check_win(player_pos, cur_player):
print_tic_tac_toe(values)
print( cur_player, " has won the game!!")
print("\n")
return cur_player
if check_draw(player_pos):
print_tic_tac_toe(values)
print("Game Drawn")
print("\n")
return 'D'
playGame()
if int(player1.score)>int(player2.score):
cur_player = player1
else:
cur_player = player2
if __name__ == "__main__":
print ("Player 1")
player1=Player(input("Enter name:"))
print ("Player 2")
player2=Player(input("Enter name:"))
playGame()
if int(player1.score)>int(player2.score):
cur_player = player1
else:
cur_player = player2
player_choice = {'X' : "", 'O' : ""}
options = ['X', 'O']
score_board = {player1: 0, player2: 0}
print_scoreboard(score_board)
while True:
print("Turn to choose for", cur_player)
print("Enter 1 for X")
print("Enter 2 for O")
print("Enter 3 to Quit")
try:
choice = int(input())
except ValueError:
print("Wrong Input!!! Try Again\n")
continue
if choice == 1:
player_choice['X'] = cur_player
if cur_player == player1:
player_choice['O'] = player2
else:
player_choice['O'] = player1
elif choice == 2:
player_choice['O'] = cur_player
if cur_player == player1:
player_choice['X'] = player2
else:
player_choice['X'] = player1
elif choice == 3:
print("Final Scores")
print_scoreboard(score_board)
break
else:
print("Wrong Choice!!!! Try Again\n")
winner = single_game(options[choice-1])
if winner != 'D' :
player_won = player_choice[winner]
score_board[player_won] = score_board[player_won] + 1
print_scoreboard(score_board)
I am building a tic-tac-toe. I have almost finished it but I cannot break the while loop in the end. I have turned win into True. But the if statement in the while loop is not working.
board = [[1,2,3],[4,"X",6],[7,8,9]]
win = False
def DisplayBoard(board):
def printborder():
print("+-------+-------+-------+")
def printline():
print("| | | |")
def printitem(board,row):
print("| ",board[row][0]," | ",board[row][1]," | ",board[row][2]," |", sep="")
printborder()
printline()
printitem(board,0)
printline()
printborder()
printline()
printitem(board,1)
printline()
printborder()
printline()
printitem(board,2)
printline()
printborder()
def EnterMove(board):
while True:
move = int(input("Enter your move: "))
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j]==move:
board[i][j]="O"
return None
def MakeListOfFreeFields(board):
freefield = []
for i in range(len(board)):
for j in range(len(board[i])):
for k in range(1,10):
if board[i][j] == k:
freefield.insert(0,k)
return freefield
def VictoryFor(board, sign):
def whowin(sign):
if sign == "O":
print("Player wins.")
win = True
elif sign == "X":
print("Computer wins.")
win = True
def checkvertical(board):
for i in range(3):
if board[0][i]==board[1][i]==board[2][i]:
whowin(sign)
def checkhorizontal(board):
for i in range(3):
if board[i][0]==board[i][1]==board[i][2]:
whowin(sign)
def checkdiagonal(board):
if board[0][0]==board[1][1]==board[2][2] or board[0][2]==board[1][1]==board[2][0]:
whowin(sign)
checkvertical(board)
checkhorizontal(board)
checkdiagonal(board)
def DrawMove(board):
from random import randrange
while True:
ran = randrange(1,10)
if ran in MakeListOfFreeFields(board):
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j]==ran:
board[i][j]="X"
return None
DisplayBoard(board)
while True:
EnterMove(board)
DisplayBoard(board)
VictoryFor(board, "O")
if win==True:
break
DrawMove(board)
DisplayBoard(board)
VictoryFor(board, "X")
if win==True:
break
print("ended")
fhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh fhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh fhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh fhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
In your whowin function (inside of VictoryFor) you simply create a local win variable. If you want to refer to the global one, you need to tell Python to do so:
def whowin(sign):
global win # <---- add this
if sign == "O":
print("Player wins.")
win = True
elif sign == "X":
print("Computer wins.")
win = True
I was trying to build this basic code for fun but I ran into some weird error. The following code asks for an answer of a basic printed out equation. When the answer is 10 or greater, it is behaving weirdly. I tried to implement some error handling methods (the failure is at int(ansr_raw) I guess). I think a better method will help me out. You don't need to spell out the code for me but pointing me at the right direction will be helpful. The code and output are given below.
code -
import random
signs = ['+', '-']
verbals = ['out', 'quit', 'help', 'break']
while True:
a, b = random.randint(1, 9), random.randint(1, 9)
ch = random.choice(signs)
print("{} {} {} = ?".format(a, ch, b))
ansr_raw = input("Enter the answer: ")
if ansr_raw in '0123456789': # trying to handle error
ansr = int(ansr_raw)
else:
for i in verbals:
if ansr_raw == i:
choice = input("Wish to Quit? [y/n] ").lower()
if choice in 'yes':
print("Quit Successful.")
break
elif choice in 'no':
continue
else:
print("Wrong choice. continuing game.")
continue
print('answer format invalid')
continue
if ch == '+':
if ansr == (a + b):
print("Right Answer.")
else:
print("wrong answer.")
elif ch == '-':
if ansr in ((a - b), (b - a)):
print("Right Answer.")
else:
print("wrong answer.")
Here is the output (arrow marks added)-
9 + 3 = ?
Enter the answer: 12
answer format invalid <----
2 - 9 = ?
Enter the answer: 5
wrong answer.
1 - 3 = ?
Enter the answer: 2
Right Answer.
8 + 3 = ?
Enter the answer: 11
answer format invalid <----
1 + 2 = ?
Enter the answer: 3
Right Answer.
6 + 2 = ?
Enter the answer:
The problem is where you say
if ansr_raw in '0123456789': # trying to handle error
ansr = int(ansr_raw)
For a single digit number like 9, yes there is a 9 in that string, but there is only a few two digits(01,23,34,45,56,67,78,89), to what you're trying to do, check if the string can become an integer; do this.
try:
ansr = int(ansr_raw)
except ValueError:
Full Code:
import random
import sys
signs = ['+', '-']
verbals = ['out', 'quit', 'help', 'break']
running = True
while running:
a, b = random.randint(1, 9), random.randint(1, 9)
ch = random.choice(signs)
print("{} {} {} = ?".format(a, ch, b))
ansr_raw = input("Enter the answer: ")
try:
ansr = int(ansr_raw)
except ValueError:
answerInv = True
for i in verbals:
if ansr_raw == i:
choice = input("Wish to Quit? [y/n] ").lower()
if choice in 'yes':
print("Quit Successful.")
sys.exit(0)
elif choice in 'no':
continue
answerInv = False
else:
print("Wrong choice. continuing game.")
answerInv = False
continue
if answerInv:
print('answer format invalid')
if ch == '+':
if ansr == (a + b):
print("Right Answer.")
else:
print("wrong answer.")
elif ch == '-':
if ansr in ((a - b), (b - a)):
print("Right Answer.")
else:
print("wrong answer.")
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