Skip to content

Instantly share code, notes, and snippets.

@berkgoksel
Last active February 20, 2019 16:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save berkgoksel/7b69e67d0ea7b47a5f016dc477120857 to your computer and use it in GitHub Desktop.
Save berkgoksel/7b69e67d0ea7b47a5f016dc477120857 to your computer and use it in GitHub Desktop.
from pip._internal import main
import sys
inst = {'y','yes'}
try:
import numpy as np
print("Everything seems OK. No need for setup.")
except ImportError:
answer = input("The game requires numpy to be installed. Would you like to install it? [Y/n]\n")
if answer in ('yes', 'y', 'Y', 'YES', 'Yes'):
try:
main(['install', 'numpy'])
print("Setup complete. Happy gaming!")
except Exception as e: print("Something went wrong:\n" + e)
else:
sys.exit("Sorry! Can't play the game without numpy. You can install it manually.")
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
import os
import time
import sys
import random
class tacToe:
def __init__(self, name_player1="player1", name_player2="player2"):
self.game = np.full((3,3),[' '], dtype=str) #np.empty doesnt print the spaces. Used np.full instead
self.plane = ['A1','A2','A3','B1','B2','B3','C1','C2','C3']
self.filled_slots = []
self.turn = 1
self.max_turns = 9
self.player1 = name_player1
self.player2 = name_player2
self.line = ' ---|---|---'
self.character = 'K'
self.starter = 1
def clear(self):
if os.name == 'nt':
os.system('cls')
else:
try:
os.system('clear')
except:
sys.exit("Operating system not supported yet. You can send me an email or fix it yourself. Its basically a clear screen issue")
if self.turn == 10:
print("Out of moves.")
#Dont print this looking at turn. use another variable.
elif (self.turn % 2 == 0):
print(self.player2 + "'s turn (Turn: " + str(self.turn) + ")")
self.character = 'O'
else:
print(self.player1 + "'s turn (Turn: " + str(self.turn) + ")")
self.character = 'X'
def show_game(self):
self.clear()
print('\n A B C')
print('\n1 %s | %s | %s ' % (self.game[0][0], self.game[0][1], self.game[0][2]))
print(self.line)
print('2 %s | %s | %s ' % (self.game[1][0], self.game[1][1], self.game[1][2]))
print(self.line)
print('3 %s | %s | %s \n' % (self.game[2][0], self.game[2][1], self.game[2][2]))
def modify_matrix(self, position):
#Dictionary looked like it was going to take longer. Here goes:
if position == 'A1':
self.game[0,0] = self.character
if position == 'A2':
self.game[1,0] = self.character
if position == 'A3':
self.game[2,0] = self.character
if position == 'B1':
self.game[0,1] = self.character
if position == 'B2':
self.game[1,1] = self.character
if position == 'B3':
self.game[2,1] = self.character
if position == 'C1':
self.game[0,2] = self.character
if position == 'C2':
self.game[1,2] = self.character
if position == 'C3':
self.game[2,2] = self.character
self.filled_slots.append(position) #We already checked if position is in plane[].
print("Modified: " + position)
def choice(self):
position = input("Move: ").upper()
if position in self.filled_slots:
print("Invalid entry! This slot has already been filled.")
time.sleep(1)
self.turn = self.turn - 1 #So the counter doesnt keep increasing with wrong entries.
time.sleep(1)
elif position in self.plane:
self.modify_matrix(position)
else:
print("Invalid Input! ")
self.turn = self.turn -1
time.sleep(1)
def random_bot_choice(self):
#bot input
pos_plane = np.array(self.plane)
pos_filled_slots = np.array(self.filled_slots)
pos_arr = np.setdiff1d(pos_plane, pos_filled_slots)
pos_arr_length = len(pos_arr) - 1
some_int = random.randint(0, pos_arr_length)
pos = pos_arr[some_int]
if pos in self.plane:
self.modify_matrix(pos)
def won(self, array):
if all(z == array[0] for z in array):
if (array[1] == "X"):
self.show_game()
sys.exit(self.player1 + " Won!")
elif (array[1] == "O"):
self.show_game()
sys.exit(self.player2 + " Won!")
def win_lose(self):
for a in range(1,4):
columns = (self.game[:,a-1:a])
self.won(columns)
for b in range(1,4):
rows = (self.game[b-1:b,:])
self.won(rows.T)
diagonal1 = (self.game.diagonal())
self.won(diagonal1)
diagonal2 = (np.fliplr(self.game).diagonal())
self.won(diagonal2)
def run_multi(self):
print("Let the battle begin!")
time.sleep(0.7)
while (self.turn <= self.max_turns):
self.show_game()
self.turn = self.turn + 1
self.choice()
if (self.turn > 5): #Can't win the game in less than 5 turns.
self.win_lose() #Check if anybody has won.
if self.turn == 10:
self.win_lose()
self.show_game()
sys.exit("It's a draw!")
def run_single(self):
while (self.turn <= self.max_turns):
self.show_game()
flag = self.turn
self.turn = self.turn + 1
if self.starter == 0:
self.choice()
if (flag != self.turn):
self.starter = 1
else:
time.sleep(1.2)
self.random_bot_choice()
self.starter = 0
if (self.turn > 5): #Can't win the game in less than 5 turns.
self.win_lose() #Check if anybody has won.
if self.turn == 10:
self.win_lose()
self.show_game()
sys.exit("It's a draw!")
#Add a banner
gameMode = 3
while not (gameMode == '1' or gameMode == '2'):
gameMode = input("Choose Game Mode: \n (1) for Single Player \n (2) for Multiplayer\n ")
if gameMode == "2":
name_player1 = input("Name for Player1: ")
name_player2 = input("Name for Player2: ")
theGame = tacToe(name_player1, name_player2) #Initialize the class
theGame.run_multi()
elif gameMode == "1":
#Check who goes first.
number = random.randint(0,1)
player_name = input("Name for player: ")
if number == 0:
theGame = tacToe("TheBot", player_name)
theGame.starter = 1
else:
theGame = tacToe(player_name, "TheBot")
theGame.starter = 0
print("Let the battle begin!")
time.sleep(0.7)
theGame.run_single()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment