0% found this document useful (0 votes)
20 views

P Counter

This is a python file

Uploaded by

attastudy7
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

P Counter

This is a python file

Uploaded by

attastudy7
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 10

import random

import sys
from random import randint
computer_turn_counter = 0
def printBoard(board):
print(' ' + board[1] + ' |' + board[2] + ' |' + board[3])
print(' ' + board[4] + ' |' + board[5] + ' |' + board[6])
print(' ' + board[7] + ' |' + board[8] + ' |' + board[9])
def isSpaceFree(board, move):
if board[move] == ' ':
return True
else:
False
def my_custom_random(takenmoves):
# Returns a valid move from the passed list on the passed board.
# Returns None if there is no valid move.
allmoves = [1,2,3,4,5,6,7,8,9]
movesList = list(set(allmoves) - set(takenmoves))
return random.choice(movesList)
def updateMove(board, letter , move):
board[move] = letter
def getPlayerMove(board):
# Let the player type in their move.
move = ' '
while move not in '1 2 3 4 5 6 7 8 9'.split() or not isSpaceFree(board,
int(move)):
print('What is your next move? (1-9)')
move = input()
return int(move)
def getComputersMove(board, computerletter, playerletter, dict ,list,
computer_turn_counter):
global magicboard
checkforplayer = 0
print("Comp Turns Completed : ",computer_turn_counter)
#If First Time
if (computer_turn_counter == 0):
move = my_custom_random(list )
computer_turn_counter=+1
return move , computer_turn_counter
#Second Time
if (computer_turn_counter == 1):
computer_turn_counter= 2
#try to get middle element
if (isSpaceFree(board,5)):
move = 5
return 5 , computer_turn_counter
else:
checkforplayer = 1
#Checks self wining chances
if (computer_turn_counter and len(dict[computerletter]) > 1 ):
print("|| In self wining chances ")
computer_turn_counter=3
length = len(dict[computerletter])
for i in range(0,length - 1):
#Formula
diff = 15 - (magicboard[ dict[computerletter][i] -1 ] +
magicboard[ dict[computerletter][length - 1] - 1 ])
print("The Diff: 15 - (",magicboard[ dict[computerletter][i] -1 ] ," +
",magicboard[ dict[computerletter][length - 1] - 1 ],"): " ,diff)
if(diff in magicboard):
checkforplayer = 1
else:
checkforplayer = 1
continue
index = magicboard.index(diff) + 1
print("The Index to be placed at is : ", index )
if (index <= 9 and index > 0):
if isSpaceFree(board, index) :
print("Returned the Difference in self win")
return index , computer_turn_counter
else:
print("Cant Add , Position is Taken Already")
checkforplayer = 1
else :
checkforplayer = 1
#Checks to Defeat the Player
if checkforplayer == 1:
print("|| In Defeat the Player ")
length = len(dict[playerletter])
for i in range(0,length - 1):
#Formula
diff = 15 - (magicboard[ dict[playerletter][i] -1 ] +
magicboard[ dict[playerletter][length - 1] - 1 ] )
print("The Diff: 15 - (",magicboard[ dict[playerletter][i] -1 ] ," +
",magicboard[ dict[playerletter][length - 1] - 1 ],"): " ,diff)
if(magicboard.index(diff)):
if(magicboard.index(diff) > 9 or magicboard.index(diff) <= 0):
checkforplayer = 1
continue
index = magicboard.index(diff) + 1
print("The Index to be placed at is : ", index )
if (index <= 9 and index > 0):
if isSpaceFree(board, index) :
print("Returned the Difference defeat player")
return index , computer_turn_counter
else:
print("Cant Add , Position is Taken Already")
checkforplayer = 1
else :
checkforplayer = 1
computer_turn_counter = computer_turn_counter + 1
return my_custom_random(list) , computer_turn_counter
def isWinner(bo, le):
# Given a board and a player’s letter, this function returns True if that
player has won.
# We use bo instead of board and le instead of letter so we don’t have to type
as much.
return ((bo[7] == le and bo[8] == le and bo[9] == le) or # across the top
(bo[4] == le and bo[5] == le and bo[6] == le) or # across the middle
(bo[1] == le and bo[2] == le and bo[3] == le) or # across the bottom
(bo[7] == le and bo[4] == le and bo[1] == le) or # down the left side
(bo[8] == le and bo[5] == le and bo[2] == le) or # down the middle
(bo[9] == le and bo[6] == le and bo[3] == le) or # down the right side
(bo[7] == le and bo[5] == le and bo[3] == le) or # diagonal
(bo[9] == le and bo[5] == le and bo[1] == le)) # diagonal
def makechoice():
#TicTacToe()
x = 1
while(x):
choice = input("Choose your Player X or O : ")
if choice =="x" or choice=="X":
print("Player has chosen X and will go First\n")
x = 0
playerletter = "X"
computerletter = "O"
turn = "player"
elif choice =="O" or choice=="o":
print("Player has chosen O , Bot will go First\n")
x = 0
playerletter = "O"
turn = "computer"
computerletter = "X"
else:
print("Not an option, IDIOT. Choose again.\n")
return playerletter,computerletter,turn
def isBoardFull(board):
# Return True if every space on the board has been taken. Otherwise return
False.
for i in range(1, 10):
if isSpaceFree(board, i):
return False
return True
magicboard = [8,3,4,
1,5,9,
6,7,2]
dict = {
"X":[],
"O":[]
}
LIST = []
board = [' '] * 10
playerletter,computerletter,turn = "X", "O", "player"
#playerletter,computerletter,turn = makechoice()
gamePlaying = True
while gamePlaying:
if turn =="player":
#Player’s turn.
printBoard(board)
move = getPlayerMove(board)
dict[playerletter].append(move )
LIST.append(move)
print(dict)
updateMove(board,playerletter,move)
if isWinner(board, playerletter):
printBoard(board)
print('****************** Hooray! You have won the game!
******************')
sys.exit("Thank You For Playing!")
gameIsPlaying = False
else:
if isBoardFull(board):
print('****************** The game is a tie! ****************** ')
printBoard(board)
sys.exit("Thank You For Playing!")
break
else:
turn = 'computer'
else:
#Computer's Turn
move , computer_turn_counter =
getComputersMove(board,computerletter ,playerletter, dict ,LIST ,
computer_turn_counter)
dict[computerletter].append(move )
LIST.append(move)
print(dict)
updateMove(board,computerletter,move)
if isWinner(board, computerletter):
printBoard(board)
print('You Lost to a bOt! .')
sys.exit("Thank You For Playing!")
gameIsPlaying = False
else:
if isBoardFull(board):
board(board)
print('The game is a tie!')
break
else:
turn = 'player'

Tic Tac Minimax


PLAYER_CHARACTER = 'O'
COMPUTER_CHARACTER = 'X'
board = {
1: ' ', 2: ' ', 3: ' ',
4: ' ', 5: ' ', 6: ' ',
7: ' ', 8: ' ', 9: ' '
}
def display_board(board):
print(
board[1].center(5, ' ') + '|' +
board[2].center(5, ' ') + '|' +
board[3].center(5, ' ')
)
print('-' * 17)
print(
board[4].center(5, ' ') + '|' +
board[5].center(5, ' ') + '|' +
board[6].center(5, ' ')
)
print('-' * 17)
print(
board[7].center(5, ' ') + '|' +
board[8].center(5, ' ') + '|' +
board[9].center(5, ' ')
)
print('\n')
def is_free(pos):
return board[pos] == ' '
def is_draw():
for key in board.keys():
if board[key] == ' ':
return False
return True
def somebody_won():
# Row check
if board[1] == board[2] and board[1] == board[3] and board[1] != ' ':
return True
elif board[4] == board[5] and board[4] == board[6] and board[4] != ' ':
return True
elif board[7] == board[8] and board[7] == board[9] and board[7] != ' ':
return True
# Column check
elif board[1] == board[4] and board[1] == board[7] and board[1] != ' ':
return True
elif board[2] == board[5] and board[2] == board[8] and board[2] != ' ':
return True
elif board[3] == board[6] and board[3] == board[9] and board[3] != ' ':
return True
# Diagonal check
elif board[1] == board[5] and board[1] == board[9] and board[1] != ' ':
return True
elif board[7] == board[5] and board[7] == board[3] and board[7] != ' ':
return True
else:
return False
def has_won(mark):
# Row check
if board[1] == board[2] and board[1] == board[3] and board[1] == mark:
return True
elif board[4] == board[5] and board[4] == board[6] and board[4] == mark:
return True
elif board[7] == board[8] and board[7] == board[9] and board[7] == mark:
return True
# Column check
elif board[1] == board[4] and board[1] == board[7] and board[1] == mark:
return True
elif board[2] == board[5] and board[2] == board[8] and board[2] == mark:
return True
elif board[3] == board[6] and board[3] == board[9] and board[3] == mark:
return True
# Diagoanl check
elif board[1] == board[5] and board[1] == board[9] and board[1] == mark:
return True
elif board[7] == board[5] and board[7] == board[3] and board[7] == mark:
return True
else:
return False
def putchar(character, position):
if is_free(position):
board[position] = character
display_board(board)
if is_draw():
print("\nIt was a tie 👨🤝💻")
exit()
if somebody_won():
if character == COMPUTER_CHARACTER:
print("\nThe computer wins 💻")
else:
print("\nThe player wins 🤴")
exit()
else:
print("This slot is already used!")
position = int(input("Enter new position: "))
putchar(character, position)
def get_player_move():
print(" Player's Turn ".center(40, '='))
pos = int(input("Enter the position for 'O': "))
putchar(PLAYER_CHARACTER, pos)
def get_computer_move():
print(" Computer's Turn ".center(40, '='))
best_score = -100
best_move = 0
for key in board.keys():
if board[key] != ' ':
continue
board[key] = COMPUTER_CHARACTER
score = minimax(board, False)
board[key] = ' '
if score > best_score:
best_score = score
best_move = key
print(f"Computer found move {best_move} with score {best_score}")
print(f"Computer picks move {best_move} with score {best_score}")
putchar(COMPUTER_CHARACTER, best_move)
def minimax(board, maximising):
if has_won(COMPUTER_CHARACTER):
return 10
if has_won(PLAYER_CHARACTER):
return -10
elif is_draw():
return 0
if maximising:
bestScore = -1000
for key in board.keys():
if board[key] == ' ':
board[key] = COMPUTER_CHARACTER
score = minimax(board, False)
board[key] = ' '
if score > bestScore:
bestScore = score
return bestScore
else:
bestScore = 1000
for key in board.keys():
if board[key] == ' ':
board[key] = PLAYER_CHARACTER
score = minimax(board, True)
board[key] = ' '
if score < bestScore:
bestScore = score
return bestScore
def main():
display_board(board)
first = input("Do you wish to play first (Y/N): ").strip().upper()
turn = first == 'Y'
while not somebody_won():
if turn:
get_player_move()
else:
get_computer_move()
turn = not turn
if __name__ == '__main__':
main()
N queens
STUCK = 0
DONE = 1
steps = 0
def generate(size):
square = []
# Generate a square of dimensions `size`
for _ in range(size):
listofzeros = [0] * size
square.append(listofzeros)
#print(square)
return square
# This function reutrns true if given position is safe for new queen
def is_safe(board: list, row: int, col: int) -> bool:
# Check the row
for i in range(len(board)):
if board[row][i] == 1:
return False
# Check the column
for i in range(len(board)):
if board[i][col] == 1:
return False
# Check the left diagonal
for difference in range(1, len(board)):
_row = row - difference
_col = col - difference
if _row < 0 or _col < 0:
break
if board[_row][_col] == 1:
return False
for difference in range(1, len(board)):
_row = row + difference
_col = col + difference
if _row >= len(board) or _col >= len(board):
break
if board[_row][_col] == 1:
return False
# Check the right diagonal
for difference in range(1, len(board)):
_row = row + difference
_col = col - difference
if _row >= len(board) or _col < 0:
break
if board[_row][_col] == 1:
return False
for difference in range(1, len(board)):
_row = row - difference
_col = col + difference
if _row < 0 or _col >= len(board):
break
if board[_row][_col] == 1:
return False
return True
# This function takes board and row and returns all safe column spots of that row
def get_all_safe_spots(board: list, row: int) -> list:
spots = []
for column in range(len(board)):
if is_safe(board, row, column):
spots.append(column)
return spots
def solve(board, row: int = 0):
if row >= len(board):
return DONE
global steps
print("\n", f" Step {steps} ".center(20, '='))
display_board(board)
steps += 1
spots = get_all_safe_spots(board, row)
if len(spots) == 0:
print("No safe spots left for current queen!")
return STUCK
for i in range(len(board)):
if i not in spots:
print(f"Skipping column {i + 1} because it is not safe")
continue
spot = i
board[row][spot] = 1
# If we can't place next queen then backtrack and select next position for
current queen
if solve(board, row + 1) == STUCK:
print(f"Backtracking from row {row + 1} column {spot + 1} ..")
board[row][spot] = 0
else:
# If every position of queen is filled then its done
if sum([sum(row) for row in board]) == len(board):
print("\n", f" Step {steps} ".center(20, '='))
display_board(board)
exit()
# If every position of queen is filled then its done
if sum([sum(row) for row in board]) == len(board):
return DONE
else:
# Otherwise backtrack
print(f"Backtracking from row {row + 1} column {spot + 1} ...")
return STUCK
def display_board(board: list, special: bool = True) -> None:
if not special:
for i in range(len(board)):
for j in range(len(board)):
if board[i][j] == 1:
print('{:3}'.format(1), end='')
else:
print('{:>3}'.format('.'), end='')
print()
return
for i in range(len(board)):
solid = i % 2 == 0
for j in range(len(board)):
if board[i][j] == 1:
print('{:>3}'.format('👑'), end='')
else:
if solid:
print('{:>3}'.format('⬛'), end='')
else:
print('{:>3}'.format('⬜'), end='')
solid = not solid
print()
def main():
size = int(input("Enter size of chessboard: "))
board = generate(size)
if solve(board) == STUCK:
print("\nThere are no valid queen positions for given dimensions of board")
return
print("\n", " Finally ".center(20, '='))
display_board(board, True)
if __name__ == '__main__':
main()

Magic Square
def generate(size: int) -> list:
EMPTY = 0
square = []
# Generate a square of dimensions `size`
for _ in range(size):
buffer = []
for _ in range(size):
buffer.append(EMPTY)
square.append(buffer)
counter = 1
row = 0
col = len(square) // 2
# Pick middle of first row as 1
square[row][col] = counter
while counter != size ** 2:
print("\n", f" Step {counter} ".center(20, '='), sep='')
display(square)
counter += 1
cyclic_row = row - 1
cyclic_column = col + 1
cyclic_row = cycle(cyclic_row, size)
cyclic_column = cycle(cyclic_column, size)
# Check if North-East slot is available
if square[cyclic_row][cyclic_column] == 0:
square[cyclic_row][cyclic_column] = counter
row, col = cyclic_row, cyclic_column
else:
# Otherwise go South
row += 1
square[row][col] = counter
return square
# For verbosity ... The entire thing could've been a single % opeartion lmao
def cycle(number: int, size: int) -> int:
if number == size:
return 0
elif number > size:
return number % size
elif number < 0:
number *= -1
number %= size
number = size - number
return number
else:
return number
def display(board: list) -> None:
for row in board:
for col in row:
print('{:5}'.format(col), end='')
print()
def main():
while True:
size = int(input("Enter size of square: "))
if size % 2 == 0:
print("Please type an odd number!")
continue
board = generate(size)
print("\n", f" Step {size ** 2} ".center(20, '='))
display(board)
break
if __name__ == '__main__':
main()

You might also like