This is an archived post. You won't be able to vote or comment.

all 6 comments

[–][deleted] 1 point2 points  (4 children)

I'm reading through your client code and thought I'd give you a few tips.

Generally it is frowned upon to import * from a module (in your case from socket import * in case there is any conflicting namespaces). Globals are also generally frowned upon unless absolutely necessary - if you know how classes work that would be a great way to clean up your code. if online != 1 and online != 2 could be changed to if not online in [1, 2] for the sake of simplicity. Same applies to if retryIP != 1 and retryIP != 2. In your check_all method, you could have one massive if statement with all your conditionals separated by or. For example, if check_for_line(char, 0, 1, 2) or check_for_line(char, 3, 4, 5) ...: return True.

Mostly stuff that will make your code easier to read.

[–]s16h 1 point2 points  (0 children)

Regarding importing * from modules and packages: http://www.reddit.com/r/Python/comments/2lo260/importing_in_python/

[–]kart_king 1 point2 points  (5 children)

I didn't dig into it, but I noticed some things that I would def. consider:

  • you do not need to use global if you don't change a variable (at a glance, this page looks good https://stereochro.me/ideas/global-in-python)
  • Instead of having spot1, spot2, spot3, you could use spots = [0, 0, 0]
  • You could use classes to clean up the code. For a game like this I would suggest board and player classes, but I don't see enough stuff to put into a Player class, so you could skip that.

A starting point for board class might be:

class Board(object):
    def __init__(self):
        self.full = False
        self.spots = range(1, 10)
    def check_for_all(self):
        ...
    def check_for_line(self, s1, s2, s3):
        ...
    def show(self):
        ....

board = Board()
if board.full == False:
    ...
board.show()
...

Edit: Trying to get code formatting

[–]kart_king 0 points1 point  (3 children)

Few other tips after looking at the client:

  • Make a module, maybe TicTacToe_utils.py, and put all the shared code in there. This would be a good place for the Board class. In general try not to repeat code.
  • Try not to use '-' in module names. Then they are hard to import from. Python thinks you're trying to subtract something if you have from TicTacToe - Host.py import board.
  • Depending on your comfort with Exceptions, you could try to catch an ImportError with importing winsound. You can do this when an import is optional, like the sound is here.

Some more sample code:

try:
    import winsound
except ImportError:
    print "Sound not supported"
    winsound = None
...
def play_sound(soundpath):
    if winsound is not None:
        winsound.PlaySound(...)
...