基于python的2048小游戏(GUI版)

2048游戏想必你也玩过吧!今天我们就用python编一个!

1.准备模块

我们要用到PyQt5模块

我们可以使用python3中的pip来安装

pip install PyQt5

由于我已经安装过了,所以会显示安装成功!!

2.代码

(代码)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

'''
Game 2048 designed with pyqt5

Author: yiwente
Date: 2020.02.23
'''

from PyQt5.QtWidgets import QMainWindow, QApplication, QMessageBox
from PyQt5.QtGui import QPainter, QColor, QFont, QPen
from PyQt5.QtCore import Qt, QRect
import sys
import os
import copy
import random


class GameForm(QMainWindow):
    def __init__(self, parent=None):
        super(GameForm, self).__init__(parent)
        self.initUi()
        # 定义各数字的背景颜色
        self.colors = {0: (204, 192, 179), 2: (238, 228, 218), 4: (237, 224, 200),
                       8: (242, 177, 121), 16: (245, 149, 99), 32: (246, 124, 95),
                       64: (246, 94, 59), 128: (237, 207, 114), 256: (237, 207, 114),
                       512: (237, 207, 114), 1024: (237, 207, 114), 2048: (237, 207, 114),
                       4096: (237, 207, 114), 8192: (237, 207, 114), 16384: (237, 207, 114),
                       32768: (237, 207, 114), 65536: (237, 207, 114), 131072: (237, 207, 114),
                       262144: (237, 207, 114), 524288: (237, 207, 114), 1048576: (237, 207, 114)}
        self.initGameData()

    def initUi(self):
        self.setWindowTitle("2048")
        self.resize(505, 720)
        self.setFixedSize(self.width(), self.height())
        self.initGameOpt()

    def initGameOpt(self):
        ''' 初始化游戏配置 '''
        self.lbFont = QFont('SimSun', 12)  # label字体
        self.lgFont = QFont('SimSun', 50)  # Logo字体
        self.nmFont = QFont('SimSun', 36)  # 面板数字字体

    def initGameData(self):
        ''' 初始化游戏数字 '''
        self.data = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
        count = 0
        while count < 2:
            row = random.randint(0, len(self.data) - 1)
            col = random.randint(0, len(self.data[0]) - 1)
            if self.data[row][col] != 0:
                continue
            self.data[row][col] = 2 if random.randint(0, 1) else 4
            count += 1

        self.curScore = 0
   
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值