测开之路四十九:用Django实现扑克牌游戏

用Django实现和之前flask一样的扑克牌游戏

项目结构

html

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>扎金花</title></head><body>    {% for poker in player1 %}        <img src="/static/poker/{{ poker }}"/>    {% endfor %}    <br>    {% for poker in player2 %}        <img src="/static/poker/{{ poker }}"/>    {% endfor %}    <br>    <h1>{{ status }}</h1></body></html>

rule规则

import random

class Rule(object):

    def __init__(self):        self.data = list(range(0, 52))        self.player1 = []        for i in range(0, 3):            poker = self.deal()            self.player1.append({                ‘color‘: poker[0],                ‘value‘: poker[1],            })        self.player2 = []        for i in range(0, 3):            poker = self.deal()            self.player2.append({                ‘color‘: poker[0],                ‘value‘: poker[1],            })

    def deal(self):        data = random.choice(self.data)        index = self.data.index(data)        self.data.pop(index)        if data < 13:            color = ‘black‘            value = data % 13 + 1            if value == 1:                value == 14        elif data < 26:            color = ‘red‘            value = data % 13 + 1            if value == 1:                value == 14        elif data < 39:            color = ‘cube‘            value = data % 13 + 1            if value == 1:                value == 14        elif data < 52:            color = ‘plum‘            value = data % 13 + 1            if value == 1:                value == 14        return color, value

    def compare_value(self, data1, data2):        """        先对其进行排序,排序后便于比较。        :param data1: 这里是pai1的牌面值        :param data2: 这里是pai2的牌面值        :return:        """        data1.sort(reverse=True)        data2.sort(reverse=True)        for i in range(0, 3):            if data1[i] == data2[i]:                continue            elif data1[i] > data2[i]:                return 1            else:                return 2

    def get_color(self, player):        color = []        for poker in player:            color.append(poker[‘color‘])        return color

    def get_value(self, player):        value = []        for poker in player:            value.append(poker[‘value‘])        return value

    def is_jinhua(self, player):        """        花色相同,非顺子。例:黑桃368,方块145。        :param pai:        :return:        """        data = self.get_color(player)        if data[0] != data[1] or \                data[0] != data[2] or \                data[1] != data[2]:            return False        else:            return True

    def is_triple(self, player):        """        # 用于判断是不是豹子,豹子是三个数相同。        :param pai:        :return:        """        data = self.get_value(player)        if data[0] == data[1] and data[1] == data[2] and data[0] == data[2]:            return True        else:            return False

    def is_shunzi(self, player):        """        花色不同的顺子。例:黑桃5红桃6方块7。        :param pai:        :return:        """        data = self.get_value(player)        data.sort(reverse=True)        if data[0] - data[1] == 1 and data[1] - data[2] == 1 and data[0] - data[2] == 2:            return True        else:            return False

    def is_shunjin(self, player):        """        :param pai:        :return:        """        if self.is_shunzi(player) and self.is_jinhua(player):            return True        else:            return False

    def is_pair(self, player):        """        :param pai:        :return:        """        data = self.get_value(player)        if data[0] == data[1] or data[1] == data[2] or data[0] == data[2]:            return True        else:            return False

    def find_pair(self, player):        """        返回相等数值的索引        :param pai:        :return:        """        data = self.get_value(player)        if data[0] == data[1]:            return 0, 1        if data[1] == data[2]:            return 1, 2        if data[0] == data[2]:            return 0, 2

    def compare_baozi(self):        """        :return:        """        if self.is_triple(self.player1) and not self.is_triple(self.player2):            return 1        if not self.is_triple(self.player1) and self.is_triple(self.player2):            return 2        if not self.is_triple(self.player1) and not self.is_triple(self.player2):            return None        if self.is_triple(self.player1) and self.is_triple(self.player2):            data1 = self.get_value(self.player1)            data2 = self.get_value(self.player2)            return self.compare_value(data1, data2)

    def compare_shunjin(self):        """        :return:        """        if self.is_shunjin(self.player1) and not self.is_shunjin(self.player2):            return 1        if not self.is_shunjin(self.player1) and self.is_shunjin(self.player2):            return 2        if not self.is_shunjin(self.player1) and not self.is_shunjin(self.player2):            return None        if self.is_shunjin(self.player1) and self.is_shunjin(self.player2):            data1 = self.get_value(self.player1)            data2 = self.get_value(self.player2)            return self.compare_value(data1, data2)

    def compare_jinhua(self):        """        :return:        """        if self.is_jinhua(self.player1) and not self.is_jinhua(self.player2):            return 1        if not self.is_jinhua(self.player1) and self.is_jinhua(self.player2):            return 2        if not self.is_jinhua(self.player1) and not self.is_jinhua(self.player2):            return None        if self.is_jinhua(self.player1) and self.is_jinhua(self.player2):            data1 = self.get_value(self.player1)            data2 = self.get_value(self.player2)            return self.compare_value(data1, data2)

    def compare_shunzi(self):        """        :param pai1:        :param pai2:        :return:        """        # 顺子大于非顺子        if self.is_shunzi(self.player1) and not self.is_shunzi(self.player2):            return 1        if not self.is_shunzi(self.player1) and self.is_shunzi(self.player2):            return 2        if not self.is_shunzi(self.player1) and not self.is_shunzi(self.player2):            return None        # 都是顺子的话比较大小        if self.is_shunzi(self.player1) and self.is_shunzi(self.player2):            data1 = self.get_value(self.player1)            data2 = self.get_value(self.player2)            return self.compare_value(data1, data2)

    def compare_pair(self):        """        两张点数相同的牌。例:223,334。        :param pai1:        :param pai2:        :return:        """        if self.is_pair(self.player1) and not self.is_pair(self.player2):            return 1        if not self.is_pair(self.player1) and self.is_pair(self.player2):            return 2        if not self.is_pair(self.player1) and not self.is_pair(self.player2):            return None        if self.is_pair(self.player1) and self.is_pair(self.player2):            data1 = self.get_value(self.player1)            data2 = self.get_value(self.player2)            f1, s1 = self.find_pair(self.player1)            f2, s2 = self.find_pair(self.player2)            if data1[f1] > data2[f2]:                return 1            elif data1[f1] < data2[f2]:                return 2            else:                data1.pop(f1)                data1.pop(s1)                data2.pop(f2)                data2.pop(s2)                if data1[0] > data2[0]:                    return 1                elif data1[0] < data2[0]:                    return 2                else:                    return 3

    def comapre_common(self):        """        # 这里是一般性的比较,不是豹子,顺子,金花等。        :return:        """        data1 = self.get_value(self.player1)        data2 = self.get_value(self.player2)        return self.compare_value(data1, data2)

    def compare(self):        player1, player2 = self.wrapper()        flag = self.compare_baozi()        if flag is not None:            return flag, player1, player2        flag = self.compare_shunjin()        if flag is not None:            return flag, player1, player2        flag = self.compare_jinhua()        if flag is not None:            return flag, player1, player2        flag = self.compare_shunzi()        if flag is not None:            return flag, player1, player2        flag = self.compare_pair()        if flag is not None:            return flag, player1, player2        flag = self.comapre_common()        if flag is not None:            return flag, player1, player2

    def wrapper(self):        player1 = []        for poker in self.player1:            player1.append(poker[‘color‘] + ‘_‘ + str(‘{0:02}‘.format(poker[‘value‘]))+‘.jpg‘)        player2 = []        for poker in self.player2:            player2.append(poker[‘color‘] + ‘_‘ + str(‘{0:02}‘.format(poker[‘value‘])) + ‘.jpg‘)        return player1, player2

