puissance4.py

Created by schraf

Created on March 28, 2021

1.48 KB

Explications en vidéo

BTS = [42,43,44,36,37,38,30] correspond aux codes des touches de 1 à 7 sur la machine.


from kandinsky import *
from ion import *
from time import sleep

BL,RO,GR,NR,WH = (0,0,255), (255,0,0), (200,)*3, (0,)*3, (250,)*3
BTS = [42,43,44,36,37,38,30]
plateau = [[0] * 7 for i in range(6)]

def grille():
  for i in range(8):
    fill_rect(55 + 30 * i, 25, 1, 180, GR)
    if i < 7: 
      fill_rect(55, 25 + 30 * i, 210, 1, GR)
      draw_string(str(i+1), 65 + 30 * i, 5, NR)

def touche():
 while True:
  for i in BTS:
   if keydown(i): 
        sleep(.5)
        return BTS.index(i)

def jouer(c, j):
  for l in range(6):
    if plateau[l][c] == 0:
      plateau[l][c] = j
      draw_string("XO"[j-1], 66 + 30 * c, 182 - 30 * l, [BL,RO][j-1])
      return [c,l]
  return False

def gagne(p):
  if not(p): return False
  [c,l] = p
  val = plateau[l][c]
  for [u,v] in [[1,0],[0,1],[1,1],[-1,1]]:
    total = 1
    for d in [1,-1]: 
      x, y = c + d * u, l + d * v
      while (0 <= x < 7) and (0 <= y < 6):
        if plateau[y][x] == val: 
          total += 1
          x += d * u
          y += d * v
        else: break
      if total > 3: return True
  return False

def aff(j):
  t = "JOUEUR "+ "XO"[j-1] + " GAGNE" if j else " PARTIE NULLE "
  t = 5*"=" + t + 5*"="
  draw_string(t, 40, 5, WH, [GR,BL,RO][j])

def go():
  grille()
  coups, joueur = 0, 1
  while True:
    c = touche()
    pos = jouer(c, joueur)
    if gagne(pos):
      aff(joueur)
      return
    if pos: 
      joueur = 3 - joueur
      coups += 1
      if coups == 42:
        aff(0)
        return

go()

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 <a href="https://www.numworks.com/legal/cookies-policy/">cookies policy</a>.