Python 小游戏 五子棋代码分享

 游戏运行效果示意(棋盘,棋子图片素材可自行寻找替换,适当美化一下)

代码思路参考自抖音视频五子棋教学视频,见https://www.douyin.com/user/MS4wLjABAAAAWgmhukssFWXxzArNArQejW7ZaQr-iUOy5f3GmgnLtDo?modal_id=7244428234979413282&vid=7244428234979413282

#五子棋小游戏,非本人原创
import pygame as pg
#定义落子函数
def set(x,y,color):
    if board[x][y]!=" ":
        print("该位置已有棋子!")
        return False
    else:
        board[x][y]=color
        return True
#检查一行中是否五子成线
def check1(board):
    for list in board:
        if "".join(list).find("0"*5)!=-1:
            print("白棋获胜!")
            return 0
        elif "".join(list).find("X"*5)!=-1:
            print("黑棋获胜!")
            return 1
    else:
        return -1
#检查行,列,正斜,反斜
def check_win(board):
    board_a=[[]for line in range(29)]
    for x in range(15):
        for y in range(15):
            board_a[x-y].append(board[x][y])
    board_b=[[]for line in range(29)]
    for x in range(15):
        for y in range(15):
            board_b[x+y].append(board[x][y])
    return [check1(board),check1([list(l) for l in zip(*board)]),check1(board_a),check1(board_b)]
def main():
    pg.init()
    clock=pg.time.Clock()
    screen=pg.display.set_mode((width,height))
    black=pg.image.load("黑.png").convert_alpha()
    white = pg.image.load("白.png").convert_alpha()
    background=pg.image.load("11.png").convert_alpha()#导入图片素材
    pg.display.set_caption("五子棋")
    objects=[]
    flag=0
    going=True
    chess_list=[black,white]
    letter_list=["X","0"]
    while going:
        screen.blit(background,(0,0))
        for event in pg.event.get():
            if event.type==pg.QUIT:
                going=False
            elif event.type==pg.KEYDOWN and event.key==pg.K_ESCAPE:
                going=False
            elif event.type==pg.MOUSEBUTTONDOWN:
                pos=pg.mouse.get_pos()#监视鼠标动作与位置
                a,b=round((pos[0]-27)/40),round((pos[1]-27)/40)
                x,y=max(0,a)if a<0 else min(a,14),max(0,b)if b<0 else min(b,14)
                if set(x,y,letter_list[flag]):
                    objects.append([chess_list[flag],(9+x*40,9+y*40)])
                    flag=[1,0][flag]
                    if 0 in check_win(board) or 1 in check_win(board):
                        going=False
        for o in objects:
            screen.blit(o[0],o[1])
        clock.tick(144)
        pg.display.update()
if __name__=="__main__":
    width=615
    height=615
    board=[[" "]*15 for line in range(15)]
    main()
    pg.quit()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值