if __name__ == ‘__main__‘:    rule = Rule()    print(rule.compare())

视图与配置

import osimport sysfrom django.shortcuts import renderfrom django.conf.urls import urlfrom django.conf import settingsfrom django.core.management import execute_from_command_linefrom rule import Rule

BASE_DIR = os.path.dirname(__file__) # 定义当前工程目录为basedir

# 设置框架配置settings.configure(    DEBUG=True,    ALLOWED_HOSTS=[‘*‘],    SECRET_KEY=‘aaa‘,  # 用于加密的字符串    ROOT_URLCONF=__name__,  # 此配置为在当前文件里面找url映射的配置    MIDDLEWARE_CLASSES=(        ‘django.middleware.commom.CommonMiddleware‘,        ‘django.middleware.csrf.CsrfViewMiddleware‘,        ‘django.middleware.clickjacking.XFrameOptionsMiddleware‘,    ),    STATIC_URL=‘/static/‘,  # 定义静态文件的存放目录,和flask一致    STATICFILES_DIRS=(os.path.join(BASE_DIR, ‘static‘),),  # 静态文件目录,指向BASE_DIR/static(括号里的逗号不能省)    INSTALLED_APPS=(‘django.contrib.staticfiles‘,),  # Django使用静态文件需要安装即在配置中录入此信息(括号里的逗号不能省)    # 模板的配置    TEMPLATES=[{            # ‘BACKEND‘: ‘django.template.backends.django.DjangoTemplates‘,  # Django自带的模板引擎            ‘BACKEND‘: ‘django.template.backends.jinja2.Jinja2‘,  # Jinja2的模板引擎            ‘APP_DIRS‘: True,  # APP_DIRS为True则默认app下的templates目录,否则使用下一行DIRS声明的目录            ‘DIRS‘: [os.path.join(BASE_DIR, ‘templates‘)],            ‘OPTIONS‘: {}}])

