• Home
  • /
  • Blog
  • /
  • 5 Interesting Games in Python That Kids Can Make

5 Interesting Games in Python That Kids Can Make

Games in Python That Kids Can Make

This post is also available in: हिन्दी (Hindi) العربية (Arabic)

Creating your own computer games in Python is a great way to learn the language.

To build a game, you’ll need to use many core programming skills. The kinds of skills that you’ll see in real-world programming. In game development, you’ll use variables, loops, conditional statements, functions, object-oriented programming, and a whole bunch of programming techniques and algorithms.

As a plus, you’ll have the satisfaction to play the game you’ve just created!

Python Frameworks for Game Development

In the Python ecosystem, you’ll find a rich set of tools, libraries, and frameworks that will help you create your games quickly. 

Games in Python That Kids Can Make

Some of the most important frameworks available in Python for game creation are:

1. Pygame

Pygame is an open-source Python library for making multimedia applications like games built on top of the excellent SDL library. This library is a combination of C, Python, Native, and  OpenGL. Pygame enables users to build fully featured games as well as multimedia programs with Python programming. It is highly portable and runs on nearly every platform and operating system.

Some of the features are: –

  • Multicore CPUs can be used easily
  • Uses optimized C and Assembly code for core functions
  • Simple and Portable
  • A small amount of code is needed

2. PyKyra

PyKyra is one of the fastest game development frameworks for Python that is based on both SDL (Software and Documentation Localisation) and the Kyra engine. Along with the standard features of this framework, it also supports MPEG video, sounds such as MP3, Ogg Vorbis, Wav, etc., direct image reading, and much more.

3. Pyglet

Pyglet is an open-sourced, cross-platform windowing and multimedia library for Python. It is a powerful Python library that can be used for developing games and other visually-rich applications on Windows, Mac OS X, and Linux. Pyglet supports windowing, user interface event handling, Joysticks, OpenGL graphics, loading images, and videos, and playing sounds and music. Pyglet runs under Python 3.5+ and also works on other Python interpreters such as PyPy.

Some of the features are-

  • No external dependencies or installation requirements
  • Flexible native windowing
  • Built-in support for images and audio
  • Written in pure Python

4. PyOpenGL

PyOpenGL is one of the most common cross-platform Python bindings to OpenGL and related APIs. In PyOpenGL, the binding is created using the standard ctypes library. PyOpenGL is interoperable with a large number of external GUI libraries for Python including PyGame, PyQt, Raw XLib, among others.

5. Kivy

Equipped with novel user interfaces like multi-touch apps, Kivy is an open-source and cross-platform Python library for the rapid development of applications. Kivy runs on Linux, Windows, OS X, Android, iOS, and Raspberry Pi and can natively use most inputs, protocols, and devices including WM_Touch, WM_Pen, Mac OS X Trackpad, and Magic Mouse, Mtdev, Linux Kernel HID, and TUIO. The library is GPU accelerated, and it comes with more than 20 widgets that are all highly extensible.

6. Panda3D

Written in Python and C++, Panda3D is an open-source and completely free-to-use engine for real-time 3D games, visualizations, simulations, experiments, and more. Panda3D includes command-line tools for processing and optimizing source assets that allow users to automate and script the content production pipeline. It supports many popular third-party libraries, such as the Bullet physics engine, Assimp model loader, OpenAL and FMOD sound libraries, and more.

7. Cocos2d

Written in Python, C++, and Objective C, Cocos2d is an open-source software framework that can be used to build games, apps, and other cross-platform GUI-based interactive programs. The Cocos2d family consists of Cocos2d-x, Cocos2d-JS, Cocos2d-XNA and Cocos2d (Python). Cocos2d-x is an open-source game framework written in C++, with a thin platform-dependent layer, and can be used to build games, apps, and other cross-platform GUI-based interactive programs. Also, Cocos2d-JS is the Cocos2d-x engine’s javascript version that supports full Cocos2d-x functionality with a set of simplified javascript-friendly APIs.

8. Python-Ogre

Python-Ogre or PyOgre is a Python binding of a C++ library for the OGRE 3D engine. PyOgre is a cross-platform and inherits speed and flexibility. Ogre is a 3D rendering engine written entirely in C++ that supports an impressive feature set and has been used to create impressive games. PyOgre actually consists of two libraries. The first is Ogre3d, which is a 3D rendering engine and the second is CEGUi, which is an embedded GUI system.

9. Ren’Py

