Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- array = []
- def init(array):
- for i in range(3):
- array.append([])
- for j in range(3):
- array[i].append(" ")
- def writeArray(array):
- for i in range(3):
- if i != 0:
- print("-----------")
- for j in range(3):
- if j == 2:
- print(array[i][j])
- else:
- print(" ", array[i][j], " |", sep="", end="")
- def integer(s):
- try:
- int(s)
- return True
- except ValueError:
- return False
- def takeTurn(array):
- tileX = input("X: ")
- tileY = input("Y: ")
- if integer(tileX) == True and integer(tileY) == True:
- tileX = int(tileX)
- tileY = int(tileY)
- else:
- print("Those are not values.")
- takeTurn(array)
- return
- if tileX < 4 and tileX > 0 and tileY < 4 and tileY> 0:
- tileX = tileX - 1
- tileY = tileY - 1
- else:
- print("Those are not values.")
- takeTurn(array)
- return
- if array[tileY][tileX] == " ":
- array[tileY][tileX] = "X"
- else:
- print("Something already exists at that point.")
- takeTurn(array)
- return
- def win(array):
- for i in range(3):
- if array[i][0] == array[i][1]and array[i][1] == array[i][2]:
- return array[i][0]
- if array[0][i] == array[1][i] and array[1][i] == array[2][i]:
- return array[0][i]
- if array[0][0] == array[1][1] and array[1][1] == array[2][2]:
- return array[0][0]
- if array[2][0] == array[1][1] and array[1][1] == array[0][2]:
- return array[0][2]
- return " "
- def score(array, depth):
- if win(array) == "X":
- return 10 - depth
- elif win(array) == "O":
- return depth - 10
- else:
- return 0
- def getMoves(array):
- moves = []
- for i in range(3):
- for j in range(3):
- if array[i][j] == " ":
- moves.append([i, j])
- return moves
- def minmax(array, depth, player):
- if win(array) != " ":
- return
- scores = []
- depth = depth + 1
- moves = getMoves(array)
- if len(moves) > 0:
- newArray = array
- for i in range(len(moves)):
- if player == "O":
- newArray[moves[i][1]][moves[i][0]] = "O"
- scores.append(minmax(newArray, depth, "X"))
- elif player == "X":
- newArray[moves[i][1]][moves[i][0]] = "X"
- scores.append(minmax(newArray, depth, "O"))
- if player == "X":
- maxM = max(scores)
- choice = moves[scores.index(maxM)]
- return maxM
- elif player == "O":
- minM = min(scores)
- choice = moves[scores.index(minM)]
- return minM
- init(array)
- turns = 0
- choice = []
- while True:
- writeArray(array)
- takeTurn(array)
- turns = turns + 1
- print(win(array))
- minmax(array, turns, "O")
- array[choice[1]][choice[0]] = "O"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement