I'm trying to figure out how to implement a function that will store and print where the user wants to place an "X" in the game of Tic Tac Toe. If there are any other suggests you have to fix my code, it would be greatly appreciated. I just started coding so apologies if it looks terrible.
def print_board():
game_board = ["-", "-", "-", "-", "-", "-", "-", "-", "-"]
print(game_board[0] + " | " + game_board[1] + " | " + game_board[2])
print(game_board[3] + " | " + game_board[4] + " | " + game_board[5])
print(game_board[6] + " | " + game_board[7] + " | " + game_board[8])
print_board()
#selecting a space on the board
selection = int(input("Select a square: "))
try:
if selection > 9 or selection < 1:
print("Sorry, please select a number between 1 and 9.")
else:
print(selection)
except ValueError:
print("Oops! That's not a number. Try again...")
You just need to keep asking until you get a valid number. Also, you need the "try" statement to wrap the function that will fail, in this case the int function. Here's a way to do it without try/except, which is really not the best choice here.
while True:
#selecting a space on the board
selection = input("Select a square: ")
if selection.isdigit():
selection = int(selection)
if 1 <= selection <= 9:
break
print("Sorry, please select a number between 1 and 9.")
else:
print("Oops! That's not a number. Try again...")
Your code looks alright, there are a couple of things to look at though. First, you are storing the game_board inside of the print_board() function, so each time you run print_board() the gamestate resets. Also, your code does not update the board when the user types a number. This can be fixed by changing the corresponding value of the board to an "X", and for a list this is as simple as game_board[selection] = "X". So after those two changes your file might look like this:
game_board = ["-", "-", "-", "-", "-", "-", "-", "-", "-"]
def print_board():
print(game_board[0] + " | " + game_board[1] + " | " + game_board[2])
print(game_board[3] + " | " + game_board[4] + " | " + game_board[5])
print(game_board[6] + " | " + game_board[7] + " | " + game_board[8])
print_board()
#selecting a space on the board
selection = int(input("Select a square: "))
try:
if selection > 9 or selection < 1:
print("Sorry, please select a number between 1 and 9.")
else:
game_board[selection] = "X"
except ValueError:
print("Oops! That's not a number. Try again...")
print_board()
Related
I can't figure out how to make this code give me the output I need. It is supposed to ask the user where they want to go on vacation, and then display the location they have chosen.
print("Congratulations! You have won an all-inclusive vacation!" + '\n')
input("Please enter your first and last name" + '\n')
print("Please choose where would you like to go on vacation?" + '\n'
+ "A. The Bermuda Triangle" + '\n'
+ "B. Space" + '\n'
+ "C. Antarctica" + '\n')
def choose_location():
if choose_location == "A":
print("You chose The Bermuda Triangle")
elif choose_location == "B":
print("You chose Space")
elif choose_location == "C":
print("You chose Antarctica")
choose_location()
not sure why you need the function
your code has a few problems.
first, don't use the same function name as the variable name.
second, instead of print, it should be input.
third, you need to save inputs to variables so you can use them.
but you need to use the input instead of print, and save the input to a variable,
print("Congratulations! You have won an all-inclusive vacation!" + '\n')
name = input("Please enter your first and last name" + '\n')
def choose_location():
location = input("Please choose where would you like to go on vacation?" + '\n'
+ "A. The Bermuda Triangle" + '\n'
+ "B. Space" + '\n'
+ "C. Antarctica" + '\n')
if location == "A":
print("You chose The Bermuda Triangle")
elif location == "B":
print("You chose Space")
elif location == "C":
print("You chose Antarctica")
choose_location()
or even a version that make-use of the function.
Notice that I added .upper() so even if the user enters a small letter it will still work
def choose_location(location):
location = location.upper()
if location == "A":
print("You chose The Bermuda Triangle")
elif location == "B":
print("You chose Space")
elif location == "C":
print("You chose Antarctica")
print("Congratulations! You have won an all-inclusive vacation!" + '\n')
name = input("Please enter your first and last name" + '\n')
choose_location(input("Please choose where would you like to go on vacation?" + '\n'
+ "A. The Bermuda Triangle" + '\n'
+ "B. Space" + '\n'
+ "C. Antarctica" + '\n'))
I'm somewhat of a beginner and I'm wondering if I'd be able to derive a Connect Four game out of my existing Tic Tac Toe game. I somewhat understand the mechanics, but am stumped at how to expand the board to 7 (rows) x 6 (columns). I know that there won't be any use for rows, because a column would be fine because a piece drops to the bottom of a Connect Four game. Below is my Tic Tac Toe code.
"""
Author: Victor Xu
Date: Jan 12, 2021
Description: An implementation of the game Tic-Tac-Toe in Python,
using a nested list, and everything else we've learned this quadmester!
"""
import random
def winner(board):
"""This function accepts the Tic-Tac-Toe board as a parameter.
If there is no winner, the function will return the empty string "".
If the user has won, it will return 'X', and if the computer has
won it will return 'O'."""
# Check rows for winner
for row in range(3):
if (board[row][0] == board[row][1] == board[row][2]) and \
(board[row][0] != " "):
return board[row][0]
# COMPLETE THE REST OF THE FUNCTION CODE BELOW
for col in range(3):
if (board[0][col] == board[1][col] == board[2][col]) and \
(board[0][col] != " "):
return board[0][col]
# Check diagonal (top-left to bottom-right) for winner
if (board[0][0] == board[1][1] == board[2][2]) and \
(board[0][0] != " "):
return board[0][0]
# Check diagonal (bottom-left to top-right) for winner
if (board[0][2] == board[1][1] == board[2][0]) and \
(board[0][2] != " "):
return board[0][2]
# No winner: return the empty string
return ""
def display_board(board):
"""This function accepts the Tic-Tac-Toe board as a parameter.
It will print the Tic-Tac-Toe board grid (using ASCII characters)
and show the positions of any X's and O's. It also displays
the column and row numbers on top and beside the board to help
the user figure out the coordinates of their next move.
This function does not return anything."""
print(" 0 1 2")
print("0: " + board[0][0] + " | " + board[0][1] + " | " + board[0][2])
print(" ---+---+---")
print("1: " + board[1][0] + " | " + board[1][1] + " | " + board[1][2])
print(" ---+---+---")
print("2: " + board[2][0] + " | " + board[2][1] + " | " + board[2][2])
print()
def make_user_move(board):
"""This function accepts the Tic-Tac-Toe board as a parameter.
It will ask the user for a row and column. If the row and
column are each within the range of 0 and 2, and that square
is not already occupied, then it will place an 'X' in that square."""
valid_move = False
while not valid_move:
row = int(input("What row would you like to move to (0-2):"))
col = int(input("What col would you like to move to (0-2):"))
if (0 <= row <= 2) and (0 <= col <= 2) and (board[row][col] == " "):
board[row][col] = 'X'
valid_move = True
else:
print("Sorry, invalid square. Please try again!\n")
def make_computer_move(board):
"""This function accepts the Tic-Tac-Toe board as a parameter.
It will randomly pick row and column values between 0 and 2.
If that square is not already occupied it will place an 'O'
in that square. Otherwise, another random row and column
will be generated."""
computer_valid_move = False
while not computer_valid_move:
row = random.randint(0, 2)
col = random.randint(0, 2)
if (0 <= row <= 2) and (0 <= col <= 2) and (board[row][col] == " "):
board[row][col] = 'O'
computer_valid_move = True
def main():
"""Our Main Game Loop:"""
free_cells = 9
users_turn = True
ttt_board = [[" ", " ", " "], [" ", " ", " "], [" ", " ", " "]]
while not winner(ttt_board) and (free_cells > 0):
display_board(ttt_board)
if users_turn:
make_user_move(ttt_board)
users_turn = not users_turn
else:
make_computer_move(ttt_board)
users_turn = not users_turn
free_cells -= 1
display_board(ttt_board)
if (winner(ttt_board) == 'X'):
print("Y O U W O N !")
elif (winner(ttt_board) == 'O'):
print("I W O N !")
else:
print("S T A L E M A T E !")
print("\n*** GAME OVER ***\n")
# Start the game!
main()
Also, I'm unsure how to check for a winning combination (connecting 4 in a row) since the board has become much larger. In a 3 x 3 tic tac toe board, I could list out the diagonal coordinates and that would be it, but it's much more difficult with a board larger than 4 x 4. Any guidance would be appreciated!
EDIT
I've created a 7 x 6 board for my Connect Four game, but now I don't know how to verify if a column's space is empty because Connect Four pieces drop to the bottom. Below is my code:
"""
Author: Victor Xu
Date: Jan 12, 2021
Description: An implementation of the game Tic-Tac-Toe in Python,
using a nested list, and everything else we've learned this quadmester!
"""
import random
def winner(board):
"""This function accepts the Tic-Tac-Toe board as a parameter.
If there is no winner, the function will return the empty string "".
If the user has won, it will return 'X', and if the computer has
won it will return 'O'."""
# No winner: return the empty string
return ""
def display_board(board):
"""This function accepts the Tic-Tac-Toe board as a parameter.
It will print the Tic-Tac-Toe board grid (using ASCII characters)
and show the positions of any X's and O's. It also displays
the column and row numbers on top and beside the board to help
the user figure out the coordinates of their next move.
This function does not return anything."""
print(" 0 1 2 3 4 5 6")
print(" " + board[0][0] + " | " + board[0][1] + " | " + board[0][2] + " | " + board[0][3] + " | " + board[0][
4] + " | " + board[0][5] + " | " + board[0][6])
print(" ---+---+---+---+---+---+---")
print(" " + board[1][0] + " | " + board[1][1] + " | " + board[1][2] + " | " + board[1][3] + " | " + board[1][
4] + " | " + board[1][5] + " | " + board[1][6])
print(" ---+---+---+---+---+---+---")
print(" " + board[2][0] + " | " + board[2][1] + " | " + board[2][2] + " | " + board[2][3] + " | " + board[2][
4] + " | " + board[2][5] + " | " + board[2][6])
print(" ---+---+---+---+---+---+---")
print(" " + board[3][0] + " | " + board[3][1] + " | " + board[3][2] + " | " + board[3][3] + " | " + board[3][
4] + " | " + board[3][5] + " | " + board[3][6])
print(" ---+---+---+---+---+---+---")
print(" " + board[4][0] + " | " + board[4][1] + " | " + board[4][2] + " | " + board[4][3] + " | " + board[4][
4] + " | " + board[4][5] + " | " + board[4][6])
print(" ---+---+---+---+---+---+---")
print(" " + board[5][0] + " | " + board[5][1] + " | " + board[5][2] + " | " + board[5][3] + " | " + board[5][
4] + " | " + board[5][5] + " | " + board[5][6])
print(" ---+---+---+---+---+---+---")
print(" " + board[6][0] + " | " + board[6][1] + " | " + board[6][2] + " | " + board[6][3] + " | " + board[6][
4] + " | " + board[6][5] + " | " + board[6][6])
print()
def make_user_move(board):
"""This function accepts the Tic-Tac-Toe board as a parameter.
It will ask the user for a row and column. If the row and
column are each within the range of 0 and 2, and that square
is not already occupied, then it will place an 'X' in that square."""
valid_move = False
while not valid_move:
col = int(input("What col would you like to move to (0-6):"))
if (0 <= col <= 6) and (board[col] == " "):
board[col] = 'X'
valid_move = True
else:
print("Sorry, invalid square. Please try again!\n")
def make_computer_move(board):
"""This function accepts the Tic-Tac-Toe board as a parameter.
It will randomly pick row and column values between 0 and 2.
If that square is not already occupied it will place an 'O'
in that square. Otherwise, another random row and column
will be generated."""
computer_valid_move = False
while not computer_valid_move:
col = random.randint(0, 6)
if (0 <= col <= 6) and (board[col] == " "):
board[col] = 'O'
computer_valid_move = True
def main():
"""Our Main Game Loop:"""
free_cells = 42
users_turn = True
ttt_board = [[" ", " ", " ", " ", " ", " ", " "], [" ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " "], [" ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " "], [" ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " "]]
while not winner(ttt_board) and (free_cells > 0):
display_board(ttt_board)
if users_turn:
make_user_move(ttt_board)
users_turn = not users_turn
else:
make_computer_move(ttt_board)
users_turn = not users_turn
free_cells -= 1
display_board(ttt_board)
if (winner(ttt_board) == 'X'):
print("Y O U W O N !")
elif (winner(ttt_board) == 'O'):
print("I W O N !")
else:
print("S T A L E M A T E !")
print("\n*** GAME OVER ***\n")
# Start the game!
main()
Whenever I enter a column number, it says that it's not a valid square...
You're currently checking if the column is 'X'
board[col] = 'X'
But the column can't be a string - because it's a list.
You need to check what the highest element with the value of 'X'. Replace
if board[col][6] == 'X':
print("Sorry, that column is full. Please try again!\n")
else:
for row in range(6, 0, -1):
if board[col][row] == 'X':
board[col][row + 1] = 'X'
valid_move = True
if not valid_move:
board[col][0] = 'X'
valid_move = True
You'll learn far better ways to work with lists as you continue to learn programming but this should get you started for now!
I am trying to create a tic-tac-toe game and keep running into this error when trying to replace an item in the board list with an 'X'. This is my code:
board = ["_", "_", "_",
"_", "_", "_",
"_", "_", "_"]
def display_board():
print(board[0] + " | " + board[1] + " | " + board[2])
print(board[3] + " | " + board[4] + " | " + board[5])
print(board[6] + " | " + board[7] + " | " + board[8])
def play():
print("----------------------------")
print("~~~ T I C T A C T O E ~~~ ")
print("----------------------------")
print("")
print("")
play_option = input("Would you like to play? 1 for 'Yes' and 2 for 'No' > ")
if int(play_option) ==1:
print("")
print("")
display_board()
else:
print("")
print("Okay, Bye!")
def turns():
pos = input("Where would you like to place? EX. 1, 2, 3.... > ")
This is where the space is being replaced with an 'X'
def placement():
if int(input) == 1:
board[0] = "X"
display_board()
elif int(input) == 2:
board[1] = "X"
display_board()
elif int(input) == 3:
board[1] = "X"
display_board()
play()
turns()
placement()
The error code:
Traceback (most recent call last):
File "C:/Users/Administrator/tiktactoe/Tik-Tac-TOe.py", line 51, in <module>
placement()
File "C:/Users/Administrator/tiktactoe/Tik-Tac-TOe.py", line 35, in placement
if int(input) == 1:
TypeError: int() argument must be a string, a bytes-like object or a number,
not 'builtin_function_or_method'
You can modify code like this.
board = ["_", "_", "_",
"_", "_", "_",
"_", "_", "_"]
def display_board():
print(board[0] + " | " + board[1] + " | " + board[2])
print(board[3] + " | " + board[4] + " | " + board[5])
print(board[6] + " | " + board[7] + " | " + board[8])
def play():
print("----------------------------")
print("~~~ T I C T A C T O E ~~~ ")
print("----------------------------")
print("")
print("")
play_option = input("Would you like to play? 1 for 'Yes' and 2 for 'No' > ")
if int(play_option) ==1:
print("")
print("")
display_board()
else:
print("")
print("Okay, Bye!")
def turns():
pos = input("Where would you like to place? EX. 1, 2, 3.... > ")
return pos
def placement(input):
if int(input) == 1:
board[0] = "X"
display_board()
elif int(input) == 2:
board[1] = "X"
display_board()
elif int(input) == 3:
board[1] = "X"
display_board()
play()
pos = turns()
placement(pos)
This happens, in your function placement, you are trying to transform an input to int(). The input from the user is stored in the variable: pos and you need to figure out some way to get this value into your function placement.
This could look like this:
def placement(input, type):
board[int(input) - 1] = type
display_board()
Where you would call this function from your turns function like this:
def turns(type):
pos = input("Where would you like to place {0}? EX. 1, 2, 3.... > ".format(type))
placement(pos, type)
I also made a small change to how your code runs:
play()
while True:
for i in ['X', 'O']:
turns(i)
Off course this should later be changed to while game_not_finished():
where you would check if the game is finished or not.
Hope this helps and good luck improving the game from this point!
Doing my homework rn and a bit stuck, why does the code execute "else" even thought the "if" has been satisfied? Ignore the sloppy code, I'm very new :/
order1 = input("What would you like to order?: \n \n" + "1: " + orderBurger + "\n" + "2: " + orderFries + "\n" + "3: " + orderDrink + "\n" + "\nAnswer = ")
while order == True:
if order1 == 1:
print("You have selected to order 1: " + orderBurger)
elif order1 == 2:
print("You have selected to order 1: " + orderFries)
elif order1 == 3:
print("You have selected to order 1: " + orderDrink)
else:
print("Invalid Input")
check = input("Is this your final item?:" + "1: " + q1 + "2: " + q2 + "Answer = ")
if check == 1:
print("Your items have been added to the basket")
break
elif check == 2:
check
elif check == 3:
check
else:
print("Invalid input")
This is the output
If you use type(order1), you'll see if your answer is a string or an int. If it's a string (and I think it is), you can convert it into int using int(order1), or replace your code by if order1 == '1'
Indentation is very important in Python. Based on how the indentations are implemented, the code blocks for conditions get executed.
A misplaced indent can lead to unexpected execution of a code block.
Here is a working demo of the ordering program
# File name: order-demo.py
moreItems = True
while (moreItems == True):
order = input("\n What would you like to order?\n"
+ " 1: Burger\n 2: Fries\n 3: Drink\n Answer = ")
if ((order == "1") or (order == "2") or (order == "3")):
print("You have selected to order " + order)
print("Your item has been added to the basket.\n")
else:
print("Invalid Input")
check = input("Is this your final item?: \n 1: Yes \n 2: No \n Answer = ")
if check == "1":
print("\n Thank you. Please proceed to checkout.")
moreItems = False
elif check == "2":
print("Please continue your shopping")
else:
print("Invalid input")
Output
$ python3 order-demo.py
What would you like to order?
1: Burger
2: Fries
3: Drink
Answer = 1
You have selected to order 1
Your item has been added to the basket.
Is this your final item?:
1: Yes
2: No
Answer = 2
Please continue your shopping
What would you like to order?
1: Burger
2: Fries
3: Drink
Answer = 2
You have selected to order 2
Your item has been added to the basket.
Is this your final item?:
1: Yes
2: No
Answer = 1
Thank you. Please proceed to checkout.
$
replace first line with this :
order1 = int( input("What would you like to order?: \n \n" + "1: " + orderBurger + "\n" + "2: " + orderFries + "\n" + "3: " + orderDrink + "\n" + "\nAnswer = ") )
I need this program to print out the number of guesses you got right and wrong. I have a dictionary (called ccdict) of cities and countries, e.g. "United Kingdom":"London". This is the code:
def choices (Correct):
list=[Correct]
f=0
cities=ccdict.values()
while f + 1<5:
f=f+1
list.append(cities[random.randint(0, len(cities))])
list.sort()
return list
countries = ccdict.keys()
randcountry = countries[random.randint(0, len(countries))]
print "What is the capital of " + randcountry + "?"
print "If you want to stop this game, type 'exit'"
randlist = choices(ccdict[randcountry])
for i in range(0,5):
print str(i+1) + " - " + randlist[i]
input=raw_input("Give me the number of the city that you think is the capital of " + randcountry + " ")
if input == "exit":
print "Now exiting game!" + sys.exit()
elif randlist[int(input)-1] == ccdict[randcountry]:
print "Correct"
else:
print "WRONG! The capital of " + randcountry + " is " + ccdict[randcountry]
Move your int() until after your if test:
input = raw_input("Give me the number of the city that you think is the capital of " + randcountry + " ")
if input == "exit":
print "Now exiting game!"
sys.exit()
elif randlist[int(input) - 1] == ccdict[randcountry]:
print "Correct"
Note how the above version only converts input to an integer at the last minute.