Not printing letters one by one on one single line [duplicate] - python

This question already has an answer here:
Why doesn't print output show up immediately in the terminal when there is no newline at the end?
(1 answer)
Closed last month.
dict = {}
def colors(col):
if col == "red":
return "\033[31m"
elif col == "green":
return "\033[32m"
elif col == "yellow":
return "\033[33m"
elif col == "blue":
return "\033[34m"
elif col == "magenta":
return "\033[35m"
def seperator(x):
colors1 = ["red","green","yellow","blue","magenta"]
for char in x:
y = random.choice(colors1)
print(f"{colors(y)}{char}",end="")
time.sleep(0.2)
seperator("MokeBeast")
I am trying to make python print the letters of this string with a 0.2 delay between each one on one single line.
I was expecting it to print out my string like this:
M (wait 0.2sec) o (wait 0.2sec) k (wait 0.2sec) e (wait 0.2sec) B (wait 0.2sec) e (wait 0.2sec) etc...
What keeps happening is that it does not print the letter one by one, instead it waits all those delays and then prints the string all in one like this: MokeBeast
How can I fix this?

You have to flush the standard output after each print to ensure they appear in between the waits:
import time
import sys
import random
dict = {}
def colors(col):
if col == "red":
return "\033[31m"
elif col == "green":
return "\033[32m"
elif col == "yellow":
return "\033[33m"
elif col == "blue":
return "\033[34m"
elif col == "magenta":
return "\033[35m"
def seperator(x):
colors1 = ["red","green","yellow","blue","magenta"]
for char in x:
y = random.choice(colors1)
print(f"{colors(y)}{char}",end="")
sys.stdout.flush() # <--- use this
time.sleep(0.2)
seperator("MokeBeast")

Related

2D Array update actually updates two different arrays? [duplicate]