Written in Python and Cython, Ren’Py is a free and cross-platform engine for digital storytelling that makes it easy to combine words, images, and sounds to create visual novels and life simulation games. Ren’Py’s support for the Python scripting language allows developers to work with complex game logic. One of Ren’Py’s biggest advantages is that it runs on almost every computer system.

Games in Python That Kids Can Make

We bring you 5 interesting activities and games that kids can make in Python.

1. Paint

Most of us are familiar with paint application in Windows that we use to draw pictures and colour them. But what if you create your own paint program with Pygame. Isn’t it exciting? 

Games in Python That Kids Can Make

The complete application can be viewed as the following sub-modules: Creating a Window to draw: As a first step, we will create a window on which we will draw. This window will be used to hold the pictures being drawn. Defining the colours of the pencil: In order to draw multi-coloured pictures, you need the option to pick pencils of different colours. And finally, a code to draw an image when the mouse is moved across the window.

import pygame
import pygame.gfxdraw
#Initializing pygame module
pygame.init()
 
#Screen variables
screen_width = 700
screen_height =500
 
# Defining Colors
white = (255, 255, 255)
blue = (67,238,250)
red = (255, 0, 0)
black = (0, 0, 0)
green = (38,245,45)
pink = (255,192,203)
orange = (255,165,0)
yellow = (255,255,0)
violet = (177, 3, 252)
 
#Setting default color to black
pencolour = black
 
 
drawingwindow =  pygame.display.set_mode((screen_width,screen_height))
pygame.display.set_caption("Paint - By Bhavik Agarwal")
drawingwindow.fill((255,255,255))
 
#Loading backgroud image and drawing it on screen
backimg = pygame.image.load("paint.png").convert_alpha()
drawingwindow.blit(backimg, (0,0))
 
#rect for the drawing area
clearrect = (119, 17, 562, 465)
 
#Defining rect value for colors in colorbox
col1= (22, 81, 30, 34)
col2= (56, 81, 34, 34)
col3= (22, 120, 30, 33)
col4= (56, 120, 34, 32)
col5= (22, 156, 30, 33)
col6= (56, 156, 34, 32)
col7= (22, 192, 30, 33)
col8= (56, 192, 34, 32)
 
#Rect that highlight which button is selected
buttonselect = (22, 81, 30, 34)
 
#Function to draw color box
def drawrectangle():    
    pygame.gfxdraw.box(drawingwindow, col1, black)
    pygame.gfxdraw.box(drawingwindow, col2, blue)
    pygame.gfxdraw.box(drawingwindow, col3, red)
    pygame.gfxdraw.box(drawingwindow, col4, green)
    pygame.gfxdraw.box(drawingwindow, col5, pink)
    pygame.gfxdraw.box(drawingwindow, col6, orange)
    pygame.gfxdraw.box(drawingwindow, col7, yellow)
    pygame.gfxdraw.box(drawingwindow, col8, violet)
drawrectangle()
 
#Set mouse cursor for pencil (default)
pygame.mouse.set_cursor(*pygame.cursors.broken_x)
exit_game = False
 
