Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I only have to do this:
Take a string entered by the user and print the game grid as in the previous stage.
Analyze the game state and print the result.
Like this:
1. Enter cells: XXXOO__O_ ---------
| X X X |
| O O _ |
| _ O _ | ---------
X wins
The problem is that my program never reaches the elif statements and I donĀ“t know why.
n = input()
number_grid = []
Winner = ""
print("---------")
Cont = {"X": 0, "O": 0, "_": 0} # This will count to check for impossible games
for i in range(0, len(n), 3):
print("|", n[i], n[i+1], n[i+2], "|")
number_grid.append([n[i], n[i+1], n[i+2]])
Cont[n[i]] = Cont[n[i]] + 1
Cont[n[i + 1]] = Cont[n[i + 1]] + 1
Cont[n[i + 2]] = Cont[n[i + 2]] + 1
print("---------")
Impossible = False
if 2 <= Cont["X"] - Cont["O"] or Cont["X"] - Cont["O"] <= -2:
Impossible = True
print("Impossible")
exit()
if Winner == "" and Impossible is False:
for rows in range(0, 3): # Check winner in rows
if number_grid[rows][0] == number_grid[rows][1] == number_grid[rows][2] != "_":
Winner = number_grid[rows][0]
print(Winner, "wins")
for columns in range(0, 3): # Check winner in columns
if number_grid[0][columns] == number_grid[1][columns] == number_grid[2][columns] != "_":
Winner = number_grid[0][columns]
print(Winner, "wins")
if number_grid[0][0] == number_grid[1][1] == number_grid[2][2] != "_": # Check winner in first diagonal
Winner = number_grid[0][0]
print(Winner, "wins")
if number_grid[0][2] == number_grid[1][1] == number_grid[2][0] != "_": # Check winner in second diagonal
Winner = number_grid[0][2]
print(Winner, "wins")
elif Cont["_"] != 0:
print("Game not finished")
elif Cont["X"] + Cont["O"] == 9:
print("Draw")
Reducing your code down...
Winner = ""
Impossible = False
if Winner == "" and Impossible is False:
# Stuff
elif Cont["_"] != 0:
print("Game not finished")
elif Cont["X"] + Cont["O"] == 9:
print("Draw")
In your current code, it's not possible for Winner != "" or Impossible != True. So you will never enter the elif statement.
Related
My code for now works as desired where the user can input a level 1-3 depending on how hard they would like it to be (1-3 being the amount of digits the numbers will have in the math equation), and then must solve math equations. Those math equations will output EEE if the answer is incorrect and everything works as planned if you correctly answer the question as it exits the function and adds one total_correct_answers variable at the bottom, then will prompt you with another equation. However, if you input an incorrect answer and then a correct answer, you will just be prompted with the same question over and over again without the try loop being truly broken out of and total_correct_answers not being incremented positively by 1. The incrementation block of code is at lines 61-65, and the equation code is lines 30-49.
import random
def main():
ten_questions()
def get_level():
while True:
try:
level_input = int(input("Level: "))
if level_input in [1,2,3]:
return level_input
except:
pass
def integer_generator(level):
if level == 1:
x = random.randint(0,9)
y = random.randint(0,9)
elif level == 2:
x = random.randint(10, 99)
y = random.randint(10, 99)
else:
x = random.randint(100, 999)
y = random.randint(100, 999)
return x, y
def question_generator(x, y):
real_answer = x + y
wrong_counter = 0
while True:
try:
answer_given = input(str(x) + " + " + str(y) + " = ")
if int(answer_given) == real_answer:
if wrong_counter == 0:
return True
elif int(answer_given) == real_answer and wrong_counter != 0:
break
else:
while wrong_counter < 2:
print("EEE")
wrong_counter +=1
break
else:
print(str(x) + " + " + str(y) + " = " + str(real_answer))
print("False, that was last attempt")
break
except:
print("EEE")
pass
def ten_questions():
num_of_questions = 0
total_correct_answers = 1
my_level = get_level()
correct_answers = question_generator(*integer_generator(my_level))
while num_of_questions <= 8:
question_generator(*integer_generator(my_level))
num_of_questions +=1
if correct_answers == True:
total_correct_answers +=1
print("Score: " + str(total_correct_answers))
if __name__ == "__main__":
main()
Because of your line 36:
if int(answer_given) == real_answer: happens when someone answers correctly, wether they are right or wrong. So it enters the if, and then faces if wrong_counter == 0: which discards wrong answers. So just replace those two lines with if int(answer_given) == real_answer and wrong_counter == 0: and you are good to go.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
Im trying to put in valid numbers into the board and meet all the conditions for the game.
The code doesnt run for some reason.
board = [
[0,0,6,9,0,5,0,1,0],
[9,7,0,0,1,2,3,0,5],
[0,2,0,0,0,4,8,6,0],
[5,0,3,8,0,0,0,2,0],
[0,0,0,0,0,0,0,0,0],
[0,8,0,0,0,1,9,0,7],
[0,5,4,1,0,0,0,7,0],
[2,0,7,4,5,0,0,9,3],
[0,6,0,7,0,3,1,0,0]
]
#cheking that the 3x3 squares dont have sum of 45, game continues if False
def check_conditions():
a = board[0][0:3] + board[1][0:3] + board[2][0:3]
b = board[3][0:3] + board[4][0:3] + board[5][0:3]
c = board[6][0:3] + board[7][0:3] + board[8][0:3]
d = board[0][3:6] + board[1][1:6] + board[2][1:6]
e = board[3][3:6] + board[4][1:6] + board[5][1:6]
f = board[6][3:6] + board[7][1:6] + board[8][1:6]
g = board[0][6:9] + board[1][6:9] + board[2][6:9]
h = board[3][6:9] + board[4][6:9] + board[5][6:9]
i = board[6][6:9] + board[7][6:9] + board[8][6:9]
all_squares = [a,b,c,d,e,f,g,h,i]
for i in all_squares:
if sum(i) != 45:
return False
#checking for duplicate in row, this function is under check_conditions()
for i in board:
if len(i) != len(set(i)):
return False
#checking that there no zeros in the board
def zero_condition():
for i in board:
for j in i:
if j == 0:
return False
#checking for duplicates in column
def get_column(col, board):
column = []
for i in range(len(board)):
column.append(board[i][col])
return column
all_column = [get_column(0, board), get_column(1, board), get_column(2, board), get_column(3, board), get_column(4, board), get_column(5, board), get_column(6, board), get_column(7, board), get_column(8, board)]
def check_column():
for i in all_column:
if len(i) != len(set(i)):
return False
#putting numbers into chosen rows and column
def choose_cell():
row = int(input("choose row:"))
column = int(input("choose column:"))
choose_num = int(input("choose a num between 1 og 9:"))
if 0< choose_num <=9:
board[row][column] = choose_num
else:
print("illegal num try again")
choose_cell()
#this is where the game starts
def begin_soduko():
answer= input("play soduko?")
if answer == "yes":
while zero_condition() == False and check_conditions == False and check_column() == False:
choose_cell()
print("you have finished soduko!!!")
I copy pasted all your code into a script and attempted to run it. If this is all your code, the first thing you are missing is a call to "begin_sudoku()" before your finishing print statement.
Afterwards, I ran it and was able to be asked whether to play, but entering "yes" still ended the game despite all three conditions being false. I found the last reason your game isn't running is because you are forgetting the parenthesis on "check_conditions()" when checking conditions in the while loop. I added the () to the end of it along with the call to begin_sudoku() and the game ran fine for me.
def begin_soduko():
answer= input("play soduko?")
if answer == "yes":
while zero_condition() == False and check_conditions() == False and check_column() == False:
choose_cell()
begin_soduko()
print("you have finished soduko!!!")
Replace your last code block with this and it should finally run.
I am making a connect four game with X's and O's. The code for checking for four in a row/column/diagonal works but I have a lot of if statements in my code. The game fully works right now but I'm wondering if there is an easier solution to the checking. Below, I have included all my code for context.
I have tried using coordinates. It seems kind of inefficient though. The function for checking is called check.
namex = input("Player X, enter your name. ") #asks for player 1 name
nameo = input("Player O, enter your name. ") #asks for player 2 name
game = [[".", ".", ".", ".", ".", "."], #gameboard
[".", ".", ".", ".", ".", "."],
[".", ".", ".", ".", ".", "."],
[".", ".", ".", ".", ".", "."],
[".", ".", ".", ".", ".", "."],
[".", ".", ".", ".", ".", "."],
[".", ".", ".", ".", ".", "."]]
loop = True
def output(matrix):
str1 = ""
str2 = ""
str3 = ""
str4 = ""
str5 = ""
str6 = ""
print("0 1 2 3 4 5 6 ") #print labels for columns in gameboard
for a in matrix:
row = 0
for b in a: #"a" is a column and "b" is a ./x/o
row += 1
if row == 1:
str1 += b
str1 += " "
if row == 2:
str2 += b
str2 += " "
if row == 3:
str3 += b
str3 += " "
if row == 4:
str4 += b
str4 += " "
if row == 5:
str5 += b
str5 += " "
if row == 6:
str6 += b
str6 += " "
print(str1) #print string for row 1
print(str2) #print string for row 2
print(str3) #print string for row 3
print(str4) #print string for row 4
print(str5) #print string for row 5
print(str6) #print string for row 6
def check(matrix): #function to check for four in row/column/diagonal to win
positionx = []
positiono = []
x = 0
for a in matrix:
y = 5
for b in a:
if b == "X":
positionx.append([x, y])
if b == "O":
positiono.append([x, y])
y -= 1
x += 1
for c1 in positionx:
'''check four in row/column/diagonal for x'''
for c2 in positionx:
for c3 in positionx:
for c4 in positionx:
if c4[0]-c3[0] == 1:#check for four in row
if c3[0]-c2[0] == 1:
if c2[0]-c1[0] == 1:
return "xwin"
if c4[1]-c3[1] == 1: #check for four in column
if c3[1]-c2[1] == 1:
if c2[1]-c1[1] == 1:
return "xwin"
if c4[0]-c3[0] == 1: #check four in diagonal
if c4[1]-c3[1] == 1:
if c3[0]-c2[0] == 1:
if c3[1]-c2[1] == 1:
if c2[0]-c1[0] == 1:
if c2[1]-c1[1] == 1:
return "xwin"
for d1 in positiono:
'''check four in row/column/diagonal for o'''
for d2 in positiono:
for d3 in positiono:
for d4 in positiono:
if d4[0]-d3[0] == 1: #check for four in row
if d3[0]-d2[0] == 1:
if d2[0]-d1[0] == 1:
return "owin"
if d4[1]-d3[1] == 1: #check for four in column
if d3[1]-d2[1] == 1:
if d2[1]-d1[1] == 1:
return "owin"
if d4[0]-d3[0] == 1: #check four in diagonal
if d4[1]-d3[1] == 1:
if d3[0]-d2[0] == 1:
if d3[1]-d2[1] == 1:
if d2[0]-d1[0] == 1:
if d2[1]-d1[1] == 1:
return "owin"
while loop == True:
xinput = input(namex + ", you're X. What column do you want to play in? Please enter a number 0-6 ")
xcolumn = int(xinput)
xrow = 5
occupied1 = False
while occupied1 == False:
if game[xcolumn][xrow] == ".": #if there is a "." change to "X"
game[xcolumn][xrow] = "X"
output(game)
occupied1 = True
xrow -= 1
if check(game) == "xwin":
loop = False
print(namex + " wins!")
break
if check(game) == "owin":
loop = False
print(nameo + " wins!")
break
oinput = input(nameo + ", you're O. What column do you want to play in? Please enter number 0-6 ")
ocolumn = int(oinput)
orow = 5
occupied2 = False
while occupied2 == False:
if game[ocolumn][orow] == ".": #if there is a "." change to "O"
game[ocolumn][orow] = "O"
output(game)
occupied2 = True
orow -= 1
if check(game) == "xwin":
loop = False
print(namex + " wins!")
break
if check(game) == "owin":
loop = False
print(nameo + " wins!")
break
I'm also open to any other suggestions to make my code for this game better. Thanks!
I had some spare time, so I rewrote your program. It's much more efficient now. Read the comments to understand how it works
cols = [[] for x in range(6)]
# I opted to have a matrix of COLUMNS rather than rows because you can easily
# append items to the end of the list to simulate a real tile being placed there
# it's more intuitive and saves us time, as you'll see
def checkWin(cols):
for i in range(6): # Each column
for j in range(6): # Each row
try: #check if the element at these coordinates exists yet
cols[i][j]
except IndexError:
break
# go back to next i - impossible that there's anything with a higher
# j because if a list is n items long, and we go to j (which is one
# higher than n and doesn't exist) then there can't be an element at
# index j + someNumber.
ret = False
try: #vertical: j is the index in each column, so this goes up the column
if cols[i][j] == cols[i][j+1] == cols[i][j+2] == cols[i][j+3] is not None:
ret = True
except IndexError: #one of the elements of the comparison doesn't exist
pass #We can't be sure that none of the other trials will return True
try: #horizontal
if cols[i][j] == cols[i+1][j] == cols[i+2][j] == cols[i+3][j] is not None:
ret = True
except IndexError:
pass
try: #diagonal
if cols[i][j] == cols[i+1][j+1] == cols[i+2][j+2] == cols[i+3][j+3] is not None:
ret = True
except IndexError:
pass
try: #other diagonal
if cols[i][j] == cols[i-1][j+1] == cols[i-2][j+2] == cols[i-3][j+3] is not None:
ret = True
except IndexError:
pass
if ret:
return cols[i][j]
return None # We've gone through every single possible element and there are NO matches
def printBoard(cols):
# Pretty intuitive function IMO - we swap i and j to go through rows.
returnstr = '\n1 2 3 4 5 6\n'
for i in range(6):
for j in range(6):
try:
cols[j][5-i]
except IndexError:
returnstr += '_ '
continue
returnstr += cols[j][5-i]+' '
returnstr += '\n'
print(returnstr)
playerX = input('Player X, input your name: ')
playerO = input('Player O, input your name: ')
if playerX == playerO:
print("Cannot have the same name!")
exit()
count = 0
while not checkWin(cols):
printBoard(cols)
i = input('{}, input your column (1-6): '.format(playerO if count else playerX))
try:
target = cols[int(i)-1]
if len(target) == 6:
print("Column {} is already full! Please pick another.".format(i))
continue
target.append('O' if count else 'X')
except ValueError:
print("'{}' is not a number! Try again.".format(i))
continue
except IndexError:
print("{} is not a valid column number! Please pick another.".format(i))
continue
count = (count+1) % 2
printBoard(cols)
if checkWin(cols) == 'X':
print('{} (Player X), you win!'.format(playerX))
else:
print('{} (Player O), you win!'.format(playerO))
A good start would be to write a generalized function that checks for a diagonal at an arbitrary location:
def diagonal(grid, x, y, piece):
'''
Return True if grid contains a four-in-a-row diagonal starting at coordinates
(x, y) and traveling downwards and to the right. Otherwise return False.
'''
for i in range(x, x+4):
# if this square does not contain the desired piece, return False
if grid[x+i][y+i] != piece
return False
# if we got all the way through the loop, this must be a diagonal
return True
Then you would call this function for every possible starting coordinate of a four square diagonal, for each player X and O.
To improve this function, you could add a way to check for diagonals that travel the other direction (up and to the right).
Ok I have a feeling that this is a simple simple issue but I have been staring at this code for about 10 hours now.
The issue I am having is in mastermind is that once I get it to recognize that I have the correct colors in the right spot I can get it to display the right spots with X and the wrong spots with O. I need to be able to convert that so instead of X and O I need it to tell the user that he/she has 2 blacks and one white
For example: The secret code is RGYB The user enters RGOY so then Python relays "You have 2 blacks(The R and G spots) and one 1 White (The Y because it's the right color just in the wrong index) As of right now I got it to display X for the right color in the right spot and anything else it is an O
I will post what I have been working with now but today I am at my wit's end
https://pastebin.com/HKK0T7bQ
if correctColor != "XXXX":
for i in range(4):
if guess[i] == tempCode[i]:
correctColor += "X"
if guess[i] != tempCode[i] in tempCode:
correctColor += "O"
print (correctColor + "\n")
if correctColor == "XXXX":
if attempts == 1:
print ("You think you are sweet because you got it right on the first try? Play me again!")
else:
print ("Well done... You needed " + str(attempts) + " attempts to guess.")
game = False
A few comments
X and O
you use X and 0 to denote the success, it will be easier and faster to use a list or tuple or booleans for this, that way you can use sum() to count how many colors and locations were correct. Then whether you represent that with X and O or red and white pins is a matter for later
compartmentalization
Your game logic (guess input, input validation, do you want to continue, etc) is mixed with the comparison logic, so it would be best to separate the different functions of your program into different methods.
This is an fineexample to introduce object oriented programming, but is so simple it doesn't need OO, but it can help. What you need is a method which takes a series of colours and compares it to another series of colours
Standard library
Python has a very extended standard library, so a lot of stuff you want to do probably already exists
Correct colours
to count the number of letters which occur in 2 strings, you can use collections.Counter
guess = "RGOY "
solution = "RGYB"
a = collections.Counter(guess)
b = collections.Counter(solution)
a & b
Counter({'G': 1, 'R': 1, 'Y': 1})
correct_colours = sum((a & b).values())
3
So the user guessed 3 colours correctly
Correct locations
can be solved with an easy list comprehension
[g == s for g, s in zip(guess, solution)]
[True, True, False, False]
sum(g == s for g, s in zip(guess, solution))
2
so the used put 2 colours on the correct location
This is a MasterMind I made in Python. Hope you like it and it helped you! :)
import random
import time
from tkinter import *
def select_level():
global level
level = level_selector.get()
root.destroy()
root = Tk()
level_selector = Scale(root, from_=1, to=3, tickinterval=1)
level_selector.set(0)
level_selector.pack()
Button(root, text="Select a difficulty level", command=select_level).pack()
mainloop()
cpc_1_digit = 0
cpc_2_digit = 0
cpc_3_digit = 0
cpc_4_digit = 0
p_1_digit = 0
p_2_digit = 0
p_3_digit = 0
p_4_digit = 0
correct_correct = 0
correct_wrong = 0
chances = 0
if level == 1:
chances = 15
elif level == 2:
chances = 10
else:
chances = 7
cpc_1_digit = random.randint(0, 9)
while cpc_2_digit == cpc_1_digit or cpc_2_digit == cpc_3_digit or cpc_2_digit ==
cpc_4_digit:
cpc_2_digit = random.randint(0, 9)
while cpc_3_digit == cpc_1_digit or cpc_3_digit == cpc_2_digit or cpc_3_digit ==
cpc_4_digit:
cpc_3_digit = random.randint(0, 9)
while cpc_4_digit == cpc_1_digit or cpc_4_digit == cpc_2_digit or cpc_4_digit ==
cpc_3_digit:
cpc_4_digit = random.randint(0, 9)
while chances > 0:
correct_correct = 0
correct_wrong = 0
answer = input("Enter a four-digit number with different digits (e.g 1476): ")
p_1_digit = int(answer[0])
p_2_digit = int(answer[1])
p_3_digit = int(answer[2])
p_4_digit = int(answer[3])
if p_1_digit == cpc_1_digit:
correct_correct = int(correct_correct) + 1
elif p_1_digit == cpc_2_digit or p_1_digit == cpc_3_digit or p_1_digit ==
cpc_4_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
if p_2_digit == cpc_2_digit:
correct_correct = correct_correct + 1
elif p_2_digit == cpc_1_digit or p_2_digit == cpc_3_digit or p_2_digit ==
cpc_4_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
if p_3_digit == cpc_3_digit:
correct_correct = int(correct_correct) + 1
elif p_3_digit == cpc_1_digit or p_3_digit == cpc_2_digit or p_3_digit ==
cpc_4_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
if p_4_digit == cpc_4_digit:
correct_correct = int(correct_correct) + 1
elif p_4_digit == cpc_1_digit or p_4_digit == cpc_3_digit or p_4_digit ==
cpc_2_digit:
correct_wrong = int(correct_wrong) + 1
else:
pass
print("")
if int(correct_correct) == 4:
print("Congratsulations! You found the computer's number!")
break
elif int(correct_wrong) > 0 or int(correct_correct) >= 1 and int(correct_correct)
< 4:
print("You got " + str(correct_correct) + " correct digit(s) in the correct
place, and " + str(correct_wrong) + " correct digit(s) but in wrong place.")
elif int(correct_correct) == 0 and int(correct_wrong) == 0:
print("You didn't guess any number, try again!")
else:
raise Exception("CheckError: line 69, something went wrong with the
comparings.")
exit()
print("")
chances = chances - 1
if chances == 0:
print("You lost... The secret number was " + str(cpc_1_digit) + str(cpc_2_digit)
+ str(cpc_3_digit) + str(cpc_4_digit) + ". Try again by rerunning the program.")
time.sleep(4)
I am a beginner with python, and I am creating a two player tic tac toe game in terminal. In total, this code takes up 139 lines, (this below being the relevant part of code I am having trouble with), however, this CheckWin function takes up around 40 lines of code, which I think is quite a lot compared to the amount of lines in this code, and considering that it performs a somewhat basic function. Basically, in the game, this function checks whether a row, column, or diagonal, has three X's or three O's, and if it does, it assigns X to the winner and O to the winner. Anyway, here is the code.
X = "X"
O = "O"
empty = " "
S = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
def CheckWin(S):
global winner
winner = ""
if S[0] == S[1] == S[2] != empty:
if S[0] == X:
winner = X
if S[0] == O:
winner = O
if S[3] == S[4] == S[5] != empty:
if S[3] == X:
winner = X
if S[3] == O:
winner = O
if S[6] == S[7] == S[8] != empty:
if S[6] == X:
winner = X
if S[6] == O:
winner = O
if S[0] == S[3] == S[6] != empty:
if S[0] == X:
winner = X
if S[0] == O:
winner = O
if S[1] == S[4] == S[7] != empty:
if S[1] == X:
winner = X
if S[1] == O:
winner = O
if S[2] == S[5] == S[8] != empty:
if S[2] == X:
winner = X
if S[2] == O:
winner = O
if S[0] == S[4] == S[8] != empty:
if S[0] == X:
winner = X
if S[0] == O:
winner = O
if S[2] == S[4] == S[6] != empty:
if S[2] == X:
winner = X
if S[2] == O:
winner = O
Basically, I need help making the function much much simpler. However, I do not want to eliminate the X, O, and winner variables, nor do I want to eliminate the list index method with the list S. Even though, is there a way to simplify all these If statements, keeping these things? If so, how?
Your code looks for "trios" of positions; you might as well have an object that holds this info:
trios = ((0,1,2), (3,4,5), (6,7,8), (0,3,6), (1,4,7), (2,5,8), (0,4,8), (2,4,6))
Then CheckWin would just loop through every trio, do that check you're doing, and return a winner if the trio matches. This way, CheckWin would be less than 10 lines of code.
I don't want to give it all away because I'm sure you can do it :)
Also, you don't need a global variable called "winner" inside CheckWin; just have CheckWin return the winner (or ""), and store the result in a variable outside the function itself.
I.e.
winner = CheckWin(S)
Have you tried using a loop instead?
X, O = 'X', 'O'
S = [X,O,X,O,X,O,O,X,O] # Test values
def CheckWin(S):
index = 0
has_winner = False
while index < len(S):
print index
if index <= 6: # after this point you won't find a winner (or you run this after every turn?)
if (index % 3 == 0 and S[index] == S[index + 1] and S[index] == S[index + 2]): # horizontals
has_winner = True
elif index < 3: # verticals and diagonals (you only need the first row to know this)
if (S[index] == S[(index + 3)] and S[index] == S[index + 6]) or \
(index == 0 and S[index] == S[4] and S[index] == S[8]) or \
(index == 2 and S[index] == S[4] and S[index] == S[6]):
has_winner = True
if has_winner: # I'm using this to prevent duplicating code above (one if less)
if S[index] in [X,O]:
return S[index]
index += 1
return has_winner # If we have a winner but the X or O criterion isn't met, it returns False
winner = CheckWin(S)