首页 > 编程语言 >Python 分享

Python 分享

时间:2023-09-26 15:33:47浏览次数:41  
标签:target Python move source print 分享 card tableaus

五子棋游戏

# 定义棋盘大小
size = 15
# 定义棋盘
chessboard = [['+' for _ in range(size)] for _ in range(size)]
# 定义当前玩家,初始为黑棋
current_player = 'black'

# 打印棋盘
def print_board(chessboard):
    for row in chessboard:
        print(' '.join(row))

# 检查是否五子连珠
def check_win(chessboard, row, col):
    directions = [(1, 0), (0, 1), (1, 1), (-1, 1)] # 横向、纵向、斜向检查
    for d in directions:
        count = 1
        for i in range(1, 5):
            new_row = row + i * d[0]
            new_col = col + i * d[1]
            if 0 <= new_row < size and 0 <= new_col < size and chessboard[new_row][new_col] == chessboard[row][col]:
                count += 1
            else:
                break
        for i in range(1, 5):
            new_row = row - i * d[0]
            new_col = col - i * d[1]
            if 0 <= new_row < size and 0 <= new_col < size and chessboard[new_row][new_col] == chessboard[row][col]:
                count += 1
            else:
                break
        if count >= 5:
            return True
    return False

# 开始游戏
def play():
    while True:
        print_board(chessboard)
        print(current_player + " player's turn.")
        move = input("Please enter your move (row, col): ")
        try:
            row, col = map(int, move.split(','))
            if 0 <= row < size and 0 <= col < size and chessboard[row][col] == '+':
                chessboard[row][col] = 'O' if current_player == 'black' else 'X'
                if check_win(chessboard, row, col):
                    print_board(chessboard)
                    print(current_player + " player wins!")
                    break
                current_player = 'white' if current_player == 'black' else 'black'
            else:
                print("Invalid move. Please try again.")
        except ValueError:
            print("Invalid input. Please enter row and column separated by comma.")

# 开始游戏
play()

蜘蛛纸牌

import random

# 定义纸牌花色和面值
suits = ['♠', '♥', '♦', '♣']
ranks = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']

# 创建一副标准的纸牌
deck = [rank + suit for suit in suits for rank in ranks]

# 混洗纸牌
random.shuffle(deck)

# 定义牌堆
tableaus = [[] for _ in range(10)]  # 10个牌堆
foundations = [[] for _ in range(8)]  # 8个基础牌堆

# 发牌
for i in range(4):
    for j in range(5):
        tableaus[j].append(deck.pop())

# 显示牌局
def display_game():
    print("Tableaus:")
    for i, tableau in enumerate(tableaus):
        print(f"{i+1}: {' '.join(tableau)}")
    print("\nFoundations:")
    for i, foundation in enumerate(foundations):
        print(f"{chr(65+i)}: {' '.join(foundation)}")

# 移动牌
def move_card(source, target):
    card = tableaus[source].pop()
    tableaus[target].append(card)

# 判断移动是否合法
def is_valid_move(source, target):
    if source == target:
        return False
    if len(tableaus[source]) == 0:
        return False
    if len(tableaus[target]) == 0:
        return True
    source_card = tableaus[source][-1]
    target_card = tableaus[target][-1]
    source_rank, source_suit = source_card[:-1], source_card[-1]
    target_rank, target_suit = target_card[:-1], target_card[-1]
    if suits.index(source_suit) % 2 != suits.index(target_suit) % 2 and ranks.index(source_rank) + 1 == ranks.index(target_rank):
        return True
    return False

# 对输入进行解析
def parse_input(input_str):
    source_str, target_str = input_str.split()
    source = int(source_str) - 1
    target = ord(target_str.upper()) - 65
    return source, target

# 游戏主循环
def play():
    while True:
        display_game()
        move = input("Please enter your move (source target): ")
        try:
            source, target = parse_input(move)
            if is_valid_move(source, target):
                move_card(source, target)
            else:
                print("Invalid move. Please try again.")
            if len(deck) == 0 and all(len(tableau) == 0 for tableau in tableaus):
                print("Congratulations! You win!")
                break
        except ValueError:
            print("Invalid input. Please enter source and target separated by a space.")

