python类和对象实例(求pi和poker游戏)

部署运行你感兴趣的模型镜像

point类

import math

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def getDistance(self, other):
        distance = math.sqrt(math.pow(self.x - other.x, 2) + math.pow(self.y - other.y, 2))
        return distance

if __name__ == '__main__':
    point1 = Point(1,1)
    point2 = Point(2,2)
    print(point1.getDistance(point2))

圆类

from point import Point

class Circle:
    def __init__(self, radius, center: Point):
        self.radius = radius
        self.center = center

    def is_point_in_circle(self, point: Point):
        distance = self.center.getDistance(point)
        return distance <= self.radius

if __name__ == '__main__':
    center = Point(1, 1)
    circle = Circle(1, center)
    point2 = Point(1.5,1.5)
    print(circle.is_point_in_circle(point2))

main

import random

from circle import Circle
from point import Point

def estimate_pi():
    center = Point(1,1)
    circle = Circle(1, center)

    in_sum = 0
    sum_count = 1000000
    for _ in range(sum_count):
        x = random.random() * 2
        y = random.random() * 2
        p = Point(x, y)

        if circle.is_point_in_circle(p):
            in_sum += 1

    result = in_sum / sum_count
    pi_estimate = result * 4
    print(f"Estimated Pi:{pi_estimate}")

if __name__ == "__main__":
    estimate_pi()

card

class Card:
    def __init__(self, color, value):
        self.value = value
        self.color = color

    def __str__(self):
        strvalue = str(self.value)
        if self.value == 11:
            strvalue = 'J'
        elif self.value == 12:
            strvalue = 'Q'
        elif self.value == 13:
            strvalue = 'K'
        elif self.value == 14:
            strvalue = 'A'

        return self.color + str(strvalue)

    def __repr__(self):
        return self.__str__()

poker

import random

from card import Card


colorLst = ['红桃', '方片', '黑桃', '草花']

class Poke:
    def __init__(self):
        self.cards = []

        for color in colorLst:
            for value in range(10, 15):
                card = Card(color, value)
                self.cards.append(card)

    def output(self):
        index = 1
        for card in self.cards:
            print(card, end='\t')

            if index % 5 == 0:
                print()

            index += 1

    def shuffle(self):
        for idx in range(len(self.cards)):
            random_idx = random.randint(0, len(self.cards) - 1)
            self.cards[idx], self.cards[random_idx] = self.cards[random_idx], self.cards[idx]

        # random.shuffle(self.cards)

    def get_one_hand(self):
        self.shuffle()
        hands = self.cards[:5]
        return hands

    def get_one_card(self, idx):
        return self.cards[idx]

    def get_type(self, hands):
        bSameColor = False
        bShunZi = False
        cardColors = [card.color for card in hands]
        cardValues = [card.value for card in hands]

        cardValuesSet = set(cardValues)
        cardColorsSet = set(cardColors)

        dic = {}

        for w in hands:
            if w.value in dic.keys():
                count = dic[w.value]
                count += 1
                dic[w.value] = count
            else:
                dic[w.value] = 1

        if len(cardColorsSet) == 1:
            bSameColor = True

        cardValuesSorted = sorted(cardValues)

        if cardValuesSorted[4] - cardValuesSorted[0] == 4 and len(cardValuesSet) == 5:
            bShunZi = True

        if bSameColor and bShunZi:
            return '同花顺'
        if bSameColor:
            return '同花'
        if bShunZi:
            return '顺子'

        if len(cardValuesSet) == 4:
            return '一对'
        if len(cardValuesSet) == 5:
            return '杂牌'

        if len(cardValuesSet) == 2:
            if 4 in dic.values():
                return '四条'
            else:
                return '满堂红'

        if len(cardValuesSet) == 3:
            if 2 in dic.values():
                return '两对'
            else:
                return '三条'


if __name__ == '__main__':
    poke = Poke()
    poke.output()

    poke.shuffle()
    print('洗牌之后')
    poke.output()

    for _ in range(500):
        poke.shuffle()
        hands = poke.get_one_hand()

        print('分到的一手牌是', end='\t')
        for card in hands:
            print(card, end=' ')

        print('\n牌型是:', end='')
        print(poke.get_type(hands))
        if poke.get_type(hands) == '四条':
            break