#Gameloop
while not exit_game:
    
 
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exit_game = True
    
                        
        #Check for button clicks
        t = pygame.mouse.get_pressed()
        if t[0] == 1:     
            mousepos = pygame.mouse.get_pos()
            if 122 < mousepos[0] < 678 and 21 < mousepos[1] < 480:
                pygame.gfxdraw.filled_ellipse(drawingwindow,mousepos[0], mousepos[1],4,4,pencolour)
                
            elif 22 < mousepos[0] < 52 and 81 < mousepos[1] < 115:
                pencolour = black
                drawrectangle()         
                buttonselect = (22, 81, 30, 34)
                
            elif 56 < mousepos[0] < 90 and 81 < mousepos[1] < 115:
                pencolour = blue
                drawrectangle()
                buttonselect = (56, 81, 34, 34)
                
            elif 22 < mousepos[0] < 52 and 120 < mousepos[1] < 153:
                pencolour = red
                drawrectangle()
                buttonselect = (22, 120, 30, 33)
                
            elif 56 < mousepos[0] < 90 and 120 < mousepos[1] < 152:
                pencolour = green
                drawrectangle()
                buttonselect = (56, 120, 34, 32)
                
            elif 22 < mousepos[0] < 52 and 156 < mousepos[1] < 189:
                pencolour = pink
                drawrectangle()
                buttonselect = (22, 156, 30, 33)
                
            elif 56 < mousepos[0] < 90 and 156 < mousepos[1] < 188:
                pencolour = orange
                drawrectangle()
                buttonselect = (56, 156, 34, 32)
                
            elif 22 < mousepos[0] < 52 and 192 < mousepos[1] < 225:
                pencolour = yellow
                drawrectangle()
                buttonselect = (22, 192, 30, 33)
                
            elif 56 < mousepos[0] < 90 and 192 < mousepos[1] < 224:
                pencolour = violet
                drawrectangle()
                buttonselect = (56, 192, 34, 32)
            #Eraser
            elif 13 < mousepos[0] < 54 and 247 < mousepos[1] < 285:
                pencolour = white
                drawrectangle()
                pygame.mouse.set_cursor(*pygame.cursors.diamond)
            #Pencil
            elif 59 < mousepos[0] < 97 and 247 < mousepos[1] < 288:
                pencolour = black
                drawrectangle()
                pygame.mouse.set_cursor(*pygame.cursors.broken_x)
                buttonselect = (22, 81, 30, 34)
                
            elif 15 < mousepos[0] < 96 and 363 < mousepos[1] < 400:                
                pygame.gfxdraw.box(drawingwindow, clearrect, white)
 
        pygame.gfxdraw.rectangle(drawingwindow, buttonselect, white)
        pygame.display.update()
                
            
pygame.quit()

2. Snake Game

You all have played the Snake Game and definitely, you never wanted to lose. As kids, we all loved looking for cheats in order to never see the “Game Over” message. But as techies, you would want to make this ‘Snake’ dance to your beats. 

Games in Python That Kids Can Make

You can build a snake game by creating the modules – Create the Screen, Create the Snake, Moving the Snake, Game Over when Snake hits the boundaries, Adding Food, Increasing the Length of the Snake, Displaying the Score.

import pygame
import time
import random
 
pygame.init()
 
white = (255, 255, 255)
yellow = (255, 255, 102)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)
 
dis_width = 600
dis_height = 400
 
dis = pygame.display.set_mode((dis_width, dis_height))
pygame.display.set_caption('Snake Game')
 
clock = pygame.time.Clock()
 
snake_block = 10
snake_speed = 15
 
font_style = pygame.font.SysFont("bahnschrift", 25)
score_font = pygame.font.SysFont("comicsansms", 35)
 
 
def Your_score(score):
    value = score_font.render("Your Score: " + str(score), True, yellow)
    dis.blit(value, [0, 0])
 
 
 
def our_snake(snake_block, snake_list):
    for x in snake_list:
        pygame.draw.rect(dis, black, [x[0], x[1], snake_block, snake_block])
 
 
def message(msg, color):
    mesg = font_style.render(msg, True, color)
    dis.blit(mesg, [dis_width / 6, dis_height / 3])
 
 
def gameLoop():
    game_over = False
    game_close = False
 
    x1 = dis_width / 2
    y1 = dis_height / 2
 
    x1_change = 0
    y1_change = 0
 
    snake_List = []
    Length_of_snake = 1
 
    foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
    foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
 
    while not game_over:
 
        while game_close == True:
            dis.fill(blue)
            message("You Lost! Press C-Play Again or Q-Quit", red)
            Your_score(Length_of_snake - 1)
            pygame.display.update()
 
            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        game_over = True
                        game_close = False
                    if event.key == pygame.K_c:
                        gameLoop()
 
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_over = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    x1_change = -snake_block
                    y1_change = 0
                elif event.key == pygame.K_RIGHT:
                    x1_change = snake_block
                    y1_change = 0
                elif event.key == pygame.K_UP:
                    y1_change = -snake_block
                    x1_change = 0
                elif event.key == pygame.K_DOWN:
                    y1_change = snake_block
                    x1_change = 0
 
        if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:
            game_close = True
        x1 += x1_change
        y1 += y1_change
        dis.fill(blue)
        pygame.draw.rect(dis, green, [foodx, foody, snake_block, snake_block])
        snake_Head = []
        snake_Head.append(x1)
        snake_Head.append(y1)
        snake_List.append(snake_Head)
        if len(snake_List) > Length_of_snake:
            del snake_List[0]
 
        for x in snake_List[:-1]:
            if x == snake_Head:
                game_close = True
 
        our_snake(snake_block, snake_List)
        Your_score(Length_of_snake - 1)
 
        pygame.display.update()
 
        if x1 == foodx and y1 == foody:
            foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
            foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
            Length_of_snake += 1
 
        clock.tick(snake_speed)
 
    pygame.quit()
    quit()
 
 