This question already has answers here:
List of lists changes reflected across sublists unexpectedly
(17 answers)
Closed 1 year ago.
I'm trying to track how many times a selection was made in a 2D array and how many times it was played in another array (it has to deal with having multiple mp3's in a directory). Not even sure I'm describing it well, but hopefully my example will show my issue.
If you take the code below (and don't have the "PlayHistory.csv" file created), run it, type "A1" you will see two 2D arrays print out. Specifically look at entries for "A1". The Selection Count is 0 and Allowed Selection Count is 1. This is what I'd expect. Now, close the program (or IDE in my case) the "PlayHistory.csv" file is present and notice A1 entry is 0). Run the program again and use "A1" as your input and you'll see both the Selection Count is 1 and the Allowed Selection Count is 1. I'm not even updating the SelectionCount array in the attached code. How is this happening?
#!/usr/bin/env python3
#
import os, sys, csv, vlc, time, serial
from pynput.keyboard import Key, Listener
#
USBDrive = None
Action = None
Playlist = []
SelectionCount = []
AllowedCount = []
Sel_char = None
Queue_counter = 0
Play_counter = 0
PlayHistory="PlayHistory.csv"
#
# Create/Find/Open PlayHistory.csv
# Create media folders as needed if new PlayHistory file is created
#
USBDrive = os.path.join("/media/pi", "USB30FD")
if os.path.isfile(os.path.join(USBDrive, PlayHistory)):
datafile = open(os.path.join(USBDrive, PlayHistory), 'r+')
datareader = csv.reader(datafile, delimiter=',')
for row in datareader:
SelectionCount.append(row)
AllowedCount.append(row)
else:
datafile = open(os.path.join(USBDrive, PlayHistory), 'w+')
datawriter = csv.writer(datafile, delimiter=',')
datawriter.writerow(['Selection', 'Count'])
SelectionCount.append(['Selection', 'Count'])
AllowedCount.append(['Selection', 'Count'])
for x in range (65, 87):
if x == 73 or x == 79:
continue
for y in range (1,11):
if y == 10:
datawriter.writerow([chr(x) + str(0),0])
SelectionCount.append([chr(x) + str(0),0])
AllowedCount.append([chr(x) + str(0),0])
# if not os.path.isdir(os.path.join(USBDrive, chr(x) + str(0))):
# os.makedirs(os.path.join(USBDrive, chr(x) + str(0)))
else:
datawriter.writerow([chr(x) + str(y),0])
SelectionCount.append([chr(x) + str(y),0])
AllowedCount.append([chr(x) + str(y),0])
# if not os.path.isdir(os.path.join(USBDrive, chr(x) + str(y))):
# os.makedirs(os.path.join(USBDrive, chr(x) + str(y)))
datafile.flush()
datafile.close()
#AllowedCount == SelectionCount
#
# Find location of Selection in SelectionCount 2D array
#
def find(l, elem):
for row, i in enumerate(l):
try:
column = i.index(elem)
except ValueError:
continue
return row, column
return -1
#
# MediaPlayer function
#
def QueueTracker(tracker, selection):
global Queue_counter, Play_counter
if tracker == "Queue":
Queue_counter = Queue_counter + 1
elif tracker == "Play":
print("Play Counter")
Play_counter = Play_counter + 1
count1,count2=find(SelectionCount, selection)
#SelectionCount[count1][1] = int(SelectionCount[count1][1]) + 1
print("SelectionCount: " + str(SelectionCount[count1][1]))
elif tracker == "Allowed":
print("Allowed Counter")
acount1,acount2=find(AllowedCount, selection)
print(AllowedCount[acount1][1])
AllowedCount[acount1][1] = int(AllowedCount[acount1][1]) + 1
print("AllowedSelectionCount: " + str(AllowedCount[acount1][1]))
print("Selected Count")
print(SelectionCount)
print("Allowed Selection Count")
print(AllowedCount)
#
# Define keyboard actions
#
def on_press(key):
global Action
try:
Sel_char = int(key.char)
except:
try:
Sel_char = str(key.char)
Sel_char = Sel_char.upper()
except:
Sel_char = None
if Sel_char == "Z":
return False
elif Sel_char == "Y":
print("Play Track")
QueueTracker("Played", "A1")
elif type(Sel_char) == str:
Action = Sel_char
elif type(Sel_char) == int:
Action = Action + str(Sel_char)
QueueTracker("Allowed", "A1")
else:
pass
# Read keyboard input
#
print("Ready...")
with Listener(on_press=on_press) as listener:
listener.join()
#
# Program is shutting down
#
print ("")
print ("Writing Play Counts to PlayHistory file")
datafile = open(os.path.join(USBDrive, PlayHistory), 'w+')
datawriter = csv.writer(datafile, delimiter=',')
datawriter.writerows(SelectionCount)
datafile.flush()
datafile.close()
print ("")
print ("Have a nice day!")
print ("")
sys.exit()
Any help would be greatly appreciated.
Thanks! Brian
Your assessment was essentially correct:
for row in datareader:
SelectionCount.append(row)
AllowedCount.append(row)
That does not make two copies. That makes two pointers to one list. If you modify the list in SelectionCount[0], that will also modify AllowedCount[0]. Change that to
for row in datareader:
SelectionCount.append(row)
AllowedCount.append(row[:])
You might also consider this simplification to your first loop creating the CSV data:
for x in 'ABCDEFGHJKLMNPQRSTUV':
for y in range (10):
datawriter.writerow([x + str(y),0])
SelectionCount.append([x + str(y),0])
AllowedCount.append([x + str(y),0])

Are there better ways to write if statements in python?

