Reversi ( othello )

Soyez le premier à donner votre avis sur cette source.

Snippet vu 13 637 fois - Téléchargée 36 fois

Contenu du snippet

vous connaissez surement ce jeu, donc je vais pas expliquer quel est son principe. et pour ceux qui connaissent pas, je suis desolé ;).
j'ai utiliser qq notions de POO, ça fait style ;)

Source / Exemple :


#!/usr/bin/env python
from Tkinter import *

class ReversiGUI(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.table = []
        self.color = [["#EEE","#FFF","EEE"],["#F88","#FCC","#FDD"],["#88F","#CCF","#DDF"]]
        self.net = 0
        self.reversi = Reversi()
        self.players = [Player(self.reversi),Human(self.reversi,"player1"),Human(self.reversi,"player2")]
        self.hostname = ""
        self.createWidget()
        self.new()
    def defPushButton(self,i,j):
        def pushButton():
            self.pushButton(i,j)
        self.table[i][j]["command"] = pushButton
    def new(self):
        i = 0
        for entry in self.entryPlayerName:
            i = i + 1
            entry.delete(0, END)
            entry.insert(0, self.players[i].name)
        i = 0
        for check in self.checkPlayerAI:
            i = i + 1
            if isinstance(self.players[i],AI): check.set(1)
            else : check.set(0)
        self.network.set(self.net)
        self.entryHostname.delete(0, END)
        self.entryHostname.insert(0, self.hostname)
        self.tableFrame.forget()
        self.tableConfig.pack(fill=BOTH, expand=1, side=TOP)
        self.buttonNew["state"] = "disable"
    def newOk(self):
        i = 0
        name = ["",""]
        for entry in self.entryPlayerName:
            name[i] = entry.get()
            i = i + 1

        self.net = self.network.get()
        self.hostname = self.entryHostname.get()
        if self.net:
            if self.hostname == "":
                self.players[2] = Net(self.reversi,name[1])
                if self.checkPlayerAI[0].get(): self.players[1] = AI(self.reversi,name[0])
                else: self.players[1] = Human(self.reversi,name[0])
            else:
                self.players[1] = Net(self.reversi,name[0],hostname)
                if self.checkPlayerAI[1].get(): self.players[2] = AI(self.reversi,name[1])
                else: self.players[2] = Human(self.reversi,name[1])
        else:
            for i in range(2):
                if self.checkPlayerAI[i].get(): self.players[i+1] = AI(self.reversi,name[i])
                else: self.players[i+1] = Human(self.reversi,name[i])
        self.reversi.reset()
        self.maj()
        self.tableConfig.forget()
        self.tableFrame.pack(fill=BOTH, expand=1, side=TOP)
        self.buttonNew["state"] = "normal"
    def newCancel(self):
        self.tableConfig.forget()
        self.tableFrame.pack(fill=BOTH, expand=1, side=TOP)
    def createWidget(self):
        self.pack(fill=BOTH, expand=1)
        self.buttonFrame = Frame(self)
        self.buttonFrame.pack(fill=X,side=BOTTOM)
        self.buttonExit = Button(self.buttonFrame, text="Exit", command=self.quit)
        self.buttonExit.pack(side=LEFT,fill=X,expand=1)
        self.buttonNew = Button(self.buttonFrame, text="New", command=self.new)
        self.buttonNew.pack(side=RIGHT,fill=X,expand=1)
        self.player = Label(self)
        self.player.pack(fill=X, side=BOTTOM)
        self.tableFrame = Frame(self)
        self.tableFrame.pack(fill=BOTH, expand=1, side=TOP)
        self.tableConfig = Frame(self)
        self.entryPlayerName = []
        self.checkPlayerAI = []
        for i in range(1,3):
            frame = Frame(self.tableConfig)
            Label(frame, text="player "+str(i)+" name :").pack(side=LEFT)
            self.checkPlayerAI.append(IntVar())
            if isinstance(self.players[i], AI): self.checkPlayerAI[-1].set(1)
            else: self.checkPlayerAI[-1].set(0)
            Checkbutton(frame, text="AI", variable=self.checkPlayerAI[-1]).pack(side=RIGHT)
            self.entryPlayerName.append(Entry(frame))
            self.entryPlayerName[-1].insert(0, self.players[i].name)
            self.entryPlayerName[-1].pack(side=RIGHT,fill=X,expand=1)
            frame.pack(side=TOP,fill=X)

        frame = Frame(self.tableConfig)
        Label(frame, text="hostname").pack(side=LEFT)
        self.entryHostname = Entry(frame)
        self.entryHostname.insert(0, self.hostname)
        self.entryHostname.pack(side=RIGHT,fill=X,expand=1)
        frame.pack(side=TOP,fill=X)
        self.network = IntVar()
        self.CheckNetwork = Checkbutton(self.tableConfig, text="NetWork", variable=self.network)
        self.network.set(self.net)
        self.CheckNetwork.pack(side=TOP, fill=X)

        frame = Frame(self.tableConfig)
        Button(frame, text="Ok", command=self.newOk).pack(side=LEFT,fill=X,expand=1)
        Button(frame, text="Cancel", command=self.newCancel).pack(side=RIGHT,fill=X,expand=1)
        frame.pack(side=TOP,fill=X)
        
        for i in range(8):
            self.table.append([])
            for j in range(8):
                self.table[i].append(Button(self.tableFrame))
                self.table[i][j].grid(row=j,column=i)
                self.defPushButton(i,j)
    def play(self, x, y):
        if self.reversi.play(x, y):
            self.maj()
            return
        self.player["text"] = "Game Interrupted (Play Error)"        
    def pushButton(self, i, j):
        self.players[self.reversi.player].callback(i,j)
    def maj(self):
        for i in range(8):
            for j in range(8):
                self.table[i][j]["bg"] = self.color[self.reversi.table[i][j]][0]
                self.table[i][j]["activebackground"] = self.color[self.reversi.player][1]
                if (i,j) in self.reversi.playList:
                    self.table[i][j]["bg"] = self.color[self.reversi.player][2]
                    self.table[i][j]["activebackground"] = self.color[self.reversi.player][1]
                    if isinstance(self.players[self.reversi.player], Human):
                        self.table[i][j]["state"] = "normal"
                    else:
                        self.table[i][j]["state"] = "disable"
                else:
                    self.table[i][j]["state"] = "disable"
        if not self.reversi.player:
            s1 = self.players[1].name + ":" + str(self.reversi.score[0])
            s2 = self.players[2].name + ":" + str(self.reversi.score[1])
            self.player["text"] = s1 + " - " + s2
            n = 0
            if self.reversi.score[0] < self.reversi.score[1]: n = 2
            if self.reversi.score[0] > self.reversi.score[1]: n = 1
            self.player["bg"] = self.color[n][0]
        else:
            self.player["text"] = self.players[self.reversi.player]
            self.player["bg"] = self.color[self.reversi.player][0]
            self.players[self.reversi.player].play(self.play)

class Player:
    def __init__(self, reversi, name="player"):
        self.name = name
        self.reversi = reversi
    def __str__(self):
        return self.name
    def __type__(self):
        return "Player"
    def send(self, x, y):
        pass
    def play(self, callback):
        callback(8,8)

class Human(Player):
    def __init__(self, reversi, name="Human"):
        Player.__init__(self, reversi, name)
    def play(self, callback):
        self.callback = callback

#TODO:
class AI(Player):
    def __init__(self, reversi, name="AI", depth=2):
        Player.__init__(self, reversi, name)
        self.depth = depth
    def play(self, callback):
        callback(8,8)

#TODO:
class Net(Player):
    def __init__(self, reversi, name="Net", hostname=""):
        Player.__init__(self, reversi, name)
        self.hostname = hostname
    def send(self, x, y):
        self.socket.write("x:"+str(x)+" y:"+str(y))
    def play(self, callback):
        str = self.socket.read(32)
        ix = str.find("x:")
        iy = str.find("y:")
        if ix == -1 or iy == -1: callback(8,8)
        try:
            x = int(str[ix+2:iy-1])
            y = int(str[iy+2:])
        except:
            callback(8,8)
        callback(x,y)
        
class Reversi:
    def reset(self):
        self.table = [[0 for j in range(8)] for i in range(8)]
        self.table[3][3] = 1
        self.table[4][4] = 1
        self.table[3][4] = 2
        self.table[4][3] = 2
        self.player = 1
        self.score = self.get_score()
        self.playList = self.where_play()
    def where_play(self):
        l = []
        if self.player == 0: return l
        for x in range(8):
            for y in range(8):
                if self.play(x, y, 1):
                    l.append((x,y))
        return l
    def make_dir(self, x, y, dx, dy, test=0):
        if (x+dx)<0 or (x+dx)>=8 or (y+dy)<0 or (y+dy)>=8:
            return -1
        if self.table[x+dx][y+dy] == 0:
            return -1
        if self.table[x+dx][y+dy] == self.player:
            return 0
        ret = self.make_dir(x+dx,y+dy,dx,dy, test)
        if ret == -1:
            return ret
        if not test:
            self.table[x+dx][y+dy] = self.player
        return ret+1
    def get_score(self):
        s = [0,0,0]
        for x in range(8):
            for y in range(8):
                s[self.table[x][y]] = s[self.table[x][y]] + 1
        return s[1:]
    def play(self, x, y, test=0):
        ret = 0
        if x<0 or x>=8 or y<0 or y>=8: return 0
        if self.player == 0: return 0
        if self.table[x][y] != 0: return 0
        for dx in range(-1,2):
            for dy in range(-1, 2):
                if dx == 0 and dy == 0: continue
                n = self.make_dir(x, y, dx, dy, test)
                if n > 0: ret = 1
        if ret and test==0:
            self.table[x][y] = self.player
            self.player = ((self.player)%2)+1
            self.playList = self.where_play()
            self.score = self.get_score()
            if not self.playList:
                self.player = ((self.player)%2)+1
                self.playList = self.where_play()
                if not self.playList:
                    self.player = 0
        return ret
    def __init__(self):
        self.reset()

app = ReversiGUI()
app.mainloop()

Conclusion :


malheuresement, je ne l'ai pas terminé, mais y'as déjà des trucs qui fonctionnent.
me reste a faire l'ia, et le reseau. mais bon je pense pas que ce sera fait un jour ;) le python c pas mon language de predilection.
sinon j'ai la meme chose en C, avec IA, en utilisant SDL ou GTK ou la Console.
mais j'ai pas encore eu le temps de le mettre sur cppfrance.

A voir également

Ajouter un commentaire Commentaire
Messages postés
4030
Date d'inscription
mardi 13 mai 2003
Statut
Modérateur
Dernière intervention
23 décembre 2008
22
Ah dommage que tu ne continues pas. Ca paraissait bien parti.
Bon ben ... attendons alors.

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.