Accomplishment: Tic Tac Toe game with Python & Kivy
I have created a simple tic tac toe game with a random bot logic (really random after a user selects a mark). Next step would be to insert the minimax algorithm for example, but I would like to know if the path I've taken to construct my code is correct and could it be improved.
I have two files: main.py and ai.py
main.py
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.popup import Popup
from kivy.uix.label import Label
from kivy.uix.stacklayout import StackLayout
from kivy.config import Config
from ai import Ai
from random import randint
class TicTacToe(App):
title = 'Tic Tac Toe'
board = []
choices = ["X","O"]
# On application build handler
def build(self):
Config.set('graphics', 'width', '600')
Config.set('graphics', 'height', '600')
self.layout = StackLayout()
for x in range(9): # range() explanation: http://pythoncentral.io/pythons-range-function-explained/
bt = Button(text='', font_size=200, width=200, height=200, size_hint=(None, None), id=str(x))
bt.bind(on_release=self.btn_pressed)
self.board.append(bt)
self.layout.add_widget(bt)
return self.layout
# On application start handler
def on_start(self):
self.init_players();
greeting = "Hello Player! You are playing with \"" + self.player + "\""
self.popup_message(greeting)
# On button pressed handler
def btn_pressed(self, button):
if len(button.text.strip()) < 1: # Continue only if the button has no mark on it...
button.text = self.player
self.bot.make_move(self.board)
self.check_winner()
# Initializes players
def init_players(self):
rand_choice = randint(0,1);
self.bot = Ai(self.choices[rand_choice]);
self.player = self.choices[0] if rand_choice == 1 else self.choices[1]
# Checks winner after every move...
def check_winner(self):
pass # Just void..
def popup_message(self, msg):
popup = Popup(title="Welcome!", content=Label(text=msg), size=(300, 100), size_hint=(None, None))
popup.open()
if __name__ == '__main__':
TicTacToe().run()
ai.py
from random import randint
class Ai:
def __init__(self, choice):
self.choice = choice
# Main function for bot making a move
def make_move(self, board):
self.make_random_move(board) # Do a random move
# Makes a random move by generating a random integer and checking if the place is free
def make_random_move(self, board):
free_buttons = []
for button in board: # Simple for loop to extract the free buttons
if len(button.text.strip()) < 1: # If the button has no mark, stripping spaces...
free_buttons.append(button)
if len(free_buttons) > 1: # If any free buttons left... let's make the move
rand = randint(0, len(free_buttons) - 1) # Generate a random integer from 0 to the length of the array
free_buttons[rand].text = self.choice