Share your repls and programming experiences

← Back to all posts
tic tac toe
Boopydoop (164)

its literally just tic tac toe that i worked on for a bit.

Comments
hotnewtop
paulramnora (7)

*** This code downloaded from...

https://repl.it/talk/share/tic-tac-toe/8982

MY TEST...

PROGRAMMING LANGUAGE: Python 3.7.1

PYTHON IDE: IDLE

COMPUTER/OS: Home based PC/WINDOWS 10 PRO

CREATED: 011218 14:57 PM GMT

UPDATED: 011218 16:57 PM GMT

***

*** import libraries...

***

import random # allows the use of random numbers (eg. random.randint(0,9))
import time # allows the use of time (eg. time.sleep(.5)/half a second)

*** First, display an introductory message to user...

print('welcome to tic-tac-toe')
print('you are X')

****

*** Variable declarations...

****

TurnNum = 1 # count up the total number of turns both players have made

        # as the game has only just started; therefore, this is players turn number: 1 

Win = False # decides if the game has already been won(True)/or, not(False)?

        # the game has not been won, yet; so, the Win flag remains False  

list array type data structure;

used to display each board number value going from: 1-9;

user can type in a single number;

then, press [ENTER] key, in order to make their move...

Tac = ['1','2','3','4','5','6','7','8','9']

(?) type data structure,

used to check if the game has already been won...

NOTE: There are 8 possible ways to win, including

straight across: (3)/(0,1,2)-(3,4,5)-(6,7,8)

straight downwards: (3)/(0,3,6)-(1,4,7)-(2,5,8)

straight diagonally: (2)/(0,4,8)-(2,4,6)

WinCombos = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6))

**

*** Sub-routine...

**

NOTE: If the following sub-routine returns: True,

then, this means the game is done: either won/or else, drawn;

otherwise, the sub-routine returns: False,

meaning the game still continues...

def CheckTac():
count = 0
for a in WinCombos:

check if X has won...

if Tac[a[0]] == Tac[a[1]] == Tac[a[2]] == "X":
print("Player 1 Wins!")
print("Congrats!")
return True

 # check if Y has won... 
 if Tac[a[0]] == Tac[a[1]] == Tac[a[2]] == "Y":
   print("Ai Wins!")
   return True
   # check the total number of moves both players have made...
   for a in range(9):
     if Tac[a] == "X" or Tac[a] == "Y":
      count += 1
      # if the number of player turns so far counts up to 9; then, the game is over;
      # no single player has actually won/and, therefore, the game is a tie
      if count == 9:
        print("Tie")
        return True

***

*** Main program...

***

while True:

time.sleep(.5) # pause, half-a-sec

#list of spaces

print game board as numbers: 1-9/

arranged into 3 separate horizontal rows...

print(f''' {Tac[0]} {Tac[1]} {Tac[2]}
{Tac[3]} {Tac[4]} {Tac[5]}
{Tac[6]} {Tac[7]} {Tac[8]}''')

time.sleep(.5) # pause, half-a-sec

#get first space
while True: # create an endless loop...
try:

  # instruct user to type in a number...in order to make a board move...  
  UserSpace = int(input(f'{TurnNum}> Please, type in a single digit number: 1-9;\n   then, press [ENTER] key to confirm: '))
except ValueError: # if the user doesn't type a number; then,...
  print('no')      # display an error message saying: no; and,
  continue         # continue endless  loop to find a valid move

                   # possibly, a valid move has been made... 
UserSpace -= 1     # decrement UserSpace by -1
TurnNum += 1       # increment the number of turns so far by +1
#print(UserSpace)
# invalid move, as space is already occupied with either a 'Y'/'X'...
if Tac[UserSpace] == 'X' or Tac[UserSpace] == 'Y': 
  TurnNum -= 1     # decrement number of turns by -1
  continue         # continue endless loop to find a valid move 
else:
 Tac[UserSpace] = 'X' # yes, valid move made; now,
 break                # break out from endless loop

while True: # create an endless loop...

AiSpace = random.randint(0,9) # select a random number space for Y to move
AiSpace -= 1
# if board space is already taken by either an 'X'/or, 'Y'; then,
# search for a next random number space which is still empty
if Tac[AiSpace] == 'X' or Tac[AiSpace] == 'Y':
  #print('debug',AiSpace,Tac,UserSpace,TurnNum)
  continue
else:                # when an empty number board space is found
  Tac[AiSpace] = 'Y' # place the 'Y' marker into it 
  break              # break out from endless loop

