Advertisement
furas

Python - TicTacToe - client

Dec 4th, 2016
365
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.46 KB | None | 0 0
  1. #
  2. # http://stackoverflow.com/questions/40956421/i-am-implementing-a-server-client-based-tictactoe-but-i-am-getting-errors
  3. # http://pastebin.com/dexntYKx
  4. #
  5.  
  6. import socket
  7. import threading
  8. from tkinter import *
  9. import Pmw
  10.  
  11. class TicTacToeClient(Frame, threading.Thread ):
  12.    """Client that plays a game of Tic-Tac-Toe"""
  13.  
  14.    def __init__(self):
  15.       """Create GUI and play game"""
  16.  
  17.       threading.Thread.__init__( self )
  18.  
  19.       # initialize GUI
  20.       Frame.__init__( self )
  21.       Pmw.initialise()
  22.       self.pack( expand = YES, fill = BOTH )
  23.       self.master.title( "Tic-Tac-Toe Client" )
  24.       self.master.geometry( "250x325" )
  25.  
  26.       self.id = Label( self, anchor = W )
  27.       self.id.grid( columnspan = 3, sticky = W+E+N+S )
  28.  
  29.       self.board = []
  30.  
  31.       # create and add all buttons to the board
  32.       for i in range(9):
  33.          newButton = Button( self, font = "Courier 20 bold",
  34.             height = 1, width = 1, relief = GROOVE,
  35.             name = str( i ) )
  36.          newButton.bind( "<Button-1>", self.sendClickedSquare )
  37.          self.board.append( newButton )
  38.  
  39.       current = 0
  40.  
  41.       # display buttons in 3x3 grid beginning with grid's row one
  42.       for i in range( 1, 4 ):
  43.  
  44.          for j in range( 3 ):
  45.             self.board[ current ].grid( row = i, column = j,
  46.                sticky = W+E+N+S )
  47.             current += 1
  48.  
  49.       # area for server messages
  50.       self.display = Pmw.ScrolledText( self, text_height = 10,
  51.          text_width = 35, vscrollmode = "static" )
  52.       self.display.grid( row = 4, columnspan = 3 )
  53.  
  54.       self.start()   # run thread
  55.  
  56.    def run( self ):
  57.       """Control thread to allow continuous updated display"""
  58.  
  59.       # setup connection to server
  60.       HOST = "127.0.0.1"
  61.       PORT = 5000
  62.       self.connection = socket.socket( socket.AF_INET,
  63.          socket.SOCK_STREAM )
  64.       self.connection.connect( ( HOST, PORT ) )
  65.       self.myMark = self.connection.recv( 1 ).decode('ascii')
  66.       self.id.config( text = 'You are player "%s"' % self.myMark )
  67.  
  68.       self.myTurn = 0
  69.  
  70.       # receive messages sent to client
  71.       while 1:
  72.          #message = self.connection.recv( 34 ).decode('ascii')
  73.          length = int(self.connection.recv(2).decode('ascii'))
  74.          message = self.connection.recv(length).decode('ascii')
  75.  
  76.  
  77.          if not message:
  78.             break
  79.  
  80.          self.processMessage( message )
  81.  
  82.       self.connection.close()
  83.       self.display.insert( END, "Game over.\n" )
  84.       self.display.insert( END, "Connection closed.\n" )
  85.       self.display.yview( END )
  86.  
  87.    def processMessage( self, message ):
  88.       """Interpret server message to perform necessary actions"""
  89.  
  90.       # valid move occurred
  91.       if message == "Valid move.":
  92.          self.display.insert( END, "Valid move, please wait.\n" )
  93.          self.display.yview( END )
  94.  
  95.          # set mark
  96.          self.board[ self.currentSquare ].config(
  97.             text = self.myMark, bg = "white" )
  98.  
  99.       # invalid move occurred
  100.       elif message == "Invalid move, try again.":
  101.          self.display.insert( END, message + "\n" )
  102.          self.display.yview( END )
  103.          self.myTurn = 1
  104.  
  105.       # opponent moved
  106.       elif message == "Opponent moved.":
  107.  
  108.          # get move location
  109.          location = int( self.connection.recv( 1 ).decode('ascii') )
  110.  
  111.          # update board
  112.          if self.myMark == "X":
  113.             self.board[ location ].config( text = "O",
  114.                bg = "gray" )
  115.          else:
  116.             self.board[ location ].config( text = "X",
  117.                bg = "gray" )
  118.  
  119.          self.display.insert( END, message + " Your turn.\n" )
  120.          self.display.yview( END )
  121.          self.myTurn = 1
  122.  
  123.       # other player's turn
  124.       elif message == "Other player connected. Your move.":
  125.          self.display.insert( END, message + "\n" )
  126.          self.display.yview( END )
  127.          self.myTurn = 1
  128.  
  129.       # simply display message
  130.       else:
  131.          self.display.insert( END, message + "\n" )
  132.          self.display.yview( END )
  133.  
  134.    def sendClickedSquare( self, event ):
  135.       """Send attempted move to server"""
  136.  
  137.       if self.myTurn:
  138.          name = event.widget.winfo_name()
  139.          self.currentSquare = int( name )
  140.  
  141.          print(name, type(name))
  142.          # send location to server
  143.          self.connection.send( name.encode('ascii') )
  144.          self.myTurn = 0
  145.  
  146. def main():
  147.    TicTacToeClient().mainloop()
  148.  
  149. if __name__ == "__main__":
  150.    main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement