Welcome, guest | Sign In | My Account | Store | Cart

A web-based Tic Tac Toe game in Python.

Python, 432 lines
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
#!/usr/bin/env python
#################################################################
##
##	Script:		pyttt.py
##	Author:		Premshree Pillai
##	Description:	Tic-Tac-Toe game in Python
##	Web:		http://www.qiksearch.com/
##			http://premshree.resource-locator.com/
##	Created:	19/03/04 (dd/mm/yy)
##
##	(C) 2004 Premshree Pillai
##
#################################################################

import cgi

print "Content-type: text/html\n\n"

global bsize,playerToken,myToken,gameOver,winArr,rowArr,colArr,digArr,vals,s1,s2,s3,s4,s5,s6,s7,s8,s9

bsize = 3
playerToken = "X"
myToken = "0"
gameOver = 0
winArr = []
rowArr = []
colArr = []
digArr = []

x = 0
while x < bsize * bsize :
	rowArr.append(0)
	colArr.append(0)
	digArr.append(0)
	x = x + 1

out1 = """<html>
<head>
<title>Tic Tac Toe in Python</title>
<style type="text/css">
.main{border:#9999CC solid 2px; width:350px}
.btn{font-family:comic sans ms,verdana,arial,helvetica; font-size:20pt; font-weight:bold; background:#9999CC; width:50px; height:50px; border:#666699 solid 1px; cursor:hand; color:#EFEFFF}
.btn_over{font-family:comic sans ms,verdana,arial,helvetica; font-size:20pt; font-weight:bold; background:#EFEFFF; width:50px; height:50px; border:#666699 solid 1px; cursor:hand; color:#9999CC}
.btn_down{font-family:comic sans ms,verdana,arial,helvetica; font-size:20pt; font-weight:bold; background:#666699; width:50px; height:50px; border:#666699 solid 1px; cursor:hand; color:#EFEFFF}
.footer{font-family:verdana,arial,helvetica; font-size:8pt; color:#FFFFFF}
.link{font-family:verdana,arial,helvetica; font-size:8pt; color:#FFFFFF}
.link:hover{font-family:verdana,arial,helvetica; font-size:8pt; color:#EFEFFF}
</style>
<script language="JavaScript">
var doneFlag=false;
function toggleVal(who) {
	var check;
	eval('check=document.ttt.'+who+'_btn.value;');
	if(check==" ") {
		if(!doneFlag) {
			eval('document.ttt.'+who+'_btn.value="X";');
			eval('document.ttt.'+who+'_btn.disabled="true";');
			eval('document.ttt.'+who+'.value="X";');
			document.ttt.submit();
			doneFlag=true;
			document.getElementById('process').innerHTML="Processing.........";
		}
	}
	else {
		alert('Invalid Move!');
	}
}
</script>
</head>
<body>
<table width="100%" height="100%"><tr><td align="center">
<table width="346" align="center" bgcolor="#9999CC" cellspacing="0" cellpadding="0"><tr><td></td></tr></table>
<table width="348" align="center" bgcolor="#9999CC" cellspacing="0" cellpadding="0"><tr><td></td></tr></table>
<table align="center" cellspacing="0" cellpadding="0" class="main"><tr><td align="center">
<table width="100%" bgcolor="#9999CC" cellspacing="0" cellpadding="0"><tr><td align="center"><a href="pyttt.py"><img src="../ttt_py.gif" border="0" alt="Tic Tac Toe (in Python)"></a></td></tr></table>
<table width="100%" bgcolor="#EFEFFF" cellspacing="0" cellpadding="0"><tr><td align="center"><a href="http://www.qiksearch.com"><img src="../qiksearch_ttt_py.gif" border="0" alt="www.qiksearch.com"></a></td></tr></table>"""

print out1

def genBox(size):
	global bsize,playerToken,myToken,gameOver,winArr,rowArr,colArr,digArr,vals,s1,s2,s3,s4,s5,s6,s7,s8,s9
	count = 0
	retVal = '<form name="ttt" method="post" action="pyttt.py">'
	i = 0
	while i < size :
		j = 0
		while j < size :
			count = count + 1
			retVal = retVal + '<input type="button" name="s' + str(count) + '_btn" value=" " class="btn" onClick="toggleVal(\'s' + str(count) + '\')" onMouseover="this.className=\'btn_over\'" onMouseout="this.className=\'btn\'" onMousedown="this.className=\'btn_down\'"><input type="hidden" name="s' + str(count) + '" value=" ">'
			j = j + 1
		retVal = retVal + '<br>'
		i = i + 1
	retVal = retVal + '</form>'
	print retVal