# 开始游戏
play()

标签:target,Python,move,source,print,分享,card,tableaus
From: https://blog.51cto.com/u_16251486/7609181

相关文章

  • VSCode python代码不高亮
    例如:我最近在通过remote-ssh插件连接远程服务器使用时经常碰到这种情况首先检查vscode中是否安装了拓展Pylance和Python当然我这里已经安装解决方法:先卸载原先的Pylance和Python拓展,而后再安装Pylance拓展(Python拓展会因此自动安装),而后等待半分钟左右vscode重新加载代......
  • Top 10 开发者分享漂亮代码美化截图的在线工具
    作为一名程序员,您大部分时间都花在创建代码上。如果您在团队中工作或需要反馈,您可以与同事共享您的代码。无论你的代码写得多好,它仍然看起来很乏味。仅仅因为有一行又一行的技术术语,并不意味着你不能美化它。您需要的是一个代码片段图像生成器。这是一个非常聪明的工具,可以将代......
  • 《流畅的Python》 读书笔记 230926
    写在最前面的话缘由关于Python的资料市面上非常多,好的其实并不太多。个人认为,基础的,下面的都还算可以B站小甲鱼黑马的视频刘江的博客廖雪峰的Python课程进阶的更少,《流畅的Python》应该算一个。加上,自己也很久没有耐心的看完一本书了鉴于以上2点,2023-9-26开始在这里跟......
  • mac M2 python 逆向解析二维码
    首先使用大家推荐的zbarmacm2python3.8安装无法解析动态库安装arch-arm64brewinstallzbarpython使用frompyzbar.pyzbarimportdecodefromPILimportImageif__name__=='__main__':file='qrcode_prod/492C230613047659_XCXM015492.png'......
  • 在线问诊 Python、FastAPI、Neo4j — 提供接口服务
    目录构建服务层接口路由层PostMan调用采用FastAPI搭建服务接口:https://www.cnblogs.com/vipsoft/p/17684079.htmlFastAPI文档:https://fastapi.tiangolo.com/zh/构建服务层qa_service.pyfromservice.question_classifierimport*fromservice.question_parserimpor......
  • 【python】只需一段代码,剪辑一个视频——Moviepy详解
    http://www.shanhubei.com/archives/2757.html前言知道吗,用moviepy一行代码就能够快速剪辑视频中某个区间的片段:clip=VideoFileClip(“videoplayback.mp4”).subclip(50,60)这一段代码,能够在3秒内将videoplayback.mp4的50秒-60秒的视频片段提取出来,非常方便。仅如此,movie......
  • Python学习笔记
    pip安装包命令pipinstallnumpy-ihttps://pypi.douban.com/simple#安装(指定国内源来安装)pipinstall--upgradenumpy#升级pipuninstallnumpy#卸载piplist#查看piplist-o#查看需要被升级的包pipshow-fnumpy#查看某个包的信息pipchecknumpy#查看兼容问......
  • 在线问诊 Python、FastAPI、Neo4j — 问题反馈
    目录查出节点拼接节点属性测试结果问答演示通过节点关系,找出对应的节点,获取节点属性值,并拼接成想要的结果。接上节生成的CQL#输入question_class={'args':{'看东西有时候清楚有时候不清楚':['symptom']},'question_types':['symptom_disease']}#输出[{'question_typ......
  • 如何在Python中实现高效的数据处理与分析
    在当今信息爆炸的时代,我们面对的数据量越来越大,如何高效地处理和分析数据成为了一种迫切的需求。Python作为一种强大的编程语言,提供了丰富的数据处理和分析库,帮助我们轻松应对这个挑战。本文将为您介绍如何在Python中实现高效的数据处理与分析,以提升工作效率和数据洞察力。1、数据......
  • Python之html2text:将HTML转换为Markdown文档示例详解
    From: https://mp.weixin.qq.com/s/Pa3NDXOseyg0mIn869mbhQ-----------------------------------------------------------------------------------------hello大家好我是Monday,本文将详细介绍如何使用Python库中的html2text模块来实现将HTML转换为Markdown的操作,并提供示例......