Game Development 12 min read

Build a Console 2048 Game in Python: Complete Step-by-Step Guide

This article walks through the full implementation of a console‑based 2048 game in Python, covering the main game loop, movement logic using matrix operations, random tile generation, score handling, board rendering with curses, and the initialization process, all illustrated with code snippets and diagrams.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Build a Console 2048 Game in Python: Complete Step-by-Step Guide

We previously covered the basic concepts needed to create a simple 2048 game; this article explains how to implement each module in Python.

Main Game Loop

The game function reads user input (w, s, a, d), checks whether a move is possible, calls the appropriate move function, generates a random tile if the board changed, and then checks for a full board (calling fail) or a win condition.

def game(board, stdscr, rscore):
    global score
    global change
    curses.noecho()
    while 1:
        order = stdscr.getch()
        current_board, change = move(order, board)
        if change:
            current_board = choice(board)
        print_board(stdscr, current_board, rscore)
        if (current_board != 0).all():
            fail(current_board)
        if win:
            stdscr.addstr('You win')
        return newboard, change

Movement Module

The core basic function performs sliding and merging for a single row, using a flag to repeat the pass until no changes occur. Directional moves ( move_up, move_down, move_left, move_right) are built on basic by applying matrix transposition and reversal.

Example of right‑slide logic:

Iterate over each of the four rows.

While a change flag is set, scan the row from right to left.

If a non‑zero cell has an empty neighbour, swap them.

If two adjacent cells have the same value, merge them (double the value, set the original cell to zero) and increase the score by 100.

The process repeats until no further moves are possible, then returns the updated board.

def basic(board):
    global score
    global win
    for i in range(4):
        flag = 1
        while flag:
            flag = 0
            j = 2
            while j >= 0:
                if board[i, j] != 0:
                    if board[i, j+1] == board[i, j]:
                        board[i, j+1] = 2 * board[i, j]
                        if board[i, j+1] == 2048:
                            win = 1
                        board[i, j] = 0
                        score += 100
                        flag = 1
                    elif board[i, j+1] == 0:
                        board[i, j], board[i, j+1] = 0, board[i, j]
                        flag = 1
                j -= 1
    return board
def move_right(board):
    return basic(board)
def move_up(board):
    board = board[::-1, ::-1].T
    board = basic(board)
    board = board[::-1, ::-1].T
    return board
def move_left(board):
    board = board[::-1, ::-1]
    board = basic(board)
    board = board[::-1, ::-1]
    return board
def move_down(board):
    board = board.T
    board = basic(board)
    board = board.T
    return board
def move(order, board):
    global score
    global win
    change = 1
    tempboard = copy.deepcopy(board)
    if order == ord('q'):
        save_score(score)
        exit()
    elif order == ord('r'):
        win = 0
        save_score(score)
        score = 0
        stdscr.clear()
        wrapper(main)
    elif win:
        change = 0
        return tempboard, change
    elif order == ord('w'):
        newboard = move_up(board)
    elif order == ord('s'):
        newboard = move_down(board)
    elif order == ord('a'):
        newboard = move_left(board)
    elif order == ord('d'):
        newboard = move_right(board)
    else:
        newboard = board
    if (newboard == tempboard).all():
        change = 0
    return newboard, change

Random Tile Generation

The choice function collects coordinates of empty cells, selects one at random, and places either a 2 (75% chance) or a 4 (25% chance) there.

def choice(board):
    udict = {}
    count = 0
    for i in range(4):
        for j in range(4):
            if not board[i, j]:
                udict[count] = (i, j)
                count += 1
    random_number = np.random.randint(0, count)
    two_or_four = np.random.choice([2, 2, 2, 4])
    board[udict[random_number]] = two_or_four
    return board

Score Management

Scores are loaded from and saved to a NumPy file out.npy. compare_score updates the high score if the current score exceeds it.

def load_score():
    rank_score = np.load(FILENAME)
    return rank_score
def save_score(score):
    rscore = load_score()
    if score > rscore:
        np.save(FILENAME, score)
def compare_score(score, rscore):
    if score > rscore:
        rscore = score
    return rscore

Board Rendering

The print_board function uses the curses library to display the current score, high score, and a grid showing only non‑zero tiles.

def print_board(stdscr, board, rscore):
    global score
    rscore = compare_score(score, rscore)
    stdscr.clear()
    stdscr.addstr('得分:' + str(score) + '
')
    stdscr.addstr('历史最高:' + str(rscore) + '
')
    for i in range(4):
        stdscr.addstr('-' * 22 + '
')
        for j in range(4):
            stdscr.addstr('|')
            if board[i, j]:
                stdscr.addstr('{:^4d}'.format(board[i, j]))
            else:
                stdscr.addstr('    ')
            stdscr.addstr('|')
        stdscr.addstr('
')
    stdscr.addstr('-' * 22 + '
')

Initialization and Main Entry

Necessary imports include numpy, curses, copy, and os. The init function creates the initial board by calling choice on a zero matrix and saves a placeholder file if it does not exist. The main function sets up the board, loads the high score, prints the board, and starts the game loop.

import numpy as np
import curses
import copy
import os
from curses import wrapper

stdscr = curses.initscr()
score = 0
win = 0
FILENAME = 'out.npy'

def init():
    if FILENAME not in os.listdir():
        np.save(FILENAME, 0)
    init_board = choice(np.zeros((4, 4), dtype=np.int))
    return init_board

def main(stdscr):
    init_board = init()
    rscore = load_score()
    print_board(stdscr, init_board, rscore)
    game(init_board, stdscr, rscore)

if __name__ == "__main__":
    wrapper(main)

Illustrations

Matrix representation of the board
Matrix representation of the board

Right‑slide example: starting row [2 2 0 4] becomes [0 0 0 8] after four passes.

Up‑slide via transpose and reverse
Up‑slide via transpose and reverse
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonGame Developmentconsolecurses2048
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.