SoFunction
Updated on 2024-10-28

python pygame implementation of the 2048 game

Implementing 2048 is relatively simple, use a 4*4 2D array to save the map, .get_pressed() to get the keyboard operation, see the code for details.

rendering (visual representation of how things will turn out)

coding

# -*- coding: utf-8 -*-
#!/usr/bin/python
'''
Created on May 31, 2014
@author: yuanzi
'''
import random
import sys
import pygame
from  import *
 
PIXEL = 150
SCORE_PIXEL = 100
SIZE = 4
 
# Classes for maps
class Map:
  def __init__(self, size):
     = size
     = 0
     = [[0 for i in range(size)] for i in range(size)]
    ()
    ()
  
  # Add a new 2 or 4 with a 1/4 chance of producing a 4
  def add(self):
    while True:
      p = (0,  *  - 1)
      if [p / ][p % ] == 0:
        x = (0, 3) > 0 and 2 or 4
        [p / ][p % ] = x
         += x
        break
  
  # The map is close to the left, other directions can be achieved by rotating it appropriately, return whether the map is updated or not
  def adjust(self):
    changed = False
    for a in :
      b = []
      last = 0
      for v in a:
        if v != 0:
          if v == last:
            (() << 1)
            last = 0
          else:
            (v)
            last = v
      b += [0] * ( - len(b))
      for i in range():
        if a[i] != b[i]:
          changed = True
      a[ : ] = b
    return changed
  
  # Rotate the map 90 degrees counterclockwise
  def rotate90(self):
     = [[[c][r] for c in range()] for r in reversed(range())]
  
  # To determine the end of the game
  def over(self):
    for r in range():
      for c in range():
        if [r][c] == 0:
          return False
    for r in range():
      for c in range( - 1):
        if [r][c] == [r][c + 1]:
          return False
    for r in range( - 1):
      for c in range():
        if [r][c] == [r + 1][c]:
          return False
    return True
  
  def moveUp(self):
    self.rotate90()
    if ():
      ()
    self.rotate90()
    self.rotate90()
    self.rotate90()
  
  def moveRight(self):
    self.rotate90()
    self.rotate90()
    if ():
      ()
    self.rotate90()
    self.rotate90()
  
  def moveDown(self):
    self.rotate90()
    self.rotate90()
    self.rotate90()
    if ():
      ()
    self.rotate90()
  
  def moveLeft(self):
    if ():
      ()
 
# Update the screen
def show(map):
  for i in range(SIZE):
    for j in range(SIZE):
      # Background color blocks
      ([i][j] == 0 and block[(i + j) % 2] or block[2 + (i + j) % 2], (PIXEL * j, PIXEL * i))
      # Numeric display
      if [i][j] != 0:
        map_text = map_font.render(str([i][j]), True, (106, 90, 205))
        text_rect = map_text.get_rect()
        text_rect.center = (PIXEL * j + PIXEL / 2, PIXEL * i + PIXEL / 2)
        (map_text, text_rect)
  # Score display
  (score_block, (0, PIXEL * SIZE))
  score_text = score_font.render((() and "Game over with score " or "Score: ") + str(), True, (106, 90, 205))
  score_rect = score_text.get_rect()
  score_rect.center = (PIXEL * SIZE / 2, PIXEL * SIZE + SCORE_PIXEL / 2)
  (score_text, score_rect)
  ()
 
map = Map(SIZE)
()
screen = .set_mode((PIXEL * SIZE, PIXEL * SIZE + SCORE_PIXEL))
.set_caption("2048")
block = [((PIXEL, PIXEL)) for i in range(4)]
# Set the color
block[0].fill((152, 251, 152))
block[1].fill((240, 255, 255))
block[2].fill((0, 255, 127))
block[3].fill((225, 255, 255))
score_block = ((PIXEL * SIZE, SCORE_PIXEL))
score_block.fill((245, 245, 245))
# Set the font
map_font = (None, PIXEL * 2 / 3)
score_font = (None, SCORE_PIXEL * 2 / 3)
clock = ()
show(map)
 
while not ():
  # 12 is the experimental parameter
  (12)
  for event in ():
    if  == QUIT:
      ()
  # Receive player actions
  pressed_keys = .get_pressed()
  if pressed_keys[K_w] or pressed_keys[K_UP]:
    ()
  elif pressed_keys[K_s] or pressed_keys[K_DOWN]:
    ()
  elif pressed_keys[K_a] or pressed_keys[K_LEFT]:
    ()
  elif pressed_keys[K_d] or pressed_keys[K_RIGHT]:
    ()
  show(map)
 
# Game over
(3000)

The implementation of animation and AI can be considered later.

This is the whole content of this article.