tictactoe.py

Created by 4223

Created on March 17, 2026

2.01 KB

leuk


from kandinsky import fill_rect, draw_string
from ion import *
from time import sleep

# grid (3x3)
grid = [["","",""],
        ["","",""],
        ["","",""]]

cursor_x = 0
cursor_y = 0
player = "X"

def draw():
    fill_rect(0,0,320,222,(0,0,0))
    
    # grid lijnen
    for i in range(1,3):
        fill_rect(i*60, 40, 2, 180, (255,255,255))
        fill_rect(0, 40+i*60, 180, 2, (255,255,255))
    
    # symbolen
    for y in range(3):
        for x in range(3):
            draw_string(grid[y][x], x*60+25, y*60+60)
    
    # cursor
    fill_rect(cursor_x*60, cursor_y*60+40, 60, 60, (50,50,50))
    
    # tekst
    draw_string("Player: "+player, 200, 20)

def check_win():
    # rijen
    for row in grid:
        if row[0] == row[1] == row[2] != "":
            return row[0]
    
    # kolommen
    for i in range(3):
        if grid[0][i] == grid[1][i] == grid[2][i] != "":
            return grid[0][i]
    
    # diagonaal
    if grid[0][0] == grid[1][1] == grid[2][2] != "":
        return grid[0][0]
    if grid[0][2] == grid[1][1] == grid[2][0] != "":
        return grid[0][2]
    
    return None

def game_over(text):
    fill_rect(0,0,320,222,(0,0,0))
    draw_string(text, 100, 100)
    draw_string("OK = restart", 80, 130)
    
    while not keydown(KEY_OK):
        pass

while True:
    
    # beweging cursor
    if keydown(KEY_UP):
        cursor_y = max(0, cursor_y-1)
        sleep(0.15)
    if keydown(KEY_DOWN):
        cursor_y = min(2, cursor_y+1)
        sleep(0.15)
    if keydown(KEY_LEFT):
        cursor_x = max(0, cursor_x-1)
        sleep(0.15)
    if keydown(KEY_RIGHT):
        cursor_x = min(2, cursor_x+1)
        sleep(0.15)
    
    # plaatsen
    if keydown(KEY_OK):
        if grid[cursor_y][cursor_x] == "":
            grid[cursor_y][cursor_x] = player
            player = "O" if player == "X" else "X"
        sleep(0.2)
    
    winnaar = check_win()
    
    if winnaar:
        game_over(winnaar + " WINS!")
        grid = [["","",""],["","",""],["","",""]]
    
    draw()
    sleep(0.05)

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.