def genBox2(size,arr):
	global bsize,playerToken,myToken,gameOver,winArr,rowArr,colArr,digArr,vals,s1,s2,s3,s4,s5,s6,s7,s8,s9
	count = 0
	retVal = '<form name="ttt" method="post" action="pyttt.py">'
	i = 0
	while i < size :
		j = 0
		while j < size :
			count = count + 1
			retVal = retVal + '<input type="button" name="s' + str(count) + '_btn" value="' + str(arr[count-1]) + '" class="btn" onClick="toggleVal(\'s' + str(count) + '\')" onMouseover="this.className=\'btn_over\'" onMouseout="this.className=\'btn\'" onMousedown="this.className=\'btn_down\'"><input type="hidden" name="s' + str(count) + '" value="' + str(arr[count-1]) + '">'
			j = j + 1
		retVal = retVal + '<br>'
		i = i + 1
	retVal = retVal + '</form>'
	print retVal

def isEmpty(who):
	if who == " ":
		return 1
	else:
		return 0;


def move(bsize,arr):
	global playerToken,myToken,gameOver,winArr,rowArr,colArr,digArr,vals,s1,s2,s3,s4,s5,s6,s7,s8,s9

	count = 0
	maxCount = 0
	pos = 0
	retVal = 0
	
	# Build Row Array
	i = 0
	while i < bsize :
		maxCount = 0
		fullCounter = 0
		j = 0
		while j < bsize :
			count = count + 1
			who = arr[count-1]
			if who == playerToken :
				maxCount = maxCount + 1
				fullCounter = fullCounter + 1
			if who == myToken :
				fullCounter = fullCounter + 1
			j = j + 1
		rowArr[i] = maxCount
		if fullCounter == bsize :
			rowArr[i] = -1
		i = i + 1

	# Building Column Array
	i = 0
	while i < bsize :
		count = i + 1
		maxCount = 0
		fullCounter = 0
		j = 0
		while j < bsize :
			who = arr[count-1]
			if who == playerToken :
				maxCount = maxCount + 1
				fullCounter = fullCounter + 1
			if who == myToken :
				fullCounter = fullCounter + 1
			count = count + bsize
			j = j + 1
		colArr[i] = maxCount
		if fullCounter == bsize :
			colArr[i] = -1
		i = i + 1

	# Building Diagonal Array
	i = 0
	while i < 2 :
		if i  == 0 :
			count = i + 1
		else:
			count = bsize
		maxCount = 0
		fullCounter = 0
		j = 0
		while j < bsize :
			who = arr[count-1]
			if who == playerToken :
				maxCount = maxCount + 1
				fullCounter = fullCounter + 1
			if who == myToken :
				fullCounter = fullCounter + 1
			if i == 0 :
				count = count + bsize + 1
			else:
				count = count + bsize - 1
			j = j + 1
		digArr[i] = maxCount
		if fullCounter == bsize :
			digArr[i] = -1
		i = i + 1

	# Finding Max Values
	maxRow = myMax(0,bsize,"row",rowArr)
	maxCol = myMax(0,bsize,"col",colArr)
	maxDig = myMax(0,bsize,"dig",digArr)
	
	maxArrs = []
	maxArrs.append(myMax(1,bsize,"row",rowArr))
	maxArrs.append(myMax(1,bsize,"col",colArr))
	maxArrs.append(myMax(1,bsize,"dig",digArr))

	if myMax(0,bsize,"x",maxArrs) == 0 :
		pos = bsize * (maxRow + 1) - bsize
	if myMax(0,bsize,"x",maxArrs) == 1 :
		pos = maxCol
	if myMax(0,bsize,"x",maxArrs) == 2 :
		if maxDig == 0 :
			pos = maxDig
		else:
			pos = bsize - 1

	retFlag = 0
	y = 0
	while y < bsize :
		if not(retFlag):
			if arr[pos] == " " :
				retVal = pos
				retFlag = 1
			if myMax(0,bsize,"x",maxArrs) == 0 :
				pos = pos + 1
			if myMax(0,bsize,"x",maxArrs) == 1 :
				pos = pos + bsize
			if myMax(0,bsize,"x",maxArrs) == 2 :
				if maxDig == 0 :
					pos = pos + bsize + 1
				else:
					pos = pos + bsize - 1
		y = y + 1
	return retVal