game

from poker import Poke


def main():
    poker = Poke()
    mapPrize = {
        "同花顺": 100,
        "四条": 25,
        "满堂红": 10,
        "同花": 5,
        "顺子": 4,
        "三条": 3,
        "两对": 2,
        "一对": 0,
        "杂牌": -1
    }

    score = 10

    while score > 0:
        print("-----------------------")
        print("your current score:", score)

        # 下注
        bet = int(input("please bet your score(1-5): "))
        score -= bet

        hand = poker.get_one_hand()
        print("Your hand:", hand)

        # 换牌选择
        print("please input card no what you want to change (ex: 1 3 5)")
        print("0 for exit, enter key for no change")
        info = input("> ")

        if info == "0":
            break
        elif info.strip() == "":
            pass  # 不换牌
        else:
            arr = info.split(" ")
            for i, s in enumerate(arr):
                card_no = int(s) - 1
                hand[card_no] = poker.get_one_card(5 + i)

        print("Final hand:", hand)

        # 计算牌型
        hand_type = poker.get_type(hand)
        print("Type:", hand_type)

        prize = mapPrize[hand_type]
        print("Earn:", prize * bet)

        score += prize * bet

    print("Game over. Final score:", score)

if __name__ == '__main__':
    main()

统计单词出现次数

text = "hello world hello python world python hello chatgpt python"
words = text.split()

dic = {}

for w in words:
    if w in dic.keys():
        count = dic[w]
        count += 1
        dic[w] = count
    else:
        dic[w] = 1

for key, value in dic.items():
    print(f'{key}: {value}')

list和字典常用操作

list01 = [10,20,30,40,50,60,70,80,90,100]
list01[0]
10
list01[-1]
100
list01[1:5]
[20, 30, 40, 50]
for x in list01:
    print(x)
10
20
30
40
50
60
70
80
90
100
for idx, x in enumerate(list01):
    print(idx ,x)
0 10
1 20
2 30
3 40
4 50
5 60
6 70
7 80
8 90
9 100
80 in list01
True
list01.append(200)
list01
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200]
list01.insert(1,88)
list01
[10, 88, 20, 30, 40, 50, 60, 70, 80, 90, 100, 200]
list01.index(30)
3
list01.remove(40)
list01
[10, 88, 20, 30, 50, 60, 70, 80, 90, 100, 200]
list01.sort()
list01
[10, 20, 30, 50, 60, 70, 80, 88, 90, 100, 200]
list01.pop(2)
30
list01 
[10, 20, 50, 60, 70, 80, 88, 90, 100, 200]
list01.append(10)
list01
[10, 20, 50, 60, 70, 80, 88, 90, 100, 200, 10]

集合

s = set(list01)
s
{10, 20, 50, 60, 70, 80, 88, 90, 100, 200}
s.add(50)
s
{10, 20, 50, 60, 70, 80, 88, 90, 100, 200}
s.discard(10)
s
{20, 50, 60, 70, 80, 88, 90, 100, 200}
len(s)
9

字典

student_result = {}
student_result["张三"] = 344
student_result["李四"] = 321
student_result["王五"] = 345
student_result
{'张三': 344, '李四': 321, '王五': 345}
student_result['张三']
344
student_result.get('张三')
344
student_result['zhangsan'] = 90
student_result
{'张三': 344, '李四': 321, '王五': 345, 'zhangsan': 90}
student_result['张三'] = 666
student_result
{'张三': 666, '李四': 321, '王五': 345, 'zhangsan': 90}
student_result.pop('zhangsan')
90
student_result
{'张三': 666, '李四': 321, '王五': 345}
'张三' in student_result
True
666 in student_result.values()
True
for key, value in student_result.items():
    print(key, value)
张三 666
李四 321
王五 345



您可能感兴趣的与本文相关的镜像

Python3.11

Python3.11

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值