i'm making a small project in python that is tic tac toe game but i'm facing a problem here is my code though it is incomplete
now my problem is while running my code , i'm getting error 'position' is not defined
please solve my problem and thanks in advance !!
def display_board(testboard):
print(' | | ')
print(' '+testboard[1]+' | '+testboard[2]+' | '+testboard[3])
print(' | | ')
print('------------')
print(' | | ')
print(' ' + testboard[4] + ' | ' + testboard[5] + ' | ' +
testboard[6])
print(' | | ')
print('------------')
print(' | | ')
print(' ' + testboard[7] + ' | ' + testboard[8] + ' | ' +
testboard[9])
print(' | | ')
def board_marker():
marker = ' '
while not (marker == 'X' or marker =='O' or marker == 'x' or marker
=='o'):
marker = input('do you want x r o')
if marker.upper() == 'X' :
return ('X','O')
else:
return ('O','X')
def place_marker(board, position, marker):
board[positon] = marker
test_board= ['#','X','O','X','O','X','O','X','O','X','O']
place_marker(test_board, , '$')
display_board(test_board)
Try this:
def display_board(testboard):
print(' | | ')
print(' '+testboard[1]+' | '+testboard[2]+' | '+testboard[3])
print(' | | ')
print('------------')
print(' | | ')
print(' ' + testboard[4] + ' | ' + testboard[5] + ' | ' +
testboard[6])
print(' | | ')
print('------------')
print(' | | ')
print(' ' + testboard[7] + ' | ' + testboard[8] + ' | ' +
testboard[9])
print(' | | ')
def board_marker():
marker = ' '
while not (marker == 'X' or marker =='O' or marker == 'x' or marker =='o'):
marker = input('do you want x r o')
if marker.upper() == 'X' :
return ('X','O')
else:
return ('O','X')
def place_marker(board, position, marker):
board[position] = marker # make it position here from positon as Nicco Haase said
test_board= ['#','X','O','X','O','X','O','X','O','X','O']
place_marker(test_board, 1, '$') # pass a value for position too don't keep it empty
display_board(test_board)
Hope this helps...
Thanks
Related
I jumped into some Python courses a little while ago and have gotten to a milestone project to make a simple tic-tac-toe game.
But I am running into a bit of a wall due to an index error that keeps happening and I cannot figure out why.
The code is the following:
#Tic Tac Toe
game_list = [' '] * 10
turn_counter = 0
game_on = True
def show_game(game_list):
print(' | |')
print(' ' + game_list[7] + ' | ' + game_list[8] + ' | ' + game_list[9])
print(' | |')
print('-----------')
print(' | |')
print(' ' + game_list[4] + ' | ' + game_list[5] + ' | ' + game_list[6])
print(' | |')
print('-----------')
print(' | |')
print(' ' + game_list[1] + ' | ' + game_list[2] + ' | ' + game_list[3])
print(' | |')
def choose_position():
# Initial Variables
within_range = False
acceptable_values = [1,2,3,4,5,6,7,8,9]
choice = 'WRONG'
# While loop that keeps asking for input
while choice.isdigit() == False or within_range == False:
choice = input("Please choose a number between 1-9 like a numpad: ")
# DIGIT CHECK
if choice.isdigit() == False:
print("Sorry, that is not a digit!")
# RANGE CHECK
if choice.isdigit() == True:
if int(choice) in acceptable_values:
within_range = True
else:
print("Sorry, you are out of the acceptable range (1-9)")
return int(choice)
def insert_choice(game_list, position, turn_counter):
print(type(position))
print(position)
# Place the character in the game_list
if turn_counter%2 == 0 or turn_counter == 0:
game_list[position] = 'X'
else:
game_list[position] = 'O'
return (game_list, position)
def gameon_choice():
choice = 'wrong'
while choice not in ['Y', 'N']:
choice = input("Keep playing? (Y or N) ")
if choice not in ['Y', 'N', 'R']:
print("sorry, I don't understand, please choose Y or N ")
if choice == 'Y':
return True
else:
return False
while game_on:
show_game(game_list)
position = choose_position()
game_list = insert_choice(game_list,position,turn_counter)
turn_counter += turn_counter
show_game(game_list)
game_on = gameon_choice()
And the error I get is:
Exception has occurred: IndexError
tuple index out of range
File "Desktop/Tictactoe.py", line 9, in show_game
print(' ' + game_list[7] + ' | ' + game_list[8] + ' | ' + game_list[9])
File "Desktop/Tictactoe.py", line 79, in <module>
show_game(game_list)
What I think is happening is that during the assignment in the insert_choice function:
game_list[position] = 'X'
the list is somehow converted to a tuple and the variables are appended instead of assigned, and then when trying to display the list again it only has two elements leading to an index error, but I cannot figure out /why/.
I hope someone can help.
Sincerely,
The insert_choice() method returns a tuple of your game_list and position:
return (game_list, position)
Thus, during your main loop, you store this tuple as the new game_list and try to access indices greater than 1 which leads to this index error.
You can either only return game_list or unpack the returned tuple as:
game_list, position = insert_choice(game_list,position,turn_counter)
Since you don't change the value of position, you probably want to do the former.
I am making a list where i can input items into a grid, but the input will only be accepted if it is beside each other in that list.
this is my current codes:
basket = [ [' ', ' ', ' ', ' '],\
[' ', ' ', ' ', ' '],\
[' ', ' ', ' ', ' '],\
[' ', ' ', ' ', ' '] ]
total_moves = 1
while total_moves <= 16:
columns = ["A", "B", "C", "D"]
cols_string = ""
for n in range(4):
cols_string += " {:2}".format(columns[n])
#printing table
print("",cols_string, end="")
for idx, i in enumerate(basket):
print('\n ' + '+-----' * 4 + '+')
print(idx + 1, end=" ")
for j in i:
print('|{:^5}'.format(j), end = '')
print('|', end = '')
print('\n ' + '+-----' * 4 + '+')
fruit = input('What fruit do you want to place?(APL/BNA/ORG): ')
build_location = input('Build where? ')
#processing build location for exact position
build_location = list(build_location)
if build_location[0] == 'A':
loc = [int(build_location[1])-1, 0]
elif build_location[0] == 'B':
loc = [int(build_location[1])-1, 1]
elif build_location[0] == 'C':
loc = [int(build_location[1])-1, 2]
elif build_location[0] == 'D':
loc = [int(build_location[1])-1, 3]
if build_location[1] == 'A':
loc = [int(build_location[0])-1, 0]
elif build_location[1] == 'B':
loc = [int(build_location[0])-1, 1]
elif build_location[1] == 'C':
loc = [int(build_location[0])-1, 2]
elif build_location[1] == 'D':
loc = [int(build_location[0])-1, 3]
if basket[loc[0]][loc[1]] == ' ':
basket[loc[0]][loc[1]] = fruit
total_moves += 1
else:
print('That slot is taken!')
This is my current print, without keying in any inputs yet:
A B C D
+-----+-----+-----+-----+
1 | | | | |
+-----+-----+-----+-----+
2 | | | | |
+-----+-----+-----+-----+
3 | | | | |
+-----+-----+-----+-----+
4 | | | | |
+-----+-----+-----+-----+
What fruit do you want to place?(APL/BNA/ORG): #input here
Build where? #input here
I am trying to make it such that, if I enter the fruit to be beside each other(for exampleA1 and B1), the fruit will be printed out, but if the fruits are not beside each other(for exampleA1 and B2), the system will printCannot place fruit there!. Can anyone help me with this?
A B C D
+-----+-----+-----+-----+
1 | APL | BNA | | |
+-----+-----+-----+-----+
2 | | ORG | | |
+-----+-----+-----+-----+
3 | | | | |
+-----+-----+-----+-----+
4 | | | | |
+-----+-----+-----+-----+
#code continues to run as the fruits are all connected to each other
A B C D
+-----+-----+-----+-----+
1 | | | | |
+-----+-----+-----+-----+
2 | | ORG | BNA | |
+-----+-----+-----+-----+
3 | | | | |
+-----+-----+-----+-----+
4 | | | | |
+-----+-----+-----+-----+
#code continues to run as fruits are connected
A B C D
+-----+-----+-----+-----+
1 | | | | |
+-----+-----+-----+-----+
2 | | | BNA | |
+-----+-----+-----+-----+
3 | | ORG | | |
+-----+-----+-----+-----+
4 | | | | |
+-----+-----+-----+-----+
#code will not run as BNA and ORG are not beside each other
A B C D
+-----+-----+-----+-----+
1 | APL | BNA | BNA | |
+-----+-----+-----+-----+
2 | | | | ORG |
+-----+-----+-----+-----+
3 | | | | |
+-----+-----+-----+-----+
4 | | | | |
+-----+-----+-----+-----+
#code will not run for ORG's input as ORG is not connected to the rest of the fruits,
so system will print 'Cannot place fruit here!' and ask user to place it again, only
continuing if ORG is at D1 or C2
This means for the first run, the code will accept any inputs, but for the second run onwards the code will only accept inputs which are beside the first input.
Your code seems very neat so far and I really like your idea! Here's the implementation I came up with so far so that fruits can only be placed directly adjacent (not diagonally) to other fruits:
basket = [ [' ', ' ', ' ', ' '],\
[' ', ' ', ' ', ' '],\
[' ', ' ', ' ', ' '],\
[' ', ' ', ' ', ' '] ]
total_moves = 1
placed = [] #new
def valid(build_location, placed): #new
for loc in placed:
if abs(ord(loc[0]) - ord(build_location[0])) == 1 and loc[1] == build_location[1]:
return True
if abs(ord(loc[1]) - ord(build_location[1])) == 1 and loc[0] == build_location[0]:
return True
if len(placed) == 0:
return True
return False
while total_moves <= 16:
columns = ["A", "B", "C", "D"]
cols_string = ""
for n in range(4):
cols_string += " {:2}".format(columns[n])
#printing table
print("",cols_string, end="")
for idx, i in enumerate(basket):
print('\n ' + '+-----' * 4 + '+')
print(idx + 1, end=" ")
for j in i:
print('|{:^5}'.format(j), end = '')
print('|', end = '')
print('\n ' + '+-----' * 4 + '+')
fruit = input('What fruit do you want to place?(APL/BNA/ORG): ')
build_location = input('Build where? ')
#processing build location for exact position
build_location = list(build_location)
if valid(build_location, placed): #new
placed.append(build_location)
if build_location[0] == 'A':
loc = [int(build_location[1])-1, 0]
elif build_location[0] == 'B':
loc = [int(build_location[1])-1, 1]
elif build_location[0] == 'C':
loc = [int(build_location[1])-1, 2]
elif build_location[0] == 'D':
loc = [int(build_location[1])-1, 3]
if build_location[1] == 'A':
loc = [int(build_location[0])-1, 0]
elif build_location[1] == 'B':
loc = [int(build_location[0])-1, 1]
elif build_location[1] == 'C':
loc = [int(build_location[0])-1, 2]
elif build_location[1] == 'D':
loc = [int(build_location[0])-1, 3]
if basket[loc[0]][loc[1]] == ' ':
basket[loc[0]][loc[1]] = fruit
total_moves += 1
else: #new
print('That spot is taken!')
else: #new
print('Can not place fruit there!')
Let me explain the code now:
First, I created an array to store the positions of fruit that have already been placed. For simplicity, I altered the code so that it would only accept positions that are placed like (A1, B2, C2, D4) and not (1A, 2B, 2C, 4D).
Next, I created a function that verifies whether or not the position is valid. This is done by looping through the array and comparing it to other fruits. If the difference in letters is 1 AND the numbers are the same, it is valid. If the difference in numbers is 1 AND the letters are the same, it is valid.
Additionally, there is an if statement at the bottom of the code that makes sure it does not overlap another fruit and gives a separate error message.
Let me know if you have any other questions!
I am wondering if I can make a table like shown with nested loops:
A B C D
+---+---+---+---+
1 | | | | |
+---+---+---+---+
2 | | | | |
+---+---+---+---+
3 | | | | |
+---+---+---+---+
4 | | | | |
+---+---+---+---+
This is my current code and results:
total_moves = 1
while total_moves <= 10:
print('Turn {}'.format(total_moves))
map = [ [' ', ' ', ' ', ' '],\
[' ', ' ', ' ', ' '],\
[' ', ' ', ' ', ' '],\
[' ', ' ', ' ', ' '] ]
for i in map:
print('\n' + '+---' * 4 + '+')
for j in i:
print('|{:^3}'.format(j), end = '')
print('|', end = '')
print('\n' + '+---' * 4 + '+')
chara = input('Please enter character to be added into box: ')
position = input('Please enter position where the character will be in: ')
Turn 1
+---+---+---+---+
| | | | |
+---+---+---+---+
| | | | |
+---+---+---+---+
| | | | |
+---+---+---+---+
| | | | |
+---+---+---+---+
Please enter character to be added into box:
Please enter position where the character will be in:
I am having issues with printing the numbers and alphabets, because I am relatively new to nested loops. Tried doing print( A B C D )but am looking for a better way to print it. Thank you!
Here is what I came up so far:
total_moves = 1
while total_moves <= 10:
print('Turn {}'.format(total_moves))
map = [ [' ', ' ', ' ', ' '],\
[' ', ' ', ' ', ' '],\
[' ', ' ', ' ', ' '],\
[' ', ' ', ' ', ' '] ]
columns = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P",\
"Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
size = len(map)
cols_string = ""
for n in range(size):
cols_string += " {} ".format(columns[n])
print(cols_string, end="")
for idx, i in enumerate(map):
print('\n ' + '+---' * size + '+')
print(idx + 1, end=" ")
for j in i:
print('|{:^3}'.format(j), end = '')
print('|', end = '')
print('\n ' + '+---' * size + '+')
I added the columns list so that it can pick the column names depending on the size of the grid (assuming it won't be larger than 26x26).
Also added the size attribute so the display of the grid also adapts to the data.
I used enumerate to have the index of the line and print it in front of it.
One thing you'll have to figure out is how to properly display the cols_string because I didn't have the time to fix that.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
So I am trying to create a dungeon type game for my assignment. But I have no clue how to create a map like that with a nested list? Any help would be appreciated.
Example of the map:
+---+---+---+---+---+---+---+---+
| T | | | | | | | |
+---+---+---+---+---+---+---+---+
| | | | T | | | | |
+---+---+---+---+---+---+---+---+
| | | | | | T | | |
+---+---+---+---+---+---+---+---+
| | T | | | | | | |
+---+---+---+---+---+---+---+---+
| | | | | | | | |
+---+---+---+---+---+---+---+---+
| | | | | | | | |
+---+---+---+---+---+---+---+---+
| | | | | T | | | |
+---+---+---+---+---+---+---+---+
| | | | | | | | K |
+---+---+---+---+---+---+---+---+
The list:
world_map = [['T', ' ', ' ', ' ', ' ', ' ', ' ', ' '],\
[' ', ' ', ' ', 'T', ' ', ' ', ' ', ' '],\
[' ', ' ', ' ', ' ', ' ', 'T', ' ', ' '],\
[' ', 'T', ' ', ' ', ' ', ' ', ' ', ' '],\
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],\
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],\
[' ', ' ', ' ', ' ', 'T', ' ', ' ', ' '],\
[' ', ' ', ' ', ' ', ' ', ' ', ' ', 'K']]
Here what I have:
current_row = 0
current_column = 0
def View_Map():
for i in world_map:
world_map[current_row][current_column] = "H/T"
print(i)
The output I get:
You can use string formatting to print this, you would need to print
for each line in your data a header ('+---+- etc -+---+'))
for each cell in your data a value V ('+ V +')
a end line after all of them ('+---+- etc -+---+'))
Header and cells would need to adapt to the maximal widht of all cell contents to get an even looking map.
You can do it like this:
m = [['T', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', 'T', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', 'T', ' ', ' '],
[' ', 'T', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', 'T', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', 'K']]
def print_map(data):
"""Prints a list of lists, puts data centered
into each boxand pads other boxes accordingly. """
# max widht of all elelemts to be printed
max_w = max(len(o) for l in data for o in l)
# fitting header
header = f"+-{'-' * max_w}-" * len(data[0]) + "+"
for line in data:
print(header)
print("+", end="")
for char in line:
# center format each "box"
print(f" {char:^{max_w}} +", end="")
print()
print(header)
print_map(m)
Output:
+---+---+---+---+---+---+---+---+
+ T + + + + + + + +
+---+---+---+---+---+---+---+---+
+ + + + T + + + + +
+---+---+---+---+---+---+---+---+
+ + + + + + T + + +
+---+---+---+---+---+---+---+---+
+ + T + + + + + + +
+---+---+---+---+---+---+---+---+
+ + + + + + + + +
+---+---+---+---+---+---+---+---+
+ + + + + T + + + +
+---+---+---+---+---+---+---+---+
+ + + + + + + + K +
+---+---+---+---+---+---+---+---+
If you have a "non-1-character-content" the code will space out the other cells as needed:
+-------+-------+-------+-------+-------+-------+-------+-------+
+ T + + + + + + + +
+-------+-------+-------+-------+-------+-------+-------+-------+
+ + + + TTTTT + + + + +
+-------+-------+-------+-------+-------+-------+-------+-------+
+ + + + + + T + + +
+-------+-------+-------+-------+-------+-------+-------+-------+
+ + T + + + + + + +
+-------+-------+-------+-------+-------+-------+-------+-------+
+ + + + + + + + +
+-------+-------+-------+-------+-------+-------+-------+-------+
+ + + + + + + + +
+-------+-------+-------+-------+-------+-------+-------+-------+
+ + + + + T + + + +
+-------+-------+-------+-------+-------+-------+-------+-------+
+ + + + + + + + K +
+-------+-------+-------+-------+-------+-------+-------+-------+
Lookup string format mini language for centering text
I am currently learning python as my first programming language and thought I had the knowledge and wanted to challenge myself to create tic-tac-toe. I have the code working to the point where it starts the game and the first move is requested but when I try to print the new board it doesn't print with he space filled out.
L1 = " "
def board():
print(" | | ")
print(" ",L1," | ",M1," | ",R1," ")
print(" | | ")
print("-----------------")
print(" | | ")
print(" ",L2," | ",M2," | ",R2," ")
print(" | | ")
print("-----------------")
print(" | | ")
print(" ",L3," | ",M3," | ",R3," ")
print(" | | ")
Xmove = input("Where does X want to go? ")
def xmove(Xmove):
if Xmove == ("L1"):
L1 = "X"
board()
xmove(Xmove)
This should be printing the new board with the top left space now an "X" but it isn't. It just prints a blank board.
You may want to move some stuff around and use a dict, so it is easier to keep track of. This also avoids the need for globals. This also conveniently handles all your potential moves, with simple code.
def board():
print(" | | ")
print(" "+pm['L1']+" | "+pm['M1']+" | "+pm['R1']+" ")
print(" | | ")
print("-----------------")
print(" | | ")
print(" "+pm['L2']+" | "+pm['M2']+" | "+pm['R2']+" ")
print(" | | ")
print("-----------------")
print(" | | ")
print(" "+pm['L3']+" | "+pm['M3']+" | "+pm['R3']+" ")
print(" | | ")
pm = {'L1': '', 'M1': '', 'R1': '',
'L2': '', 'M2': '', 'R2': '',
'L3': '', 'M3': '', 'R3': '', }
def xmove():
Xmove = input("Where does X want to go? ")
pm[Xmove] = 'X'
board()
xmove()
I hope you can see why it might be tedious to use global variables like this-- you have to declare them as global variables every time you want to use them. In your case, you'd have to declare 9 global variables in each function that needs to access them. Instead, you could group them together use a class approach. Then all you have to do is pass the class around. It might look something like this:
class BoardClass:
def __init__(self):
# This is the constructor function that is run when you create a
# a new instance of BoardClass. All we'll do is set the default
# values. 'self' is exactly what it sounds like. *itself*
self.L1 = " "
self.M1 = " "
self.R1 = " "
self.L2 = " "
self.M2 = " "
self.R2 = " "
self.L3 = " "
self.M3 = " "
self.R3 = " "
def board(b):
# b is the BoardClass object. You can refer to its members with b.varname
print(" | | ")
print(" ",b.L1," | ",b.M1," | ",b.R1," ")
print(" | | ")
print("-----------------")
print(" | | ")
print(" ",b.L2," | ",b.M2," | ",b.R2," ")
print(" | | ")
print("-----------------")
print(" | | ")
print(" ",b.L3," | ",b.M3," | ",b.R3," ")
print(" | | ")
def xmove(b, Xmove):
# Again, b is the BoardClass object.
if Xmove == ("L1"):
b.L1 = "X" # You can set the parameters of b like this
board(b)
# Create your board
b = BoardClass()
# Ask user for move
Xmove = input("Where does X want to go? ")
# Make the move and print
xmove(b, Xmove)
This only makes one move though, you'll have to come up with your own logic to get the game to loop and switch turns.
Right now you have L1 set up as a global variable. You can access global variables inside functions, but to change them you need to use the global keyword, something like this:
def xmove(Xmove):
global L1
if Xmove == ("L1"):
L1 = "X"
board()