python program error while combine two program - python-3.x

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)

Related

My boolean flag isn't triggering when it's supposed to

At the play_again input, whenever I input "n" to end the loop, python seems to ignore it and prints :
Your cards: [x, x], current score: xx
Computers first card: x.
Would you like to draw another card? Press 'y' to draw or 'n' to stand.
Even though I have set end_game back to True.
What gives?
import random
from art import logo
from replit import clear
def deal_card():
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
card = random.choice(cards)
return card
def calculate_score(card_list):
if len(card_list) == 2 and sum(card_list) == 21:
return 0
if 11 in card_list and sum(card_list) > 21:
card_list.remove(11)
card_list.append(1)
return sum(card_list)
def compare(user, computer):
if user == computer:
return "I'ts a draw!"
elif user == 0:
return "You win with a BlackJack!"
elif computer == 0:
return "Computer wins with a BlackJack!"
elif computer > 21:
return "You win! Computer busts."
elif user > 21:
return "Computer wins, you bust!"
elif user > computer:
return "You win!"
else:
return "You lose!"
def main_loop():
print(logo)
user_cards = []
computer_cards = []
game_end = False
for _ in range(2):
user_cards.append(deal_card())
computer_cards.append(deal_card())
while not game_end:
user_score = calculate_score(user_cards)
computer_score = calculate_score(computer_cards)
print(f"Your cards: {user_cards}, current score: {user_score}")
print(f"Computers first card: {computer_cards[0]}.")
if user_score == 0 or computer_score == 0 or user_score > 21:
game_end = True
else:
play_again = input("Would you like to draw another card? Press 'y' to draw or 'n' to stand.")
if play_again == "y":
user_cards.append(deal_card())
else:
end_game = True
while computer_score != 0 and computer_score < 17:
computer_cards.append(deal_card())
computer_score = calculate_score(computer_cards)
print(f"Your final hand: {user_cards}, Your final score{user_score}.")
print(f"Computers final hand: {computer_cards}, Computers final score {computer_score}." )
print(compare(user_score, computer_score))
while input("Would you like to play a game of BlackJack?: ") == 'y':
clear()
main_loop()
else:
print('Goodbye!')
quit()
Please check your variable name game_end in "while not game_end:" loop,
if user_score == 0 or computer_score == 0 or user_score > 21:
game_end = True
else:
play_again = input("Would you like to draw another card? Press 'y' to draw
or 'n' to stand.")
if play_again == "y":
user_cards.append(deal_card())
else:
end_game = True
I think it's "game_end" in else: , you put end_game , please change it, other function working fine.

How to delete lines of output, python?

So here is my code:
Krotos = [100, 25]
Sephiroth = [100, 25]
endGame = 0
def checkHealth():
global endGame
if Krotos[0] == 0:
print("Game Over")
endGame = 1
if Sephiroth[0] == 0:
print("You Win")
endGame = 1
def krotosAttack():
Sephiroth[0] -= Krotos[1]
def printHealth():
print("Krotos:", Krotos[0])
print("Sephiroth:", Sephiroth[0])
def sephirothAttack():
Krotos[0] -= Sephiroth[1]
def checkInput():
print("Click 1 for attack\nClick 2 for shield")
x = int(input(":"))
if x == 1:
krotosAttack()
while endGame == 0:
checkInput()
checkHealth()
if endGame == 0:
sephirothAttack()
checkHealth()
printHealth()
My output is:
Click 1 for attack
Click 2 for shield
:1
Krotos: 75
Sephiroth: 75
Click 1 for attack
Click 2 for shield
:
How can I get rid of the first three lines so it only shows the newest information? Any new ideas would be useful. I have tried using google but I can't find anything.
Try this below :
Krotos = [100, 25]
Sephiroth = [100, 25]
endGame = 0
def clear():
import os
os.system("clear") # Linux
os.system("cls") # Windows
def checkHealth():
global endGame
if Krotos[0] == 0:
print("Game Over")
endGame = 1
if Sephiroth[0] == 0:
print("You Win")
endGame = 1
def krotosAttack():
Sephiroth[0] -= Krotos[1]
def printHealth():
print("Krotos:", Krotos[0])
print("Sephiroth:", Sephiroth[0])
def sephirothAttack():
Krotos[0] -= Sephiroth[1]
def checkInput():
print("Click 1 for attack\nClick 2 for shield")
x = int(input(":"))
if x == 1:
krotosAttack()
clear() # -------------> Call clear function after your input
while endGame == 0:
checkInput()
checkHealth()
if endGame == 0:
sephirothAttack()
checkHealth()
printHealth()
You can clear the console after every attack:
import os
os.system("cls") #windows
os.system("clear") #linux

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)]
...

tic tac toe for python3