So ive been writing Python for a bit now. I've decided to make an app to help my sister with multiplication tables. Im writing the code that will randomly pick from my 10 lists of the diffrent questions (I know there are better ways to write it but it gave me abilities i wanted to use with SQL). lists are by Table (Tone,Ttwo,Tthree, etc.) inside Tone would be ['1*1','1*2',...] then as seen in the if statement it calls by calling the list and problem with randomly generated numbers.
def pick_question():
Table = random.randint(0,9)
Col = random.randint(0,9)
if Table == 0:
if Col == 0:
return Tone[0]
elif Col == 1:
return Tone[1]
elif Col == 2:
return Tone[2]
elif Col == 3:
return Tone[3]
elif Col == 4:
return Tone[4]
elif Col == 5:
return Tone[5]
elif Col == 6:
return Tone[6]
elif Col == 7:
return Tone[7]
elif Col == 8:
return Tone[8]
elif Col == 9:
return Tone[9]
elif Table == 1:
if Col == 0:
return Ttwo[0]
elif Col == 1:
return Ttwo[1]
elif Col == 2:
return Ttwo[2]
elif Col == 3:
return Ttwo[3]
elif Col == 4:
return Ttwo[4]
elif Col == 5:
return Ttwo[5]
elif Col == 6:
return Ttwo[6]
elif Col == 7:
return Ttwo[7]
elif Col == 8:
return Ttwo[8]
elif Col == 9:
return Ttwo[9]
obviously it would keep going but it was already quite long. was wondering if there was anyway to make this not hae to be so repetitive and look better...
def pick_question():
Table = random.randint(0,9)
Col = random.randint(0,9)
return [Tone,Ttwo][Table][Col]
I guess what you are trying to write is
import random
Tone = [f"1*{i}" for i in range(1,10)]
Ttwo = [f"2*{i}" for i in range(1,10)]
Tthree = [f"3*{i}" for i in range(1,10)]
Tfour = [f"4*{i}" for i in range(1,10)]
Tfive = [f"5*{i}" for i in range(1,10)]
Tsix = [f"6*{i}" for i in range(1,10)]
Tseven = [f"7*{i}" for i in range(1,10)]
Teight = [f"8*{i}" for i in range(1,10)]
Tnine = [f"9*{i}" for i in range(1,10)]
Questions = [
Tone,
Ttwo,
Tthree,
Tfour,
Tfive,
Tsix,
Tseven,
Teight,
Tnine,
]
def pick_question():
Table = random.randint(0,8)
Col = random.randint(0,8)
return Questions[Table][Col]
print(pick_question())
but I guess what you are trying to do is this:
import random
A=random.randint(1,9)
B=random.randint(1,9)
print(f"{A}*{B}=?")
C=input()
try:
assert A*B==int(C)
print("You are RIGHT!")
except:
print(f"Your are WRONG, right answer is: {A*B}")
Good luck with python! it's an amazing language! :)
Just use a one-dimensional list:
def pick_question():
Table = random.randint(0,9)
Col = random.randint(0,9)
if Table == 0:
return Tone[Col]
elif Table == 1:
return Ttwo[Col]
This will do the trick.
Or even better, a two-dimensional list:
def pick_question():
Table = random.randint(0,9)
Col = random.randint(0,9)
List = [Tone, Ttwo]
return List[Table][Col]
I quite like this solution with dictionaries and the get method:
route = input()
branch = {'y': code1, 'n': code2}.get(route)
This shortens your code and will be easier to read.
Rather than write the inner if structures, why not just
return Tone[Col]
?
In fact, you can create a list with the Tone, Ttwo, etc. inside it and then write
return outer_list[Table][Col]
def pick_question(list_with_tone_ttwo):
table = random.randint(0,9)
col = random.randint(0,9)
return list_with_tone_ttwo[table][col]
EDIT: added full function

How to check for 3 in a row in tic tac toe game

