• Advertisement
  • Popular Tags

  • Popular Now

  • Advertisement
  • Similar Content

    • By adambiser
      Hello all,
      I have teamed up with TheGameCreators for them to trial a Python version of AppGameKit in the form of a PYD file that makes AppGameKit commands available to Python 3.6 and greater.  Currently this PYD is compiled only for use with the Windows x86 version of Python.  It is a free, unlimited version of their commercial product, but it does show the AppGameKit logo for a few seconds on game startup and AppGameKit is mentioned in the window title when in windowed mode.  The PYD works with PyInstaller for easy distribution.
      If you haven't heard of AppGameKit, I would recommend looking over their website.  They also have documentation online and an active community forum.  I should point out that method names have been changed to follow PEP 8 naming conventions, so they will be similar but different from the online help.  I also had to make a few changes mentioned on the project's itch.io page.  There is also a PYI file there that can be used with PyCharm for easier access to the same information.
      As mentioned, this is a trial for them, but if there's a positive response they will extend the project and include a way of compiling an executable without the intro logo and window title text as well as support other OS.
      Please take a look and feel free to ask me any questions about it here or on the project's community forum on itch.io.
      AppGameKit for Python project page at itch.io: https://fascimania.itch.io/appgamekit-for-python
      Original announcement url: https://www.thegamecreators.com/post/announcing-appgamekit-for-python
    • By RidiculousName
      I want to make a random map generator in python 3, but I have no idea how to do it. Could someone recommend me a good starting point?
      What I want to make is a flat 2D overworld-map with roads, rivers, settlements, farmlands, forests, and plains.
      I don't want to model specific buildings. This is just for a game I'm making where I'd like the player to be able to travel from point to point.
    • By Hashbrown
      I'm trying to learn how to make my own model, view, projection setup. I've managed to translate, rotate, and scale my models, but have an issue with my perspective projection matrix.
      Even though I'm multiplying halfFOV with my aspect ratio, the image looks squished unless my window is a perfect square like this:

      If it's not a perfect square: the wider my window the more stretched my object looks in the Z axis like an egg.

      So it definitely has to do with with my projection matrix, specifically related to my aspect ratio. The way I'm multiplying my matrices is as follows, I'll show you my translation and projection keep it simple:
      Translation [1, 0, 0, 0, 0, 1 0, 0 0, 0, 1, 0, x, y, z, 1] Projection let halfFOV = Math.tan(toRad(FOV/2.0)); let zRange = (NEAR - FAR); let x = 1.0 / (halfFOV * aspect); let y = 1.0 / (halfFOV); let z = (NEAR + FAR) / zRange; let w = 2 * FAR * NEAR / zRange; [x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, -1, 0, 0, w, 0] I normally see the -1 where the w is, but for some reason I need to set it up the way you see it in my matrix, if not it won't work. I'll also share how I'm multiplying matrices very quickly:
      function (r, a, b) r.mat[0] = (a.mat[0] * b.mat[0]) + (a.mat[1] * b.mat[4]) + (a.mat[2] * b.mat[8]) + (a.mat[3] * b.mat[12]); r.mat[1] = (a.mat[0] * b.mat[1]) + (a.mat[1] * b.mat[5]) + (a.mat[2] * b.mat[9]) + (a.mat[3] * b.mat[13]); r.mat[2] = (a.mat[0] * b.mat[2]) + (a.mat[1] * b.mat[6]) + (a.mat[2] * b.mat[10]) + (a.mat[3] * b.mat[14]); r.mat[3] = (a.mat[0] * b.mat[3]) + (a.mat[1] * b.mat[7]) + (a.mat[2] * b.mat[11]) + (a.mat[3] * b.mat[15]); // don't need to add the rest of it... // How I use it Mathf.mul(resultMat, position, projection); So I take the left row and multiply it against the right column. I then get rows as a result as you can see. If you want to check out the full implementation it's here. I've also checked that I'm getting the correct window size. I divide width/height to get the aspect ratio too. Not sure what I'm doing wrong. I also tried multiplying my matrices on the gpu (glsl) and I gt the same results, so it's definitely my projection matrix
      Hope this all makes sense.
      Edit: I probably should have posted this thread in the Math categories, my apologies.
    • By DotaCard Channel

    • By Hashbrown
      I'm trying to make fixed time-step game loop following this wonderful site, but I suspect I'm not understanding the concept correctly. I'm working with JavaScript and the browser, but I'm sure you'll understand better than I do.
      Here are the steps I'm taking:
      - I'm using the 60fps update loop (requestAnimationFrame) provided by browsers.
      - Using a 30fps step (1.0/30.0) for my fixed update loop.
      - I'm currently getting all the necessary time data at the beginning of the frame:

          function updateFrame () {         now  = window.performance.now();         msDt = now - last;         dt   = msDt / 1000.0;  // ignored         lag += Math.min(1, msDt);         last = now; }
      - I'm also separating the physics (fixed update) and rendering update loops like this:

      // within update frame loop while (lag >= fpsLimit) {     lag -= fpsLimit;     game.fixedUpdate(); } game.update(); game.render();
      If you notice, I increment lag in milliseconds, not seconds (divided by 1000). That way, when I get to the while loop, lag decreases exactly 30 times and then moves down to rendering part. So if I log inside the while loop and after it, I get 30 logs from the while loop and 1 after it. Repeat.

      But if I do it the way the site recommends, which is to increment lag by seconds (divided by 1000), the number is lower, but the while loop only runs once. I'm guessing because I only increment by the fpsLimit (0.033) and it would take only one iteration to escape the while loop.
      I hope I made sense, I'm basically trying to do something similar to Unity. Have a fixed update I know will loop 30 times, and also update every frame. Not sure if I'm understand correctly though. Thanks if your read this far!
  • Advertisement
  • Advertisement

tic-tac-toe review request

Recommended Posts

I was looking for an opportunity to learn/improve skills so I wrote this simple Tic-Tac-Toe game.

I have written Python code for simple network tests and know enough JavaScript to get by. Still not certain on fine details though, particularly what subtle (or not) best practices I am likely missing.

Code review, testing and advice on how to improve would be appreciated.

Code is running on PythonAnywhere here:

Code is here on GIT:

The three pieces are:
JavaScript and Markup: tictactoe_page.html
Bottle Framework Implementation: tictactoe_bottle.py
Python Game Logic: tictactoe_logic.py

If you look closely at the game logic the AI is...primitive. Researching MinMax to improve it is the next thing on list but in my experience if I wait for perfection I never get anything done.

Anyway...how can I improve this game and this code?


Share this post

Link to post
Share on other sites
# Lines with a line number in front refer to your code, everything else is my comment.

     5	        self.gamestate = 0 #0=in play;1=win;2=tie
     8	        self.current_player_turn = 0 #0=player1;1=player2

# Define some names for the game state.

WIN = 1
TIE = 2

PLAYER1 = "player 1"
PLAYER2 = "player 2"

self.gamestate = IN_PLAY
self.current_player_turn = PLAYER1  # Nothing wrong with using strings as value of a constant.

     9	        print 'init'

# In Python 3 this will fail, add parentheses to prepare yourself for the
# transition.


    11	    def validatemove(self, move):

# Add a doc-string describing the function interfaces, eg

    def validatemove(self, move):
        Verify that the move is valid.

        @param move: Move to verify.
        @type  move: C{int}

        @return: Whether the move was valid.
        @rtype:  C{bool}

# There are several different styles of documenting, I used EpyDoc. Note that
# Python 3 will support typed parameters and return values, making the @type and
# @rtype entries mostly obsolete.

# I know this may seem totally useless to you, and for this function I arguably
# agree with you. The point is however, in a year, you don't know what each
# function is doing, nor do you remember the types of the arguments or the
# special edge-cases that apply in calling a function.
# That means you will have to reverse-engineer that information from the code,
# when you open this file again. Reverse engineering information is always
# slower and more error-prone than just reading exactly what you want to know.
# Documentation as such is thus an investment for the future that makes you work
# faster and more accurately tomorrow.

    12	        print 'validating move', move

# Python 3 will want something like

print('validating move {}'.format(move))

    13	        #is the 'move' in range?
    14	        if not self.gamestate == 0:
    15	            print 'game is not in play'
    16	            return False
    17	        if move > 8 or move < 0:
    18	            print 'move is not in range'
    19	            return False
    20	        if move in self.player1_moves | self.player2_moves:
    21	            print 'play already made'
    22	            return False

    23	        print 'move', move, 'evaluated as legal'
    24	        return True

# If you insert empty lines between the different checks, it's easier to see
# the steps you're making.
# The problem you'll have here is that an empty line between functions and an
# empty line between statements looks very similar. This is also where function
# documentation helps. It adds a big different looking piece of text with each
# function, making it easier to see where a function starts in the code.

    26	    def getgamestate(self):
    27	        if self.gamestate == 0:
    28	            return "in play"
    29	        elif self.gamestate == 1:
    30	            return "win"
    31	        else:
    32	            return "tie"

# I tend to be more paranoid, and pretty much always check for completeness, ie

if self.gamestate == 0:
    return "in play"
elif self.gamestate == 1:
    return "win"
    assert self.gamestate == 2
    return "tie"

# It's surprising how often these checks trigger, because you forgot some case somewhere.
# A simpler way to do the above is
    0: 'in play',
    1: 'win',
    2: 'tie',

def getgamestate(self):
    Get a human-readable description of the game state.

    @return: Description of the current state of the game.
    @rtype:  C{str}
    return GAMESTATE_DESCRIPTIONS[self.gamestate]

# I just document all functions to avoid the problem of deciding what is
# trivial enough not to document, ymmv.

    34	    def getcurrentplayerturn(self):
    35	        if self.current_player_turn == 0:
    36	            return "player 1"
    37	        elif self.current_player_turn == 1:
    38	            return "player 2"

# With the string constants, this would be just

def getcurrentplayerturn(self):
    Get the name of the current player.

    @return: Name of the current player.
    @rtype:  C{str}
    return self.current_player_turn

# And yes, it's normal that the documentation is longer than the code in
# Python, the language is very efficient in number of lines needed to express
# something.

    55	    def evaluateWinState(self,movesetToEval):
    56	        #012
    57	        #345
    58	        #678
    59	        winStateList = [{0,1,2},{3,4,5},{6,7,8},{0,3,6},{1,4,7},{2,5,8},{0,4,8},{2,4,6}]

winStateList = [
        {0, 1, 2}, {3, 4, 5}, {6, 7, 8}, # Horizontal
        {0, 3, 6}, {1, 4, 7}, {2, 5, 8}, # Vertical
        {0, 4, 8}, # Main diagonal
        {2, 4, 6}, # Other diagonal
# Exploit the multi-line capabilities of Python to make it easier to understand
# what the data contains. The comments also point you directly to what the entries mean,
# while in your version you have to actually parse the entries to find the
# right one.
# Addedsomemorewhitespacetomakeiteasiertoread (here it's quite ok, but if you
# use floating point numbers, 0.0,0.0 versus 0,0,0,0 becomes hard to read. The
# comma behind the last entry makes it simpler to extend the list at a later
# time, though this list will never get extended, most likely.

    85	            else:
    86	                raise AssertionError("unexpected ui state")

    87	        #ai's second turn (human has made two moves)
    88	        elif player1move_count == 2:

# I would also insert empty lines between the various elif clauses, as I
# consider them separate cases.


Share this post

Link to post
Share on other sites
19 hours ago, Aerodactyl55 said:

You say the AI is primitive but it is impossible to beat. Is that intentional? Maybe you can add a small chance for the AI to make a mistake, as an 'improvement'.

The goal was to make it extremely difficult. I said primitive because the algorithm I used (if you can call it that) is very simple. Seems to work quite effectively though. Go figure. I'll see I can add an "easy" setting.

Thanks for the code review Alberth! Will make the changes as I have time and push to GIT.

Share this post

Link to post
Share on other sites

You know that tic-tac-toe is a solved problem, where the optimal strategy has been published?




To make it easier, draw a random number whether to play according to your strategy, or do a random move. By varying the treshold you can make it more random or more optimal.

Note that random moves may still be optimal, except it doesn't happen very often :P


Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Advertisement