| HomeTurtlegraficsGPanelRoboticsGameGrid WebTigerPython |
| Python - Online |
| Deutsch English |
![]()
GAME DESCRIPTION |
To ensure that the mark changes after each click, introduce a variable player that switches between the values 1 and 2. In the main programme, first assign the value 1 to the player. To be able to change the value of the variable in the callback function, you must designate it as global (global player). In the simplest version of the game, the players take turns placing their marks and check the result themselves. Program: #TicTacToe.py from gamegrid import * def onMousePressed(e): global player loc = toLocationInGrid(e.getX(), e.getY()) if getOneActorAt(loc) != None: return mark = Actor("sprites/mark.gif", 2) addActor(mark, loc) if player == 1: mark.show(0) player = 2 elif player == 2: mark.show(1) player = 1 makeGameGrid(3, 3, 70, Color.black, False, mousePressed = onMousePressed) setBgColor(makeColor("yellow")) show() doRun() player = 1 |
ADDITIONAL MATERIAL |
The game situation can be checked after each move using the following trick: The horizontal, vertical and diagonal positions on the game board are represented in a comma-separated string pattern of the form XOX,XX- ,O-O, ... (empty cells are represented by the character “-”). If XXX or OOO appear in this string, one player has won. Program: #TicTacToe2.py from gamegrid import * def onMousePressed(e): global player loc = toLocationInGrid(e.getX(), e.getY()) if getOneActorAt(loc) != None: return mark = Actor("sprites/mark.gif", 2) addActor(mark, loc) if player == 1: mark.show(0) player = 2 elif player == 2: mark.show(1) player = 1 checkGameState() refresh() def setPattern(x, y): global pattern location = Location(x, y) a = getOneActorAt(location) if a == None: pattern += '-' elif a.getIdVisible() == 0: pattern += 'O' elif a.getIdVisible() == 1: pattern += 'X' def checkGameState(): # Convert board state into string pattern global pattern pattern = "" # Horizontal for y in range(3): for x in range(3): setPattern(x, y) pattern += ',' # Separator # Vertical for x in range(3): for y in range(3): setPattern(x, y) pattern += ',' # Diagonal for x in range(3): setPattern(x, x); pattern += ',' for x in range(3): setPattern(x, 2 - x); if "XXX" in pattern: setTitle("X won") elif "OOO" in pattern: setTitle("O won") elif not "-" in pattern: setTitle("Board full") makeGameGrid(3, 3, 70, Color.black, False, mousePressed = onMousePressed) setBgColor(makeColor("yellow")) player = 1 show() doRun() |
![]()