I am making a tic tac toe game and trying to create a function that checks if 3 of the same spots in a row have the same input 'x' or '0'. I am having trouble with the three_in_row function I am trying to make to trigger game over. I am trying to figure out how to do this in a simple way so all rows or columns will be triggers if 3 X's or 0's are played... Here's what I have so far. This is in python 2.7.13
(this is only part of the code I think should be relevant)
def setup_board(size):
board = []
for row in range(size):
board.append([])
for col in range(size):
board[row].append(empty)
return board
def three_in_row(b):
b[0][0] and b[0][1] and b[0][2] == 'x'
def game_over(b):
if three_in_row(b) == True:
print "Congratulations You Win!"
else:
return False
def tic_tac_toe():
b = setup_board(3)
run_game(b)
In my opinion, it might make more sense to store X's as +1 and O's as -1, so that you can easily do arithmetic to check if the game is over.
For example:
def three_in_row(b):
xWin = check_winner(b,3)
oWin = check_winner(b,-3)
return xWin | oWin
def check_winner(b, valToCheck):
foundWin = any(sum(r) in {valToCheck} for r in b) # check rows
# now check columns
for i in range(3):
foundWin = foundWin | (sum([b[j][i] for j in range(3)]) == valToCheck)
# now check diagonals
foundWin = foundWin | (sum([b[i][i] for i in range(3)]) == valToCheck)
foundWin = foundWin | (sum([b[i][2-i] for i in range(3)]) == valToCheck)
return foundWin
Thanks to Blender for the following more succinct method:
def three_in_row(b):
return any(sum(r) in {3, -3} for r in b)
def line_match(game):
for i in range(3):
set_r = set(game[i])
if len(set_r) == 1 and game[i][0] != 0:
return game[i][0]
return 0
#transposed column function for future use
#def column(game):
# trans = numpy.transpose(game)
# for i in range(3):
# set_r = set(trans[i])
# if len(set_r) == 1 and trans[i][0] != 0:
# return list(set_r)[0]
def diagonal_match(game):
if game[1][1] != 0:
if game[1][1] == game[0][0] == game[2][2]:
return game[1][1]
elif game[1][1] == game[0][2] == game[2][0]:
return game[1][1]
return 0
The correct syntax for the checks is either:
b[0][0] == 'x' and b[0][1] == 'x' and b[0][2] == 'x'
or (more succinctly):
b[0][0] == b[0][1] == b[0][2] == 'x'
You are also missing a return just before your check, like:
return b[0][0] == b[0][1] == b[0][2] == 'x'
Anyways, your code does not iterate over all the rows. A possible correction would be:
def three_in_row(b):
for row in rage(0, 3):
if b[row][0] == b[row][1] == b[row][2] == 'x':
return True
return False
Doing a three_in_column(b) should be fairly easy (changing b[row][n] in b[n][column]), so is also manually checking the two diagonals.

