[introduction to Python tutorial] Python example: Games 20148

Posted by stovellp on Wed, 12 Jan 2022 10:59:53 +0100

This tutorial quickly and completely presents the process of programming in Python language through 2048 games, and organically combines the contents previously introduced. 2048 is a puzzle game popular on mobile phones, tablets and other terminal devices. It was first released in March 2014. The main interface is shown in Figure 1.

Figure 1: main interface of 2048 games

The rules of the game are: you can choose one of the up, down, left and right directions to slide each time. Each time you slide, all the digital blocks will move closer to the sliding direction. The system will also randomly appear a digital block in the blank place, and the blocks of the same number will be added when they move closer and collide. The number box given by the system is either 2 or 4. Players should find a way to put together the number box "2048" in this small 16 grid range.

The game skills summarized by netizens include:

  • Put the maximum number in the corner as far as possible;
  • Numbers are arranged next to each other in order;
  • First, the column / row in which the maximum number and sub maximum number are satisfied is full;
  • Always note that there should be similar numbers next to the larger number of activities (more than 32);
  • The main moving direction of a behavior with a large number;
  • Don't rush to "clean the desktop";
  • According to the rules of the game, the process of the game can be sorted out, as shown in Figure 2.

Figure 2: main flow of 2048 games

According to the flow chart, the whole game program can be roughly divided into three parts:

  1. Program initialization;
  2. Judge user input;
  3. Enter the main cycle of the game.

The third part can be further subdivided into the following three parts:

  1. Waiting for operation;
  2. Judge the operation and deal with it;
  3. Restart or exit.

In order to make the game interface beautiful, the pygame library is used here. The commands to install the pygame library are as follows:

  1. pip install pygame

The installation process is shown in Figure 3.

Figure 3: pygame library installation process

Let's continue to focus on 2048 games. First, let's look at program initialization. Here we mainly complete the following work: import the required modules, initialize the chessboard and window interface, and initialize various components and variables. According to the rules of the game, the size of the chessboard is 4 × 4 square chessboard with 16 grids in total. For simplicity, we use a two-dimensional list to store the numbers in each grid.

The statement to define the chessboard and initialize the numbers stored in each grid is as follows:

board = [[0, 0, 0, 0]
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]

The following statement initializes the properties of the window:

1.  #Side length of each grid, unit: pixel (the same below)
2.  box_size = 50
3.  #Spacing between grids
4.  box_gap = 5
5.  #The distance from the top edge of the central chessboard area to the top of the window
6.  top_of_window = 100
7.  #Distance from the lower edge of the central chessboard area to the bottom of the window
8.  bottom_of_window = 30
9.  #The distance from the left edge of the central chessboard area to the left of the window
10.  left_of_window = 2 0
11.  #Window width
12.  window_width = box_size * 4 + box_gap * 5 + left_of_window * 2
13.  #Window height
14.  window_height = top_of_window + box_gap * 5 + box_size * 4 + left_of_window + bottom_of_window
15.  #Initialization window
16.  window = pygame.display.set_mode((window_width, window_height), 0, 32)
17.  #Window title
18.  pygame.display.set_caption("2048")
19.  #score
20.  score = 0
21.  #Define some color constants using pygame's built-in color values
22.  OLDLACE = pygame.color.THECOLORS["oldlacen"]
23.  IVORY = pygame.color.THECOLORS["ivory3"]
24.  BLACK = pygame.color.THECOLORS["black"]
25.  RED = pygame.color.THECOLORS["red"]
26.  RED2 = pygame.color.THECOLORS["red2"]
27.  DARKGOLD = pygame.color.THECOLORS["darkgoldenrodl"]
28.  GOLD = pygame.color.THECOLORS["gold"]
29.  GRAY = pygame.color.THECOLORS["gray41"]
30.  CHOCOLATE = pygame.color.THECOLORS["chocolate"]
31.  CHOCOLATE1 = pygame.color.THECOLORS["chocolate1"]
32.  CORAL = pygame.color.THECOLORS["coral"]
33.  CORAL2 = pygame.color.THECOLORS["coral2"]
34.  ORANGED = pygame.color.THECOLORS["orangered"]
35.  ORANGED2 = pygame.color.THECOLORS["orangered2"]
36.  DARKORANGE = pygame.color.THECOLORS["darkorange"]
37.  DARKORANGE2 = pygame.color.THECOLORS["darkorange2"]
38.  FORESTGREEN = pygame.color.THECOLORS["forestgreen"]
39.  #Interface font
40.  FONTNAME = "SimHei"