gameLoop()

3. Dot Connect

Dot Connect game is the one where a player connects the dots to make boxes. The rules are well-known: each player gets to create a new line between two dots (single-click near the line you wish to create). If a player creates a box, he gets a point and gets to go again. (Two boxes get two points, but only one extra turn.) The highest score out of 81 boxes wins!

Games in Python That Kids Can Make

from Tkinter import *
import tkFont
 
TOL = 8
CELLSIZE = 40
OFFSET = 10
CIRCLERAD = 2
DOTOFFSET = OFFSET + CIRCLERAD
GAME_H = 400
GAME_W = 400
 
 
class Player(object):
 
    def __init__(self, name, color="black"):
        self.score = 0
        self.str = StringVar()
        self.name = name
        self.color = color
 
    def update(self):
        self.str.set(self.name + ": %d" % self.score)
 
 
 
class MyFrame(Frame):
 
    def __init__(self, master):
        Frame.__init__(self, master)
        self.GO_font = tkFont.Font(self, \
                                   name="GOFont", \
                                   family = "Times", \
                                   weight="bold", \
                                   size=36)
        self.canvas = Canvas(self, height = GAME_H, width = GAME_W)
        self.canvas.bind("<Button-1>", lambda e:self.click(e))
        self.canvas.grid(row=0,column=0)
 
        self.dots = [[self.canvas.create_oval(CELLSIZE*i+OFFSET, \
                                              CELLSIZE*j+OFFSET, \
                                              CELLSIZE*i+OFFSET+2*CIRCLERAD, \
                                              CELLSIZE*j+OFFSET+2*CIRCLERAD, \
                                              fill="black") \
                      for j in range(10)] for i in range(10)]
        self.lines = []
 
        self.infoframe = Frame(self)
        self.players = [Player("Player 1","blue"), Player("Player 2","red")]
        self.infoframe.players = [Label(self.infoframe, textvariable = i.str) for i in self.players]
        for i in self.infoframe.players:
            i.grid()
        
        self.turn = self.players[0]
        self.update_players()
        self.infoframe.grid(row = 0, column = 1, sticky = N)
 
        self.grid()
 
    def update_players(self):
        for i in self.players:
            i.update()
 
    def click(self, event):
        x,y = event.x, event.y
        orient = self.isclose(x,y)
 
        if orient:
            if self.line_exists(x,y, orient):
                return
            l = self.create_line(x,y, orient)
            score = self.new_box_made(l)
            if score:
                self.turn.score += score
                self.turn.update()
                self.check_game_over()
            else:
                index = self.players.index(self.turn)
                self.turn = self.players[1-index]
            self.lines.append(l)
 
    def create_line(self, x, y, orient):
        startx = CELLSIZE * ((x-OFFSET)//CELLSIZE) + DOTOFFSET
        starty = CELLSIZE * ((y-OFFSET)//CELLSIZE) + DOTOFFSET
        tmpx = (x-OFFSET)//CELLSIZE
        tmpy = (y-OFFSET)//CELLSIZE
        
        if orient == HORIZONTAL:
            endx = startx + CELLSIZE
            endy = starty
        else:
            endx = startx
            endy = starty + CELLSIZE
        #print "line drawn: %d,%d to %d,%d" % (startx,starty,endx,endy)
        return self.canvas.create_line(startx,starty,endx,endy)
        
 
    def new_box_made(self, line):
        score = 0
        x0,y0,x1,y1 = self.canvas.coords(line)
        if x0 == x1: # vertical line
            midx = x0
            midy = (y0+y1)/2
            pre = (x0 - CELLSIZE/2, midy)
            post = (x0 + CELLSIZE/2, midy)
        elif y0 == y1: # horizontal line
            midx = (x0 + x1)/2
            midy = y0
            pre = (midx, y0 - CELLSIZE/2)
            post = (midx, y0 + CELLSIZE/2)
        
        if len(self.find_lines(pre)) == 3:  # not 4, because newly created line is 
            self.fill_in(pre)               # is not returned (?!)
            score += 1
        if len(self.find_lines(post)) == 3:
            self.fill_in(post)
            score += 1
        return score
 
    def find_lines(self, coords):
        x, y = coords
        if x < 0 or x > GAME_W:
            return []
        if y < 0 or y > GAME_W:
            return []
        #print "Cell center: %d,%d" % (x,y)
        lines = [x for x in self.canvas.find_enclosed(x-CELLSIZE,\
                                                      y-CELLSIZE,\
                                                      x+CELLSIZE,\
                                                      y+CELLSIZE)\
                 if x in self.lines]
        #print lines
        return lines
 
    def fill_in(self, coords):
        x,y = coords
        self.canvas.create_text(x,y,text=self.turn.name, fill=self.turn.color)
        
    def isclose(self, x, y):
        x -= OFFSET
        y -= OFFSET
        dx = x - (x//CELLSIZE)*CELLSIZE
        dy = y - (y//CELLSIZE)*CELLSIZE
        
        if abs(dx) < TOL:
            if abs(dy) < TOL:
                return None  # mouse in corner of box; ignore
            else:
                return VERTICAL
        elif abs(dy) < TOL:
            return HORIZONTAL
        else:
            return None
 
    def line_exists(self, x,y, orient):
        id_ = self.canvas.find_closest(x,y,halo=TOL)[0]
        if id_ in self.lines:
            return True
        else:
            return False
 
    def check_game_over(self):
        total = sum([x.score for x in self.players])
        if total == 81:
            self.canvas.create_text(GAME_W/2, GAME_H/2, \
                                    text="GAME OVER", font="GOFont", \
                                    fill="#888")
        
        
mainw = Tk()
mainw.f = MyFrame(mainw)
mainw.mainloop()

4. Ping Pong

Pong is one of the most famous arcade games, simulating table tennis. Each player controls a paddle in the game by dragging it vertically across the screen’s left or right side. Players use their paddles to strike back and forth on the ball.

Games in Python That Kids Can Make

Turtle is an inbuilt graphic module in Python. It uses a panel and pen to depict illustrations. 

Below are the steps used:

  • Step 1) Create two paddles A and B on the left and right sides of the screen.
  • Step 2) Create a ball.
  • Step 3) Create an event to move the paddle vertically by pressing a certain key.
  • Step 4) Create the function to update the score after each player misses a collision.