6X6 grid, 3 Player Tic Tac Toe game Python [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm very new to Python and I have to create a tic tac toe game with 3 players, 'X', 'O' and 'Y'. The grid has to be 6x6 instead of the normal 3x3. I have been having a lot of trouble with this and I'm very unsure how to do it. I have a 2 player 3x3 game working but implementing another player and validating the wins is becoming more tedious than I previously expected. I need help with validating a win. I haven't written the code to check for a diagonal win because I want to get everything else working before I do that. This is what I have so far but it's not correct. It's not printing out the values entered and when I do enter a value it says X has won straight away. I'd really appreciate it if you could help me. Thanks!
grid = [[0,0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0,0]]
def get_state(grid, row, col):
occupant = grid[col-1][row-1]
if occupant == 1:
return 'X'
if occupant == 2:
return 'O'
if occupant == 3:
return 'Y'
return ' '
def set_state(grid, row, col, player):
if player == 'X':
occupant = 1
elif player == 'O':
occupant = 2
elif player == 'Y':
occupant = 3
grid[col-1][row-1] = occupant
def is_winner(grid):
if grid[0][0] == grid[0][1] == grid [0][2]:
return True
if grid[0][1] == grid[0][2] == grid [0][3]:
return True
if grid[0][2] == grid[0][3] == grid [0][4]:
return True
if grid[0][3] == grid[0][4] == grid [0][5]:
return True
if grid[1][0] == grid[1][1] == grid [1][2]:
return True
if grid[1][1] == grid[1][2] == grid [1][3]:
return True
if grid[1][2] == grid[1][3] == grid [1][4]:
return True
if grid[1][3] == grid[1][4] == grid [1][5]:
return True
if grid[2][0] == grid[2][1] == grid [2][2]:
return True
if grid[2][1] == grid[2][2] == grid [2][3]:
return True
if grid[2][2] == grid[2][3] == grid [2][4]:
return True
if grid[2][3] == grid[2][4] == grid [2][5]:
return True
if grid[3][0] == grid[3][1] == grid [3][2]:
return True
if grid[3][1] == grid[3][2] == grid [3][3]:
return True
if grid[3][2] == grid[3][3] == grid [3][4]:
return True
if grid[3][3] == grid[3][4] == grid [3][5]:
return True
if grid[4][0] == grid[4][1] == grid [4][2]:
return True
if grid[4][1] == grid[4][2] == grid [4][3]:
return True
if grid[4][2] == grid[4][3] == grid [4][4]:
return True
if grid[4][3] == grid[4][4] == grid [4][5]:
return True
if grid[5][0] == grid[5][1] == grid [5][2]:
return True
if grid[5][1] == grid[5][2] == grid [5][3]:
return True
if grid[5][2] == grid[5][3] == grid [5][4]:
return True
if grid[5][3] == grid[5][4] == grid [5][5]:
return True
if grid[0][0] == grid[1][0] == grid [2][0]:
return True
if grid[1][0] == grid[2][0] == grid [3][0]:
return True
if grid[2][0] == grid[3][0] == grid [4][0]:
return True
if grid[3][0] == grid[4][0] == grid [5][0]:
return True
if grid[0][1] == grid[1][1] == grid [2][1]:
return True
if grid[1][1] == grid[2][1] == grid [3][1]:
return True
if grid[2][1] == grid[3][1] == grid [4][1]:
return True
if grid[3][1] == grid[4][1] == grid [5][1]:
return True
if grid[0][2] == grid[1][2] == grid [2][2]:
return True
if grid[1][2] == grid[2][2] == grid [3][2]:
return True
if grid[2][2] == grid[3][2] == grid [4][2]:
return True
if grid[3][2] == grid[4][2] == grid [5][2]:
return True
if grid[0][3] == grid[1][3] == grid [2][3]:
return True
if grid[1][3] == grid[2][3] == grid [3][3]:
return True
if grid[2][3] == grid[3][3] == grid [4][3]:
return True
if grid[3][3] == grid[4][3] == grid [5][3]:
return True
if grid[0][4] == grid[1][4] == grid [2][4]:
return True
if grid[1][4] == grid[2][4] == grid [3][4]:
return True
if grid[2][4] == grid[3][4] == grid [4][4]:
return True
if grid[3][4] == grid[4][4] == grid [5][4]:
return True
if grid[0][5] == grid[1][5] == grid [2][5]:
return True
if grid[1][5] == grid[2][5] == grid [3][5]:
return True
if grid[2][5] == grid[3][5] == grid [4][5]:
return True
if grid[3][5] == grid[4][5] == grid [5][5]:
return True
return False
def print_grid(grid):
print_row(grid,1)
print('-----------')
print_row(grid,2)
print('-----------')
print_row(grid,4)
print('-----------')
print_row(grid,4)
print('-----------')
print_row(grid,5)
print('-----------')
print_row(grid,6)
def print_row(grid, row):
output = get_state(grid,row,1)
output += '|' + get_state(grid, row, 2)
output += '|' + get_state(grid, row, 3)
output += '|' + get_state(grid, row, 4)
output += '|' + get_state(grid, row, 5)
output += '|' + get_state(grid, row, 5)
print (output)
ongoing = True
currentPlayer = 'X'
spaces = 36
while ongoing:
print_grid(grid)
print (currentPlayer + "'s turn")
print("Column?")
col = int(input())
print("Row?")
row = int(input())
current = get_state(grid,row,col)
if current != ' ':
print ("That spot is taken!")
else:
set_state(grid, row, col, currentPlayer)
spaces -= 1
if is_winner(grid):
print (currentPlayer + "'s wins!")
ongoing = False
else:
if currentPlayer == 'X':
currentPlayer = 'O'
elif currentPlayer == 'O':
curentPlayer = 'Y'
elif currentPlayer == 'Y':
currentPlayer = 'X'
if spaces == 0:
print("Stalemate!")
ongong = False
The is_winner(grid) function checks if 3 of the grid cells are the same. You initialized the grid to be 0, so the first player would always 'win'. One fix I suggest would be to initialize the list with different values. Another one would be to check (after finding that 3 cells are same) the values of the grid:
if grid[0][0] == grid[0][1] == grid[0][2]:
return grid[0][0] in ['X', 'O', 'Y']
The answer given by chucksys is good, although I would do it in a slightly different way. You need to determine that the 3 cells are the same, and not empty - so just check against your default value.
if grid[0][0] == grid[0][1] == grid[0][2] != 0:
return True
good luck with your game it's fun !!!! You can leave the code as it is. just make a different grid. one that contains a different value in every cell. That will prevent you from rewriting a lot of the game. At the beginning add the following code:grid = []
inner = []
b = 10
for i in xrange(6):
for ii in xrange(6):
inner.append(b)
b += 1
grid.append(inner)
inner = list()
This will make your grid, error proof from your checker function is_winner
There is also one small bug. curentPlayer = 'Y' change to currentPlayer = 'Y' near the end of the code

List index out of range when coding a valid move for board game

Hey everyone im new here and im trying to make a game called HiQ now i got the board drawn and everything and i can click on one of the pieces, but when i do the piece does change color and i get an error in the shell as well (listed below) im not sure why im getting this and i was hoping you guys could give me better insight. Ill provide my code below as well and it is coded in python 3, thank you
builtins.IndexError: list index out of range
boardcirc =[[0,0,0,1,1,1,0,0,0],
[0,0,0,1,1,1,0,0,0],
[0,0,0,1,1,1,0,0,0],
[1,1,1,1,1,1,1,1,1],
[1,1,1,1,2,1,1,1,1],
[1,1,1,1,1,1,1,1,1],
[0,0,0,1,1,1,0,0,0],
[0,0,0,1,1,1,0,0,0],
[0,0,0,1,1,1,0,0,0]]
def HiQ():
splash_screen()
make_board()
def make_board():
make_sqr()
make_circ()
get_click()
def get_click():
global count, boardcirc
while 1!=0:
count = count - 1
displaymessage("Pieces: " + str(count))
where = win.getMouse()
col = where.x//90
row = where.y//90
valid_move(row,col)
make_move(row,col)
def valid_move(row,col):
if boardcirc[row][col] == 0:
return False
if boardcirc[row-1][col] == 1 and boardcirc[row-2][col] == 1:
return True
if boardcirc[row+1][col] == 1 and boardcirc[row+2][col] == 1:
return True
if boardcirc[row][col-1] == 1 and boardcirc[row][col-2] == 1:
return True
if boardcirc[row][col+1] == 1 and boardcirc[row][col+2] == 1:
return True
def make_move(row,col):
while valid_move(row,col) == True:
col = (col*85)+42
row = (row*85)+42
circ = Circle(Point(col,row),35)
circ.setFill("white")
circ.draw(win)
thats everything that applies to the error
For your valid_move(row,col), you can't have all those if statements.
Instead of doing this, use elif's after the initial if statement, and don't forget to write an else statement
if boardcirc[row][col] == 0:
return False
if boardcirc[row-1][col] == 1 and boardcirc[row-2][col] == 1:
return True
elif boardcirc[row+1][col] == 1 and boardcirc[row+2][col] == 1:
return True
elif boardcirc[row][col-1] == 1 and boardcirc[row][col-2] == 1:
return True
elif boardcirc[row][col+1] == 1 and boardcirc[row][col+2] == 1:
return True
else:
return False

Categories