#print('debug',AiSpace,Tac,UserSpace,TurnNum)
Win = CheckTac() # make sub-routine call to check if game is already won
CheckTac() # ...not sure why CheckTac() is being called, twice?
if Win == True: # if the game is already done; then,...
TurnNum = 1 # reset number of game players turns to become, 1
Tac = ['1','2','3','4','5','6','7','8','9'] # reset board to numbers: 1-9
Cont = input('Continue? y or n') # ask if user wishes to restart game?
if Cont == 'y': # if the response is 'y'es; then,...
print('welcome back') # print welcome back message
continue # continue running endless loop
else: # otherwise,...
print('goodbye') # print a goodbye message
exit() # exit from endless loop/meaning, game finishes

 #*** NOTE: I still don't fully understand all of this Python code, yet?!
 #          However, I've not given up; still working away on getting there...
 #          This simple form of AI doesn't seem to by playing the game very intelligently;
 #          but, instead, it just seems to move quite randomly anywhere...; which makes it really easy to defeat. 
 #          Possibly, in order to learn/understand more, I will try adding on 'intelligence' in the form of...
 #          1. Go for 'a winning line'/(as opposed to just randomly selecting to move anywhere)
 #          2. otherwise, aim to 'block', first; before making a next move   

'''

Boopydoop (164)

@paulramnora wow that's extremely well made if you want to post this any where I'm perfectly fine with that.

paulramnora (7)

@Boopydoop Your code is both very neat and compact; in many ways, I much prefer it to my own version; the only reason why I decided to add multiple comments was in order to try and understand it a bit more. Naturally, you were/are the 'original' creator; so, I don't deserve any credit at all; and, of course, the very first thing I did was to include a link at the very top so that people can understand it's all 'your' code; not mine. Well done; you did a really fine job! Before I encountered seeing this program, I really didn't realise that it's possible to make AI games using Python so very quickly and easily. Normally, all I ever practised using Python was merely short bits and pieces of the language such as print() statement stating 'Hello, world!' I seldom tried writing/designing whole programs; so, it 'inspires' me to try doing something different, in future.

I think, in order to write programs well using any language; you need to be well versed in understanding the language words/commands...which comes through doing much practice; then, eventually, you find you are no longer an 'outsider' to that language' anymore; when you understand the language as an 'insider'...then, the language has already become a part of you...meaning you do actually 'think' in that same language; and, thus, you are able to translate any real life problems you encounter into that particular programming language code. Myself, I'm still very much a Python newbie 'outsider'...so this language doesn't come naturally to me at all; instead, I have to 'force' myself to both learn/use it; so, I got a hell of a lot more practising to do before I can ever claim to be, well and truly, familiar. My own programming background is: BASIC-Beginner's All-Purpose Symbolic Instruction Code, btw.; which is going all the way back to the early 1980's. In own my day, there were no computers in school/and, mobile phones were not even invented, yet!

The very first programming language they taught us in school -1970's- was something called: CESIL-Computer Education in School Instructional Language. I recall it was basically 'machine code' based; instructions like JIZERO-JUMP IF ZERO/JINEG-JUMP IF NOT EQUAL/-etc. We didn't actually see any computer at all; -apart from maybe glimpsing a photo of a computer machine inside of an instruction book-. The teacher would hand out to the students cardboard 'punch cards'...which we in turn would write up/code using pencil. At the end of the class, the teacher would collect all of our 'punch cards' together; and, take these off to go feed into a computer we never ever saw; then, next week, the teacher would return back to class, and, hand out our program results having been printed out onto reams of tear off 'light green' computing paper sheets. So, now-a-days, people don't even realise just how lucky they are to write/run/see the results of their computer program, instantly, right away...! ;-)

paulramnora (7)

Nice! ;-) As a 'beginner' there is much for me to go learn here; and, I do truly appreciate seeing that your code is neither too short/long; nor does it appear to be overly complex for me to be able to read/understand. -Thanks!

Boopydoop (164)

@paulramnora thanks I'm glad this helped you I am not an expert though so I would recommend find some actual tutorials on replit and other places on the internet.- your welcome.

paulramnora (7)

@Boopydoop Your reply is much appreciated. i learned an awful lot from you, today. Thanks, again! ;-)

Still studying other Python code you wrote(was looking at your Turtle one). Will heed your advice, though; and, try learning from the 'experts'.

It can sometimes be argued that the best teachers of 'beginners'...is, in fact, beginners themselves...as their code is not over-complex to get to grips with understanding.

However, as one's skill and understanding improves; then, of course, it would be time to consider learning from far more advanced people, instead(intermediate/expert).

Boopydoop (164)

@paulramnora I'm glad that I helped you today and I also have definitely learned something from your insights I hope you have a great day.

ZaylieRasmussen (2)

I am MASTER TIC TAC TOE