# Import required library
import turtle
 
 
# Create screen
sc = turtle.Screen()
sc.title("Pong game")
sc.bgcolor("white")
sc.setup(width=1000, height=600)
 
 
# Left paddle
left_pad = turtle.Turtle()
left_pad.speed(0)
left_pad.shape("square")
left_pad.color("black")
left_pad.shapesize(stretch_wid=6, stretch_len=2)
left_pad.penup()
left_pad.goto(-400, 0)
 
 
# Right paddle
right_pad = turtle.Turtle()
right_pad.speed(0)
right_pad.shape("square")
right_pad.color("black")
right_pad.shapesize(stretch_wid=6, stretch_len=2)
right_pad.penup()
right_pad.goto(400, 0)
 
 
# Ball of circle shape
hit_ball = turtle.Turtle()
hit_ball.speed(40)
hit_ball.shape("circle")
hit_ball.color("blue")
hit_ball.penup()
hit_ball.goto(0, 0)
hit_ball.dx = 5
hit_ball.dy = -5
 
 
# Initialize the score
left_player = 0
right_player = 0
 
 
# Displays the score
sketch = turtle.Turtle()
sketch.speed(0)
sketch.color("blue")
sketch.penup()
sketch.hideturtle()
sketch.goto(0, 260)
sketch.write("Left_player : 0 Right_player: 0",
			align="center", font=("Courier", 24, "normal"))
 
 
# Functions to move paddle vertically
def paddleaup():
	y = left_pad.ycor()
	y += 20
	left_pad.sety(y)
 
 
def paddleadown():
	y = left_pad.ycor()
	y -= 20
	left_pad.sety(y)
 
 
def paddlebup():
	y = right_pad.ycor()
	y += 20
	right_pad.sety(y)
 
 
def paddlebdown():
	y = right_pad.ycor()
	y -= 20
	right_pad.sety(y)
 
 
