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