how do I add a score counter to this tic tac toe game:
i need to be able to keep score of the tic tac toe games so that the users (its a 2 player game) can play mutable games in a row and the program will keep score for them.The program bellow already allows the users to continue to play so that they can play multiple games in a row however the program does not keep track of the score of player x and o or the number of ties. how to I add to this so that it will tray player x's wins, player o's wins, and the number on ties
def drawboard(board):
print(' | |')
print(' ' + str(board[7]) + ' | ' +str( board[8]) + ' | ' + str(board[9]))
print(' | |')
print('-----------')
print(' | |')
print(' ' + str(board[4]) + ' | ' + str(board[5]) + ' | ' + str(board[6]))
print(' | |')
print('-----------')
print(' | |')
print(' ' + str(board[1]) + ' | ' + str(board[2]) + ' | ' + str(board[3]))
print(' | |')
def draw(board):
print(board[7], board[8], board[9])
print(board[4], board[5], board[6])
print(board[1], board[2], board[3])
print()
def t(board):
while True:
try:
x = int(input())
if x in board:
return x
else:
print("\nSpace already taken. Try again")
except ValueError:
print("\nThat's not a number. enter a space 1-9")
def GO(win,board):
for x, o, b in win:
if board[x] == board[o] == board[b]:
print("Player {0} wins!\n".format(board[x]))
print("Congratulations!\n")
return True
if 9 == sum((pos == 'X' or pos == 'O') for pos in board):
print("The game ends in a tie\n")
return True
def tic_tac_toe():
board = [None] + list(range(1, 10))
win = [(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 player in 'XO' * 9:
drawboard(board)
if GO(win,board):
break
print("Player {0}".format(player))
board[t(board)] = player
print()
def main():
while True:
tic_tac_toe()
if input("Play again (y/n)\n") != "y":
break
main()
Seeing that the code is already a bit messy and still without answer, I would suggest a quick & dirty solution.
You can define a global variable outside of all the functions, like:
scoreboard = {"X": 0, "O": 0, "T": 0}
Then you simply increment the scores in your GO function.
def GO(win,board):
for x, o, b in win:
if board[x] == board[o] == board[b]:
print("Player {0} wins!\n".format(board[x]))
print("Congratulations!\n")
scoreboard[board[x]] += 1
return True
if 9 == sum((pos == 'X' or pos == 'O') for pos in board):
print("The game ends in a tie\n")
scoreboard["T"] += 1
return True
And just print the scores from scoreboard wherever you want.
However, I would recommend to learn how to make your code more readable. It will help you to write more difficult programs more easily. It will help to avoid quick and dirty solutions like this one and make a lot of difficult things fall into place without much effort.
In any case, congrats on writing a working TTT game, keep it up :)
def GO(win,board):
for x, o, b in win:
if board[x] == board[o] == board[b]:
print("Player {0} wins!\n".format(board[x]))
print("Congratulations!\n")
return True
if 9 == sum((pos == 'X' or pos == 'O') for pos in board):
print("The game ends in a tie\n")
# return False if there is no winner
return False
def tic_tac_toe():
board = [None] + list(range(1, 10))
win = [(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 player in 'XO' * 9:
drawboard(board)
if GO(win,board):
# returns the winner if there is one
return player
elif GO(win, board) is False:
# returns False if winner is a tie
return False
print("Player {0}".format(player))
board[t(board)] = player
print()
First, you should create unique output values for different game outcomes rather than only True. Then, you can keep score in your while loop based on the value of the function call.
def main():
count_x = 0
count_o = 0
while True:
score = tic_tac_toe()
if score == 'X':
count_x += 1
elif score == 'O':
count_o += 1
print("The running score is " + '('+ str(count_x), str(count_y) +')')
if input("Play again (y/n)\n") != "y":
break
main()

Is there a way to add to a next free space in a two-dimensional array? (Python 3.x)

Is there a way in Python to add to an array to the next free space available? So if (0,0) has already a value, move on to the (0,1) and add the value there. I got as far as shown below, and I'm stuck now..
class Array:
def __init__(self):
self.array = [[0 for x in range(5)] for x in range(5)]
def view(self):
for x in self.array:
print(x)
def input(self):
item = input("Enter an item: ")
self.array[0][0] = item
array = Array()
array.input()
array.view()
Here is one example. I am simply running the loop 9 times. You should be able to work it into your OOP style code. I am also using pprint module from standard library as I like how it displays nested lists.
from pprint import pprint as pp
myList = [[0 for x in range(5)] for x in range(5)]
for i in range(9):
userInput = int(input("Enter an item: "))
isFound = False # This flag is used to prevent duplicate entries.
for rowIndex, row in enumerate(myList):
for colIndex, column in enumerate(row):
if column == 0 and not isFound:
myList[rowIndex][colIndex] = userInput
isFound = True
break
pp(myList)
Output after last iteration of the loop: (assuming 5 was always entered):
Enter an item: 5
[[5, 5, 5, 5, 5],
[5, 5, 5, 5, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]]
class Array:
def __init__(self):
self.myList = [[0 for x in range(5)] for x in range(5)]
def input(self):
print("You will be asked to put a value, if you want to stop, press RETURN key.")
for i in range(25):
print()
userInput = input("Enter an item: ")
isFound = False
if userInput == '':
menu()
for rowIndex, row in enumerate(self.myList):
for colIndex, column in enumerate(row):
if column == 0 and not isFound:
self.myList[rowIndex][colIndex] = userInput
isFound = True
break
print()
for x in self.myList:
print(x)
def remove(self):
print("Which box do you want to delete? Type in coordinates.")
x = int(input("Please enter a column: "))
x -= 1
y = int(input("Please enter a row: "))
y -= 1
self.myList[x][y] = 0
print()
for i in self.myList:
print(i)
menu()
def view(self):
for i in self.myList:
print(i)
menu()
array = Array()
def menu():
print()
print()
print()
print("****************")
print(" MENU")
print("****************")
print("Please choose:")
print("1. Add an item to the array")
print("2. Remove an item from the array")
print("3. View array")
print()
print("0. Quit")
print("****************")
option = int(input("Enter (1, 2 or 0): "))
print()
if option == 1:
array.input()
elif option == 2:
array.remove()
elif option == 3:
array.view()
elif option == 0:
quit()
else:
print("Error..")
menu()

Resources