# Keyboard bindings
sc.listen()
sc.onkeypress(paddleaup, "e")
sc.onkeypress(paddleadown, "x")
sc.onkeypress(paddlebup, "Up")
sc.onkeypress(paddlebdown, "Down")
 
 
while True:
	sc.update()
 
	hit_ball.setx(hit_ball.xcor()+hit_ball.dx)
	hit_ball.sety(hit_ball.ycor()+hit_ball.dy)
 
	# Checking borders
	if hit_ball.ycor() > 280:
		hit_ball.sety(280)
		hit_ball.dy *= -1
 
	if hit_ball.ycor() < -280:
		hit_ball.sety(-280)
		hit_ball.dy *= -1
 
	if hit_ball.xcor() > 500:
		hit_ball.goto(0, 0)
		hit_ball.dy *= -1
		left_player += 1
		sketch.clear()
		sketch.write("Left_player : {} Right_player: {}".format(
					left_player, right_player), align="center",
					font=("Courier", 24, "normal"))
 
	if hit_ball.xcor() < -500:
		hit_ball.goto(0, 0)
		hit_ball.dy *= -1
		right_player += 1
		sketch.clear()
		sketch.write("Left_player : {} Right_player: {}".format(
								left_player, right_player), align="center",
								font=("Courier", 24, "normal"))
 
	# Paddle ball collision
	if (hit_ball.xcor() > 360 and
						hit_ball.xcor() < 370) and
						(hit_ball.ycor() < right_pad.ycor()+40 and
						hit_ball.ycor() > right_pad.ycor()-40):
		hit_ball.setx(360)
		hit_ball.dx*=-1
		
	if (hit_ball.xcor()<-360 and
					hit_ball.xcor()>-370) and
					(hit_ball.ycor()<left_pad.ycor()+40 and
						hit_ball.ycor()>left_pad.ycor()-40):
		hit_ball.setx(-360)
		hit_ball.dx*=-1

5. Tic Tac Toe

Tic Tac Toe is one of the most played games and is the best time killer game that you can play anywhere with just a pen and paper. If you don’t know how to play this game don’t worry let us first understand that.

Games in Python That Kids Can Make

The game is played by two individuals. First, we draw a board with a 3×3 square grid. The first player chooses ‘X’ and draws it on any of the square grid, then it’s the chance of the second player to draw ‘O’ on the available spaces. Like this, the players draw ‘X’ and ‘O’ alternatively on the empty spaces until a player succeeds in drawing 3 consecutive marks either in the horizontal, vertical or diagonal way. Then the player wins the game otherwise the game draws when all spots are filled.

# Tic-Tac-Toe Program using
# random number in Python

# importing all necessary libraries
import numpy as np
import random
from time import sleep

# Creates an empty board
def create_board():
	return(np.array([[0, 0, 0],
					[0, 0, 0],
					[0, 0, 0]]))

# Check for empty places on board
def possibilities(board):
	l = []
	
	for i in range(len(board)):
		for j in range(len(board)):
			
			if board[i][j] == 0:
				l.append((i, j))
	return(l)

# Select a random place for the player
def random_place(board, player):
	selection = possibilities(board)
	current_loc = random.choice(selection)
	board[current_loc] = player
	return(board)

# Checks whether the player has three
# of their marks in a horizontal row
def row_win(board, player):
	for x in range(len(board)):
		win = True
		
		for y in range(len(board)):
			if board[x, y] != player:
				win = False
				continue
				
		if win == True:
			return(win)
	return(win)

# Checks whether the player has three
# of their marks in a vertical row
def col_win(board, player):
	for x in range(len(board)):
		win = True
		
		for y in range(len(board)):
			if board[y][x] != player:
				win = False
				continue
				
		if win == True:
			return(win)
	return(win)

# Checks whether the player has three
# of their marks in a diagonal row
def diag_win(board, player):
	win = True
	y = 0
	for x in range(len(board)):
		if board[x, x] != player:
			win = False
	if win:
		return win
	win = True
	if win:
		for x in range(len(board)):
			y = len(board) - 1 - x
			if board[x, y] != player:
				win = False
	return win

# Evaluates whether there is
# a winner or a tie
def evaluate(board):
	winner = 0
	
	for player in [1, 2]:
		if (row_win(board, player) or
			col_win(board,player) or
			diag_win(board,player)):
				
			winner = player
			
	if np.all(board != 0) and winner == 0:
		winner = -1
	return winner

# Main function to start the game
def play_game():
	board, winner, counter = create_board(), 0, 1
	print(board)
	sleep(2)
	
	while winner == 0:
		for player in [1, 2]:
			board = random_place(board, player)
			print("Board after " + str(counter) + " move")
			print(board)
			sleep(2)
			counter += 1
			winner = evaluate(board)
			if winner != 0:
				break
	return(winner)

# Driver Code
print("Winner is: " + str(play_game()))

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}
>