Drawing checkerboard lattice is mainly composed of box class and draw class_ Box() function completed:

1.  class Box:
2.  def __init__(self, topleft, text, color):
3.  self.topleft = topleft
4.  self.text = text
5.  self.color = color
6.  def render(self, surface):
7.  x, y = self.topleft
8.  #Draw checkerboard
9.  pygame.draw.rect(surface, self.color, (xz y, box_size, box_ size))
10.  #Defines the height of the number in the checkerboard
11.  text_height = int(box_size * 0.35)
12.  #Sets the font used for numbers in the checkerboard
13.  font_obj = pygame.font.SysFont(FONTNAME, text_height)
14.  text_surface = font_obj.render(self.text, True, BLACK)
15.  text_rect = text_surface.get_rect()
16.  text_rect.center = (x + box_size / 2, y + box_size / 2)
17.  surface.blit(text_surface, text_rect)
18.  def draw_box():
19.  giobal board
20.  #Define the color of different numbers in each grid on the chessboard
21.  colors = {0 : (192, 192, 192) , 2 : (176, 224, 230) , 4 : (127, 255, 212), 8 : (135, 206, 235) , 16 : (64, 224, 208),
22.  32 : (0, 255, 255), 64 : (0, 201, 87), 128: (50, 205, 50), 256 : (34, 139, 34),
23.  512 : (0, 255, 127) , 1024 : (61, 145, 64), 2048 : (48, 128, 20), 4096 : (65, 105, 255),
24.  8192 : (8, 46, 84) , 16384 : (11, 23, 70), 32 768: (25, 25, 112), 65536 : (0, 0, 255) }
25.  x, y = left_of_window, top_of_window
26.  size = box_size * 4 + box gap * 5
27.  pygame.draw.rect(window, BLACK, (x, y, size, size))
28.  x, y = x + box_gap, y + box_gap
29.  #Use nested loops to draw all the squares on the chessboard
30.  for i in range(4):
31.  for j in range(4):
32.  idx = board. [ i ] [ j ]
33.  if idx == 0:
34.  text =""
35.  else :
36.  text = str(idx)
37.  if idx > 65536: idx = 65536
38.  color = colors[idx]
39.  box = Box((x, y), text, color) box.render(window)
40.  x += box_size + box_gap
41.  x = left_of_window + box_gap
42.  y += box_size + box_gap


Next, you need to initialize the opening number on the chessboard. Let's see set_random_number( ) Function: for novices, Xiaobai wants to learn it more easily Python Basics, Python Reptiles, web Development, big data, data analysis,Artificial intelligence and other technologies. Here we share the system teaching resources. My captain (Tongying): 2763177065 [tutorial]/tool/method/[solution]



1.  def set_random_number():
2.  pool =[]
3.  for i in range(4):
4.  for j in range (4):
5.  if board[i][j] == 0:
6.  pool. append. ( (if j ))
7.  m = random.choice(pool)
8.  pool.remove(m)
9.  value = random.uniform(0, 1)
10.  if value < 0.1:
11.  value = 4
12.  else :
13.  value = 2
14.  board[m[0]][m[1]] = value

Its function is to randomly select two grids on the chessboard and set their value to 2 or 4.

The following code will draw the rest of the interface content of the game window:

1.  #Show game name
2.  window.blit(write ("2048", height = 45, color = GOLD), (left_of_ window, left_of_window // 2))
3.  #Displays the current score
4.  window.blit(write("score", height=14, color=FORESTGREEN), (left_of_window+105, left_of_window//2 + 5))
5.  rect1 = pygame.draw.rect(window, FORESTGREEN, (left_of_window+100, left_of_window//2 + 30, 60, 20))
6.  text1 = write(str(score), height=14, color=GOLD)
7.  text1_rect = text1.get_rect()
8.  text1_rect.center = (left_of_window+100+30, left_of_window//2 + 40)
9.  window.blit(textlf textl_rect)
10.  #Displays the highest score in history
11.  window.blit(write("highest", height=14, color=FORESTGREEN), (left_of_window+175, left_of_window//2 + 5))
12.  rect2 = pygame.draw.rect(window, FORESTGREEN, (left_of_window+165, left_of_window//2 + 30, 60, 20))
13.  #Read the highest score in history
14.  best = read_best()
15.  if best < score:
16.  best = score
17.  text2 = write(str(best), height=14, color=GOLD)
18.  text2_rect = text2.get_rect()
19.  text2_rect.center = (left_of_window+165+30, left_of_window//2 + 40)
20.  window.blit(text2, text2_rect)
21.  #Display game operation tips
22.  window.blit(write("Use the up, down, left and right direction keys to control", height=16, color=GRAY), (left_of_window, window_height - bottom_of_Window))

Judge that the user's operation and processing are completed through infinite loop, and the code is as follows:

1.  while True:
2.  #Get the current user action through the event mechanism
3.  for event in pygame.event.get():
4.  #The user operation is to exit the window or write the highest score when pressing ESC key, and exit the game window
5.  if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):
6.  write_best(best)
7.  pygame.quit ()
8.  exit ()
9.  #The game does not monitor the user's operation at the normal end
10.  elif not gameover:
11.  #The user presses the up arrow key on the keyboard
12.  if event.type == KEYUP and event.key == K_UP:
13.  up()
14.  #The user presses the down arrow key on the keyboard 
15.  elif event.type ==KEYUP and event.key == K DOWN:
16.  down()    
17.  #The user presses the left arrow key on the keyboard 
18.  elif event.type ==KEYUP and event.key == K_LEFT:
19.  left ()    
20.  # The user presses the right arrow key on the keyboard 
21.  elif event.type ==KEYUP and event.key == K_ RHGHT:
22.  right ()
23.  #Start a new game
24.  if newboard != board:
25.  set_random_number()
26.  newboard = deepcopy(board) draw_box()
27.  gameover = is_over()
28.  rect1 = pygame.draw.rect(window, FORESTGREEN,(left_ of_window+100, left_of_window//2 + 30, 60, 20))
29.  text1 = write(str(score), height=14, color=GOLD)
30.  text_rect = text1.get_rect()
31.  text_rect.center = (left_of_window+100+30Aleft_of_window//2 + 4 0)
32.  window.blit(text1, text_rect)
33.  rect2 = pygame.draw.rect(window, FORESTGREEN, (left_of_window+165, left_of_window//2 + 30, 60, 20))
34.  if best < score:
35.  best = score
36.  text2 = write(str(best), height=14, color=GOLD)
37.  text2_rect = text2.get_rect()
38.  text2_rect.center = (left_of_window+l65+30, left_of_window//2 + 4 0)
39.  window.blit(text2, text2_rect)
40.  #The game ends normally (that is, the user has synthesized 2048 or not, but the next operation cannot be continued on the chessboard)
41.  else :
42.  write_best(best)
43.  window.blit(write("game over! ", height = 40, color = FORESTGREEN), (left_of_windowz window_height // 2))

In order to achieve the game effect, several key functions need to be defined: first, sum the numbers on the chessboard, which is used to merge the numbers on the chessboard after the user presses the up, down, left and right operation keys. The code is as follows:

1.  def combinate(L):
2.  glbal score
3.  ans = [0, 0, 0 , 0]
4.  num =[]
5.  for i in L:
6.  if i != 0:
7.  num. append. (i)
8.  length = len(num)
9.  #When there are 4 numbers that are not 0
10.  if length == 4:
11.  if num[0] == num[1]:
12.  ans[0] = num[0] + num[1]
13.  score += ans[0]
14.  if num[2] == num[3]:
15.  ans[1] = num[2] + num [3]
16.  score += ans[1]
17.  else :
18.  ans[1]=num[2]
19.  ans [2]=num[3]
20.  elif num[1] ==num[2]
21.  ans [0]= num[0] 
22.  ans[1]= num[1] + num[2]
23.  ans [2]= num[3] 
24.  score += ans[1] 
25.  elif num[2] ==num[3]
26.  ans [ 0]= num[0] 
27.  ans[1]= num[1] 
28.  ans [2]= num[2] + num[3]
29.  score += ans[2] 
30.  else :  
31.  for i in range(length): 
32.  ans[i] = num[i]
33.  #When there are 3 numbers that are not 0
34.  elif length == 3:
35.  if num[0] == num[1]:
36.  ans[0] = num[0] + num[1]
37.  ans[1] = num[2]
38.  score += ans[0]
39.  elif num[1] == num[2]:
40.  ans [0] = num[0]
41.  ans[1]=num[1] + num[2]
42.  score += ans[1]
43.  else :
44.  for i in range(length):
45.  ans[i] = num[i]
46.  #When there are 2 numbers that are not 0
47.  elif length == 2:
48.  if num[0] == num[1]:
49.  ans[0] = num[0] + num[1]
50.  score += ans[0]
51.  else :
52.  for i in range(length):
53.  ans[i] = num[i]
54.  #When there are only 1 numbers that are not 0
55.  elif length == 1:
56.  ans[0] = num[0]
57.  else :
58.  pass
59.  return ans

The second is the corresponding operation after the user presses the up, down, left and right control keys. It should be noted that we define the list for storing the numbers on the chessboard as a line two-dimensional list, so it is relatively easy to process the left and right keys. You only need to judge whether the left and right adjacent numbers should be merged. When processing the up and down keys, you need to find the target numbers according to the corresponding columns and then judge whether they should be merged. The code is as follows:

1.  def left():
2.  for i in range(4):
3.  temp = combinate (boa:rd [ i ])
4.  for j in range (4):
5.  board[i][j] = temp[j]

7.  def right():
8.  for i in range(4):
9.  temp = combinate (boaird[i][::-1]
10.  for j in range (4):
11.  board[i][3-j] = temp[j]

13.  def up():
14.  for i in range(4):
15.  to_comb =[]
16.  for j in range (4):
17.  to_comb.append(board[j][i])
18.  temp = combinate(to_comb)
19.  for k in range(4):
20.  board[k][i] = temp[k]

22.  def down():
23.  for i in range(4):
24.  to_comb =[]
25.  for j in range (4):
26.  to_comb.append(board[3-j][i])
27.  temp = combina.te(to_comb)
28.  for k in range (4):
29.  board[3-k][i] = temp[k]

The third is the function to judge whether the game is over_ over( ). According to the rules of the game, the game can continue only when there are still spaces on the chessboard, or there are adjacent and identical numbers in the same row / column. Otherwise, the game ends, and the function can be defined as follows:

1.  def is_over():
2.  #There are still spaces on the chessboard
3.  for i in range(4):
4.  for j in range(4):
5.  if board[i][j]==0:
6.  return False

8.  #There are adjacent and identical numbers in the same row
9.  for i in range(4):
10.  for j in range(3):
11.  if board[i][j] == board[i][j+1]:
12.  return False

14.  #There are adjacent and identical numbers in the same column
15.  for i in range(3):
16.  for j in range(4):
17.  if board[i][j] == board[i+1][j]:
18.  return False

20.  return True

So far, the main contents and key codes of the game 2048 have been introduced.

Topics: Python Programmer pygame