1. minesweeper

The effect

  1. code
From tkinter import * import random class main: Class minebtn(Button): def __init__(self,master,xy,**kw): Button.__init__(self,master,**kw) self.xy = xy self._state = 0 The question mark def __init__ (self) : Self. width = 9 self.height = 9 self.minenum = 10 self.minenum = 10 Colorlist = ['green', # green' DodgerBlue', # Light blue' DarkOrange1',# Orange 'Blue ',# Blue' Red ',# Red 'Chocolate4', # brown 'Grey ', Self.setgui () def setgui(self): Self.root = Tk() self.root. Title (' minesweeper ') self.restLabel = Label(self.root,text=f' {self.minenum}') self.restlabel.grid(row=0,column=0,columnspan=3) self.mineplace = The random sample (range (self. Width * self. Height), the self. Minenum) # random ray self. Mineplace = [(x % self. The width, x / / self. Height) for x Self. Mines = {} for y in range(self.height): for x in range(self.width): Self. Mines [(x, y)] = self. Minebtn (self. Root, y = (x, y), the font = (' bold ', 8, 'bold'), width = 2, bd = 1, relief = 'ridge') Self.mines [(x,y)].bind('< buttonRelease-1 >',lambda event:self._open(event.widget)) # Self.mines [(x,y)].bind('< buttonRelease-3 >',lambda event:self.make(event.widget)) # If (row=y+1,column=x, column=x) self.root.mainloop() # def _open(self,widget): Xy = widget.xy x = xy[0] y = xy[1] # get the coordinates of the current button # Self. Showmine () return # Do nothing if widget._state == 1: Return Widget. configure(relief='flat',bg='white') # Change the style of the current button widget._state = 1 # Button state is set to open # Get the coordinates of the eight ray around = [(x-1,y-1), (x,y-1), (x+1,y-1), (x-1,y), (x+1,y), (x-1,y+1), (x,y+1), (x+1,y+1)] _sum = 0 around_ = [] for o, If 0 <= o <= self.width - 1 and 0 <= p <= self.height - 1: Self. Mines [(o,p)].xy in self. Mineplace: around_.append((o,p)) # If _sum == 0: widget['text'] = "for I, j in around: if self.mines[(i,j)]._state == 0: self._open(self.mines[(i,j)]) else: Widget ['fg'] = self. Colorlist [_sum-1] # def make(self,widget): String = {0: "', 2: '♀, 3:'? '} if widget._state == 0: Widget. _state = 2 Widget ['text'] = string[2] self.rest -= 1 self. restLabel ['text'] = f {self.rest}' elif widget._state == 2: Widget. _state = 3 Widget ['text'] = string[3] self.rest += 1 self.restLabel ['text'] = f {self.rest}' elif widget._state == 3: widget._state = 0 widget['text'] = string[0] # def showmine(self): For I,j in self.mineplace: self.mines[(I,j)]. Configure (text='ி',fg='red') main()Copy the code

Because it is so simple, there are not so many complicated steps, and for this simple H5 game, it is very easy to design in Python.