Python3 tkinter simple 2048 game, button operation or keyboard operation, python3tkinter

Source: Internet
Author: User

Python3 tkinter simple 2048 game, button operation or keyboard operation, python3tkinter

This 2048 game is relatively simple. You should not laugh

First, we will introduce the 2048 game, which is a 4x4 two-dimensional array. You can change the value of the array through the upper, lower, and left operations. For example, if you move up, each column is added with adjacent and equal numbers. After the addition, the numbers are displayed at the top of each column, and a number (2 or 4) is randomly filled in the blank space ). Game termination rules: no blank spaces and no adjacent numbers can be added.

The following code is used as an example to describe how to move up:

 1         for i in range(4): 2             list_data = [] 3             for j in range(4): 4                 temp = self.data[j][i] 5                 if temp != 0: 6                     if not list_data: 7                         list_data.append([temp]) 8                     elif list_data[-1][0] == temp and len(list_data[-1]) == 1: 9                         list_data[-1].append(temp)10                         self.scores += 2 * temp11                     else:12                         list_data.append([temp])13             list_data = [sum(k) for k in list_data]14             for z in range(4):15                 self.data[z][i] = 016             for m, n in enumerate(list_data):17                 self.data[m][i] = n18         self.myprint()
View Code

Overall idea: self. data is the initialization array, and list_data is the temporary data and address. Place two adjacent numbers in each column that are equal and not 0 in the sublist of list_data [[], and then sum each sublist, you can see the result after this column is moved up. There are two ways to add a blank space for this column: ① assign the entire column to 0 first, and put the value in the previous list_data column before the column:, 10 ,.... . ② Put the values in the previous list_data column into each column, and then add null in less than four places. The first type is used here.

The following code determines the end of the game:

1         for i in range(4):2             x = y = 03             for j in range(4):4                 if i <= 2 and j <= 2:5                     if self.data[i][j] == self.data[i+1][j] or self.data[i][j] == self.data[i][j+1] or self.data[3][3] == self.data[2][3] or self.data[3][3] == self.data[3][2]:6                         return True7         else:8             return False
View Code

The above is the determination when there is no space. The idea is to traverse the numbers at each position in sequence from the upper left corner to determine whether it is equal to the number on the right or bottom of it. To avoid overflow, traverse the first three rows and three columns, and the last one is the position in the lower right corner. Just judge it separately.

All code above:

1 '''2 2048GUI 3 ''' 4 import tkinter 5 import random 6 7 class Gui2048: 8 def _ init _ (self): # display Form 9 self. data = [[0 for I in range (4)] for j in range (4)] 10 self. scores = 0 11 self. window = tkinter. tk () 12 self. window. title ("2048") 13 14 self. window. bind ("<Key>", self. fangxiangEvent) 15 16 self. canvasDa = tkinter. canvas (self. window, 17 width = 400, 18 height = 400, 19 bg = "white") 20 self. canvasDa. Pack () 21 22 frame = tkinter. frame (self. window) 23 frame. pack () 24 25 self. buttonL = tkinter. button (frame, 26 text = "Left", 27 command = self. bleft ). grid (row = 1, column = 1) 28 self. buttonR = tkinter. button (frame, 29 text = "right", 30 command = self. bright ). grid (row = 1, column = 2) 31 self. buttonU = tkinter. button (frame, 32 text = "up", 33 command = self. bup ). grid (row = 1, column = 3) 34 self. buttonD = tkinter. button (Frame, 35 text = "bottom", 36 command = self. bdown ). grid (row = 1, column = 4) 37 self. fenshu = tkinter. stringVar () 38 tkinter. label (frame, 39 textvariable = self. fenshu ). grid (row = 1, column = 5) 40 41 def fangxiangEvent (self, event): 42 if event. char = "w": 43 self. bup () 44 elif event. char = "s": 45 self. bdown () 46 elif event. char = "a": 47 self. bleft () 48 elif event. char = "d": 49 self. bright () 50 51 def Myprint (self): # insert data 52 self. rand_num () 53 self. fenshu. set (self. scores) 54 for x, line in enumerate (self. data): 55 print (line) 56 for y, num in enumerate (line): 57 self. labelXiao = tkinter. label (self. canvasDa, 58 width = 10, 59 height = 5, 60 bg = "white", 61 text = num if num! = 0 else "", 62 font = 'helvetica-20 bold ') 63 self. labelXiao. grid (row = x + 1, column = y + 1) 64 print ("---------") 65 66 def showit (self): # display window 67 self. window. mainloop () 68 69 # determine whether to continue 70 def wether_on (self): 71 for I in range (4): 72 x = y = 0 73 for j in range (4 ): 74 if I <= 2 and j <= 2: 75 if self. data [I] [j] = self. data [I + 1] [j] or self. data [I] [j] = self. data [I] [j + 1] or self. data [3] [3] = self. Data [2] [3] or self. data [3] [3] = self. data [3] [2]: 76 return True 77 else: 78 return False 79 80 # after the collision moves, randomly select the blank position, fill in a random number 2 or 4 81 def rand_num (self): 82 values = [2, 4] 83 zero_pos = [[k, _ k] for k, v in enumerate (self. data) for _ k, _ v in enumerate (v) if _ v = 0] 84 if not zero_pos: 85 if self. wether_on (): 86 return 87 else: 88 self. fenshu. set ("end, score" + str (self. scores) 89 pos = random. choice (zero _ Pos) 90 self. data [pos [0] [pos [1] = random. choice (values) 91 92 def bleft (self): 93 for I in range (4): 94 list_data = [] 95 for j in range (4): 96 temp = self. data [I] [j] 97 if temp! = 0: 98 if not list_data: 99 list_data.append ([temp]) 100 elif list_data [-1] [0] = temp and len (list_data [-1]) = 1:101 list_data [-1]. append (temp) 102 self. scores + = 2 * temp103 else: 104 list_data.append ([temp]) 105 list_data = [sum (k) for k in list_data] 106 for z in range (4): 107 self. data [I] [z] = 0108 for k, v in enumerate (list_data): 109 self. data [I] [k] = v110 self. myprint () 111 112 def bright (self): 1 13 for I in range (4): 114 list_data = [] 115 for j in range (4): 116 temp = self. data [I] [j] 117 if temp! = If not list_data: 119 list_data.append ([temp]) 120 elif list_data [-1] [0] = temp and len (list_data [-1]) = 1:121 list_data [-1]. append (temp) 122 self. scores + = 2 * temp123 else: 124 list_data.append ([temp]) 125 list_data = [sum (k) for k in list_data] 126 for z in range (4): 127 self. data [I] [z] = 0128 for m, n in enumerate (list_data): 129 self. data [I] [4-len (list_data) + m] = n130 self. myprint () 131 1 32 def bup (self): 133 for I in range (4): 134 list_data = [] 135 for j in range (4): 136 temp = self. data [j] [I] 137 if temp! = If not list_data: 139 list_data.append ([temp]) 140 elif list_data [-1] [0] = temp and len (list_data [-1]) = 1:141 list_data [-1]. append (temp) 142 self. scores + = 2 * temp143 else: 144 list_data.append ([temp]) 145 list_data = [sum (k) for k in list_data] 146 for z in range (4): 147 self. data [z] [I] = 0148 for m, n in enumerate (list_data): 149 self. data [m] [I] = n150 self. myprint () 151 152 def bdown (self): 15 3 for I in range (4): 154 list_data = [] 155 for j in range (4): 156 temp = self. data [j] [I] 157 if temp! = If not list_data: 159 list_data.append ([temp]) 160 elif list_data [-1] [0] = temp and len (list_data [-1]) = 1: 161 list_data [-1]. append (temp) 162 self. scores + = 2 * temp163 else: 164 list_data.append ([temp]) 165 list_data = [sum (k) for k in list_data] 166 for z in range (4): 167 self. data [z] [I] = 0168 for m, n in enumerate (list_data): 169 self. data [4-len (list_data) + m] [I] = n170 self. myprint () 171 172 if _ name _ = '_ main _': 173 GG = Gui2048 () 174 GG. myprint () 175 GG. showit ()
All Code

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.