def myMax(what,bsize,type,arr):
	global playerToken,myToken,gameOver,winArr,rowArr,colArr,digArr,vals,s1,s2,s3,s4,s5,s6,s7,s8,s9

	max = -1
	maxIndex = -1
	if type != "dig" :
		i = 0
		while i < bsize :
			if arr[i] > max :
				max = arr[i]
				maxIndex = i
			i = i + 1
	if type == "dig" :
		i = 0
		while i < 2 :
			if arr[i] > max :
				max = arr[i]
				maxIndex = i
			i = i + 1
	if what == 0 :
		return maxIndex
	else:
		return max

def playerWin():
	global bsize,playerToken,myToken,gameOver,winArr,rowArr,colArr,digArr,vals,s1,s2,s3,s4,s5,s6,s7,s8,s9

	who = playerToken
	if (s1 == who == s2 == s3) or (s4 == who == s5 == s6) or (s7 == who == s8 == s9) or (s1 == who == s4 == s7) or (s2 == who == s5 == s8) or (s3 == who == s6 == s9) or (s1 == who == s5 == s9) or (s3 == who == s5 == s7) :
		return 1
	else:
		return 0

def iWin():
	global bsize,playerToken,myToken,gameOver,winArr,rowArr,colArr,digArr,vals,s1,s2,s3,s4,s5,s6,s7,s8,s9

	who = myToken
	if (s1 == who == s2 == s3) or (s4 == who == s5 == s6) or (s7 == who == s8 == s9) or (s1 == who == s4 == s7) or (s2 == who == s5 == s8) or (s3 == who == s6 == s9) or (s1 == who == s5 == s9) or (s3 == who == s5 == s7) :
		return 1
	else:
		return 0

def whereWinComp():
	global bsize,playerToken,myToken,gameOver,winArr,rowArr,colArr,digArr,vals,s1,s2,s3,s4,s5,s6,s7,s8,s9

	who = myToken
	if (s1 == who == s2 == s3) :
		winArr = ['s1','s2','s3']
	if (s4 == who == s5 == s6) :
		winArr = ['s4','s5','s6']
	if (s7 == who == s8 == s9) :
		winArr = ['s7','s8','s9']
	if (s1 == who == s4 == s7) :
		winArr = ['s1','s4','s7']
	if (s2 == who == s5 == s8) :
		winArr = ['s2','s5','s8']
	if (s3 == who == s6 == s9) :
		winArr = ['s3','s6','s9']
	if (s1 == who == s5 == s9) :
		winArr = ['s1','s5','s9']
	if (s3 == who == s5 == s7) :
		winArr = ['s3','s5','s7']

def whereWinPlayer():
	global bsize,playerToken,myToken,gameOver,winArr,rowArr,colArr,digArr,vals,s1,s2,s3,s4,s5,s6,s7,s8,s9

	who = playerToken
	if (s1 == who == s2 == s3) :
		winArr = ['s1','s2','s3']
	if (s4 == who == s5 == s6) :
		winArr = ['s4','s5','s6']
	if (s7 == who == s8 == s9) :
		winArr = ['s7','s8','s9']
	if (s1 == who == s4 == s7) :
		winArr = ['s1','s4','s7']
	if (s2 == who == s5 == s8) :
		winArr = ['s2','s5','s8']
	if (s3 == who == s6 == s9) :
		winArr = ['s3','s6','s9']
	if (s1 == who == s5 == s9) :
		winArr = ['s1','s5','s9']
	if (s3 == who == s5 == s7) :
		winArr = ['s3','s5','s7']

def draw():
	global bsize,playerToken,myToken,gameOver,winArr,rowArr,colArr,digArr,vals,s1,s2,s3,s4,s5,s6,s7,s8,s9

	drawCounter = 0
	dCounter = 0
	while dCounter < len(vals) :
		if vals[dCounter] != " " :
			drawCounter = drawCounter + 1
		dCounter = dCounter + 1
	if drawCounter == bsize * bsize :
		return 1
	else:
		return 0