def game(request):    rule = Rule()    status, player1, player2 = rule.compare()    context = {        ‘status‘: status,        ‘player1‘: player1,        ‘player2‘: player2,    }    return render(request, ‘game.html‘, context)

# 通过正则匹配url,做视图映射urlpatterns = (    url(r‘^game$‘, game),    )if __name__ ==  ‘__main__‘:    execute_from_command_line(sys.argv)

访问

原文地址:https://www.cnblogs.com/zhongyehai/p/10952221.html

时间: 2024-10-02 06:12:38

测开之路四十九:用Django实现扑克牌游戏的相关文章

测开之路四十八:Django之重定向与cookie

基础配置与上一篇一致 404错误 定义一个error页面 <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>错误页</title></head><body> <h1>哎呀,出错啦!</h1></body></html> 追加一个404的视图

测开之路七十九:性能测试蓝图之执行逻辑

import osimport csvimport json from kafka import KafkaProducerfrom kafka import KafkaConsumer from common.mongo import Mongofrom common import get_case_id class Logic(object): def __init__(self): pass def start(self, data): """ 这是投递消息函数,只负责

测开之路七十四:python处理kafka

kafka-python地址:https://github.com/dpkp/kafka-python 安装kafka-python:pip install kafka-python 接收消息 from kafka import KafkaConsumerconsumer = KafkaConsumer('test', bootstrap_servers=['localhost:9092']) # 定义消费者for msg in consumer: print(msg) 发条消息尝试接收,结果是

测开之路二十五:彩票游戏

玩法 import random money = random.randint(0, 999) def generate_code(money): return list(set([ money[0] + money[1] + money[2], money[0]+money[2]+money[1], money[1] + money[0] + money[2], money[1] + money[2] + money[0], money[2] + money[0] + money[1], mo

测开之路七十六:性能测试蓝图之html

<!-- 继承base模板 -->{% extends 'base.html' %} {% block script %} <!-- 从cdn引入ace edter的js --> <script src="https://cdn.bootcss.com/ace/1.4.5/ace.js"></script> <script src="https://cdn.bootcss.com/ace/1.4.5/mode-python

测开之路七十八:性能测试蓝图之视图层

from flask import requestfrom flask import jsonifyfrom flask import Blueprintfrom flask import render_templatefrom performance.logic import Logic performance = Blueprint('performance', __name__, static_folder='static', template_folder='templates', ur

测开之路二十六:Flask基础之最小web程序

Flask中文文档:http://docs.jinkan.org/docs/flask/ 安装Flask库 选端口号的一种方法(避免和别人选的端口冲突,小于1024的时候重新选) 最小web程序 用127.0.0.1或者localhost访问 返回html标签 原文地址:https://www.cnblogs.com/zhongyehai/p/10816624.html

测开之路三十五:css引入

CSS是一种定义样式结构,如字体.颜色.位置等的语言,被用于描述网页上的信息格式化和现实的方式.CSS样式可以直接存储于HTML网页或者单独的样式单文件.无论哪一种方式,样式单包含将样式应用到指定类型的元素的规则.外部使用时,样式单规则被放置在一个带有文件扩展名css的外部样式单文档中. css引入方式: 1.div标签 2.style标签,在head里面声明给某一个标签加样式,如果body里面的改标签没有特别声明样式,将全部展示为同一声明的样式,类似于继承与重写的关系 3.link标签:外链导

测开之路三十六:常用的css选择器

在static下新建一个css,并写入内容 /*标签选择器,label标签的颜色为红色*/label {color: red;} /*.代表类选择器,绿色*/.test {color: green;} /*#代表id选择器,黄色*/#test {color: yellow;} /*div标签下的魔偶写标签下的lable标签(相对关系),内容的颜色为蓝色*/div label {color: blue;} /*div标签下的直接的lable标签(父子关系),,灰色*/div > label {co