form = cgi.FieldStorage()
if form :
	s1 = form['s1'].value
	s2 = form['s2'].value
	s3 = form['s3'].value
	s4 = form['s4'].value
	s5 = form['s5'].value
	s6 = form['s6'].value
	s7 = form['s7'].value
	s8 = form['s8'].value
	s9 = form['s9'].value
	vals = [s1,s2,s3,s4,s5,s6,s7,s8,s9]

	if draw() or playerWin() :
		gameOver = 1

	# Computer's Move!
	movIndex = move(bsize,vals)
	if not(gameOver) :
		vals[movIndex] = myToken

	# Update S's
	if not(gameOver) :
		if movIndex == 0 :
			s1 = myToken
		if movIndex == 1 :
			s2 = myToken
		if movIndex == 2 :
			s3 = myToken
		if movIndex == 3 :
			s4 = myToken
		if movIndex == 4 :
			s5 = myToken
		if movIndex == 5 :
			s6 = myToken
		if movIndex == 6 :
			s7 = myToken
		if movIndex == 7 :
			s8 = myToken
		if movIndex == 8 :
			s9 = myToken
	genBox2(bsize,vals)

	if playerWin() :
		print '<font face="verdana,arial,helvetica" color="#009900" size="4"><b>Wow! You Won!</b></font><br><br>'
		print '<input type="button" onClick="location.href=\'pyttt.py\'" value="Play Again!" style="background:#CCCCCC; font-weight:bold; cursor:hand"><br><br>'
		whereWinPlayer()
		print '<script language="JavaScript">'
		winCount = 0
		while winCount < len(winArr) :
			print 'document.ttt.' + winArr[winCount] + '_btn.style.color=\'#009900\';'
			winCount = winCount + 1
		w = 0
		while w < (bsize * bsize) :
			if vals[w] == " " :
				print 'document.ttt.s' + str(w + 1) + '_btn.disabled=true;'
			w = w + 1
		print '</script>'
		gameOver = 1

	if iWin() and not(gameOver) :
		print '<font face="verdana,arial,helvetica" color="#FF0000" size="4"><b>Oops! You Lost!</b></font><br><br>'
		print '<input type="button" onClick="location.href=\'pyttt.py\'" value="Play Again!" style="background:#CCCCCC; font-weight:bold; cursor:hand"><br><br>'
		whereWinComp()
		print '<script language="JavaScript">'
		winCount = 0
		while winCount < len(winArr) :
			print 'document.ttt.' + winArr[winCount] + '_btn.style.color=\'#FF0000\';';
			winCount = winCount + 1
		w = 0
		while w < bsize * bsize :
			if vals[w] == " " :
				print 'document.ttt.s' + str(w + 1) + '_btn.disabled=true;'
			w = w + 1
		print '</script>'
		gameOver = 1

	if draw() and not(playerWin()) and not(iWin()) :
		print '<font face="verdana,arial,helvetica" color="#000000" size="4"><b>It\'s a Draw!</b></font><br><br>'
		print '<input type="button" onClick="location.href=\'pyttt.py\'" value="Play Again!" style="background:#CCCCCC; font-weight:bold; cursor:hand"><br><br>'
		print '<script language="JavaScript">'
		w = 0
		while w < bsize * bsize :
			if vals[w] == " " :
				print 'document.ttt.s' + str(w + 1) + '_btn.disabled=true;'
			w = w + 1
		print '</script>'
else:
	genBox(bsize)

out2 = """<div style="font-family:verdana,arial,helvetica; font-weight:bold; font-size:10pt; color:#CC0000; background:#EFEFFF; width:100%; padding:3px" id="process"></div>

<table width="100%" bgcolor="#9999CC"><tr><td><span class="footer">&#169; 2004 <a href="http://www.qiksearch.com" class="link">Premshree Pillai</a> | <a href="http://www.guestbookdepot.com/cgi-bin/guestbook.cgi?book_id=374186" class="link">Sign my Guestbook</a>.</span></td></tr></table>
</td></tr></table>
<table width="348" align="center" bgcolor="#9999CC" cellspacing="0" cellpadding="0"><tr><td></td></tr></table>
<table width="346" align="center" bgcolor="#9999CC" cellspacing="0" cellpadding="0"><tr><td></td></tr></table>
</td></tr></table>
</body>
</html>"""

print out2

This is a simple web-based Tic Tac Toe game in Python. See the game in action at http://balajin.net/cgi-bin/pyttt.py

4 comments

Gregor Rayman 20 years ago  # | flag

Have a look at 5-tic-tac-toe. http://www.i-technology.de/fivewins_en.htm

It is not in Python but in JavaScript. The source is provided, perhaps you'd like to convert it to Python?

Hmm...I had written a JavaScript version with support for multiple board sizes long ago - http://www.premshree.resource-locator.com/javascripts/tic-tac-toe/

Gregor Rayman 20 years ago  # | flag

Slightly different game. In tic-tac-toe, the board size is the same as the winning length of the line (3). In the Get5 (Gomoku) the board size is 19x19 and the winning length is 5

dode william 19 years, 12 months ago  # | flag

gomuku with 5 stones. I made a gomoku game in python, that work in ascii or with pygame. 5 stones to align. Sources are free. http://flibuste.net/libre/morpyon

Created by Premshree Pillai on Thu, 18 Mar 2004 (PSF)
Python recipes (4591)
Premshree Pillai's recipes (11)

Required Modules

Other Information and Tasks