Python雙人五子棋

来源:https://www.cnblogs.com/godforever/archive/2022/06/18/16389057.html
-Advertisement-
Play Games

這篇文章旨在介紹一個雙人的五子棋程式。再次重申,本人不擅長對代碼的可讀性進行優化,所以可能有些雜亂(在所難免)。 先瞅一眼效果圖: 請註意,這個棋子……是這麼圓潤立體!本程式不需任何素材圖片,完全用代碼繪製所需的圖像,因此這樣立體的棋子十分難能可貴。那麼,這究竟是如何做到的呢?別急,聽我慢慢道來。 ...


這篇文章旨在介紹一個雙人的五子棋程式。再次重申,本人不擅長對代碼的可讀性進行優化,所以可能有些雜亂(在所難免)。

先瞅一眼效果圖:

請註意,這個棋子……是這麼圓潤立體!本程式不需任何素材圖片,完全用代碼繪製所需的圖像,因此這樣立體的棋子十分難能可貴。那麼,這究竟是如何做到的呢?別急,聽我慢慢道來。

首先,一個好的程式必須配有高端大氣的文字。對於博大精深的中文,gbk或utf-8的編碼聲明自然是非常必要的。於是,就有了第一行代碼:

#coding:utf-8

然後,當然是模塊的導入。本次所需的模塊不多,只有sys、pygame和random。其中pygame需要用pip工具進行安裝。

import sys
import pygame
import random

接下來,我們定義一個函數:do(),裡面輸入我們所需要的代碼。至於為何要定義函數,這是因為在游戲結束後需要重新運行該程式,因而不可避免地要將全部的程式代碼輸入一個函數中,並調用這個函數。

def do():

然後,就是最重磅的棋子繪製函數,我們先看黑棋:

    def black(x, y):
        a = 30
        b = 30
        c = 30
        d = 8
        for i in range(50):
            pygame.draw.circle(screen, (a, b, c), [19.5 + 32 * x, 19.5 + 32 * y], 111 / d)
            a += 0.3
            b += 0.3
            c += 0.3
            d += 0.2
        pygame.display.update()

這裡的x和y是繪製黑棋的位置,暫且先不管。可以看到,這一個圓潤的棋子是有50個同心圓組成。這些同心圓的顏色逐個變淺,相鄰兩個圓的顏色差值不變。因此,我們只需要使圓的直徑(或半徑)呈曲線變化,就可以使繪製的棋子邊緣非常圓潤。作為一個初二的學生,我立馬想到了反比例函數。因此,“d=8”“111/d”和“d+=0.2”實際上是使同心圓的半徑隨迴圈變數的變化呈一個偏移的反比例函數,這樣就可以營造一種圓潤的視感。

同理,白棋的繪製也是遵循類似的方式。在此不在贅述,只給出代碼:

    def white(x, y):
        a = 200
        b = 200
        c = 200
        d = 8
        for i in range(50):
            pygame.draw.circle(screen, (a, b, c), [19.5 + 32 * x, 19.5 + 32 * y], 111 / d)
            a += 0.3
            b += 0.3
            c += 0.3
            d += 0.2
        pygame.display.update()

接下來,是冗長無味的棋盤繪製:

    pygame.init()
    screen = pygame.display.set_mode((615, 615))
    pygame.display.set_caption('五子棋')
    screen.fill("#DD954F")
    a = pygame.Surface((603, 603), flags=pygame.HWSURFACE)
    a.fill(color='#121010')
    b = pygame.Surface((585, 585), flags=pygame.HWSURFACE)
    b.fill(color="#DD954F")
    c = pygame.Surface((579, 579), flags=pygame.HWSURFACE)
    c.fill(color='#121010')
    d = pygame.Surface((576, 576), flags=pygame.HWSURFACE)
    d.fill(color="#DD954F")
    e = pygame.Surface((31, 31), flags=pygame.HWSURFACE)
    e.fill(color="#DD954F")
    screen.blit(a, (6.5, 6.5))
    screen.blit(b, (15, 15))
    screen.blit(c, (18, 18))
    for j in range(18):
        for i in range(18):
            screen.blit(e, (20 + 32 * i, 20 + 32 * j))
    alist = []
    for j in range(19):
        alistone = []
        for i in range(19):
            alistone.append(0)
        alist.append(alistone)
    pygame.draw.circle(screen, '#121010', [307.5, 307.5], 5)
    pygame.draw.circle(screen, '#121010', [115.5, 307.5], 5)
    pygame.draw.circle(screen, '#121010', [499.5, 307.5], 5)
    pygame.draw.circle(screen, '#121010', [115.5, 499.5], 5)
    pygame.draw.circle(screen, '#121010', [499.5, 499.5], 5)
    pygame.draw.circle(screen, '#121010', [115.5, 115.5], 5)
    pygame.draw.circle(screen, '#121010', [499.5, 115.5], 5)
    pygame.draw.circle(screen, '#121010', [307.5, 499.5], 5)
    pygame.draw.circle(screen, '#121010', [307.5, 115.5], 5)
    pygame.display.flip()

可以看到,我們先畫了一個花哨的邊框,然後畫上其中的格子,順便定義了一個被0填滿的19*19的二維列表(在此處似乎很冗餘,但到後面,你會發現它異常有用!)。最後,九個平平無奇的點被畫上了棋盤。

至此,我們的五子棋初見雛形。但是,要使用它進行對弈,這還遠遠不夠。

    wb = "black"
    font1 = pygame.font.SysFont('stxingkai', 70)
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.MOUSEBUTTONDOWN:
                x, y = pygame.mouse.get_pos()
                x = round((x - 19.5) / 32)
                y = round((y - 19.5) / 32)
                if x < 0:
                    x = 0
                if x > 18:
                    x = 18
                if y < 0:
                    y = 0
                if y > 18:
                    y = 18
                z = False
                if alist[x][y] == 0:
                    eval(wb + "({},{})".format(x, y))
                    if wb == "black":
                        alist[x][y] = 1
                        wb1 = "黑棋"
                        wb = "white"
                    elif wb == "white":
                        alist[x][y] = 2
                        wb1 = "白棋"
                        wb = "black"

這裡,就是最核心的對弈程式。首先我們進入主迴圈,並獲取事件。在這裡,我們除了對按下關閉按鈕進行了幾乎每個pygame程式都會進行的處理外,還對按下滑鼠事件進行了處理。首先,我們獲取滑鼠點擊的坐標,通過計算來得到對應的格點(這裡對不在格點上的點擊進行四捨五入,對棋盤之外的點擊自動匹配與其最近的格點)。然後,根據此時的先手方和計算得的格點運行black/white函數,繪製所需的棋子。

                    xx = x
                    yy = y
                    while True:
                        if xx == 0:
                            break
                        elif alist[xx][yy] != alist[x][y]:
                            xx += 1
                            break
                        else:
                            xx -= 1
                    num = 0
                    while True:
                        if xx == 18:
                            break
                        elif alist[xx][yy] != alist[x][y]:
                            break
                        else:
                            xx += 1
                            num += 1
                    if num >= 5:
                        pygame.font.init()
                        text = font1.render("{}贏了".format(wb1), True, (0, 0, 0))
                        textRect = text.get_rect()
                        textRect.center = (307.5, 307.5)
                        screen.blit(text, textRect)
                        pygame.display.flip()
                        while True:
                            for event in pygame.event.get():
                                if event.type == pygame.QUIT:
                                    pygame.quit()
                                    sys.exit()
                                if event.type == pygame.MOUSEBUTTONDOWN:
                                    do()
                    xx = x
                    yy = y
                    while True:
                        if yy == 0:
                            break
                        elif alist[xx][yy] != alist[x][y]:
                            yy += 1
                            break
                        else:
                            yy -= 1
                    num = 0
                    while True:
                        if yy == 18:
                            break
                        elif alist[xx][yy] != alist[x][y]:
                            break
                        else:
                            yy += 1
                            num += 1
                    if num >= 5:
                        pygame.font.init()
                        text = font1.render("{}贏了".format(wb1), True, (0, 0, 0))
                        textRect = text.get_rect()
                        textRect.center = (307.5, 307.5)
                        screen.blit(text, textRect)
                        pygame.display.flip()
                        while True:
                            for event in pygame.event.get():
                                if event.type == pygame.QUIT:
                                    pygame.quit()
                                    sys.exit()
                                if event.type == pygame.MOUSEBUTTONDOWN:
                                    do()
                    xx = x
                    yy = y
                    while True:
                        if xx == 0:
                            break
                        elif yy == 0:
                            break
                        elif alist[xx][yy] != alist[x][y]:
                            xx += 1
                            yy += 1
                            break
                        else:
                            xx -= 1
                            yy -= 1
                    num = 0
                    while True:
                        if xx == 18:
                            break
                        elif yy == 18:
                            break
                        elif alist[xx][yy] != alist[x][y]:
                            break
                        else:
                            xx += 1
                            yy += 1
                            num += 1
                    if num >= 5:
                        pygame.font.init()
                        text = font1.render("{}贏了".format(wb1), True, (0, 0, 0))
                        textRect = text.get_rect()
                        textRect.center = (307.5, 307.5)
                        screen.blit(text, textRect)
                        pygame.display.flip()
                        while True:
                            for event in pygame.event.get():
                                if event.type == pygame.QUIT:
                                    pygame.quit()
                                    sys.exit()
                                if event.type == pygame.MOUSEBUTTONDOWN:
                                    do()
                    xx = x
                    yy = y
                    while True:
                        if xx == 0:
                            break
                        elif yy == 18:
                            break
                        elif alist[xx][yy] != alist[x][y]:
                            xx += 1
                            yy -= 1
                            break
                        else:
                            xx -= 1
                            yy += 1
                    num = 0
                    while True:
                        if xx == 18:
                            break
                        elif yy == 0:
                            break
                        elif alist[xx][yy] != alist[x][y]:
                            break
                        else:
                            xx += 1
                            yy -= 1
                            num += 1
                    if num >= 5:
                        pygame.font.init()
                        text = font1.render("{}贏了".format(wb1), True, (0, 0, 0))
                        textRect = text.get_rect()
                        textRect.center = (307.5, 307.5)
                        screen.blit(text, textRect)
                        pygame.display.flip()
                        while True:
                            for event in pygame.event.get():
                                if event.type == pygame.QUIT:
                                    pygame.quit()
                                    sys.exit()
                                if event.type == pygame.MOUSEBUTTONDOWN:
                                    do()

這是冗長的勝負判斷,具體內容我自己也難以解釋(這個程式編了有一段時間了)。主要思路,是向各個方向尋找同色棋子的連接,並判斷是否滿五個棋。當然,不得不承認,這一段確實不太高明,似乎有別人發佈過比我更好的方案,感興趣的可以上網找找。

do()

這是程式的收尾,也就是對do()函數的運行。至此,整個程式完全結束。

完整代碼:

#coding:utf-8
import sys
import pygame
import random
def do():
    def black(x, y):
        a = 20
        b = 20
        c = 20
        d = 0
        for i in range(50):
            pygame.draw.circle(screen, (a, b, c), [19.5 + 32 * x, 19.5 + 32 * y], (10/(d-5)+10)*1.6)
            a += 1
            b += 1
            c += 1
            d += 0.08
        pygame.display.update()

    def white(x, y):
        a = 170
        b = 170
        c = 170
        d = 0
        for i in range(50):
            pygame.draw.circle(screen, (a, b, c), [19.5 + 32 * x, 19.5 + 32 * y], (10/(d-5)+10)*1.6)
            a += 1
            b += 1
            c += 1
            d += 0.08
        pygame.display.update()
    pygame.init()
    screen = pygame.display.set_mode((615, 615))
    pygame.display.set_caption('五子棋')
    screen.fill("#DD954F")
    a = pygame.Surface((603, 603), flags=pygame.HWSURFACE)
    a.fill(color='#121010')
    b = pygame.Surface((585, 585), flags=pygame.HWSURFACE)
    b.fill(color="#DD954F")
    c = pygame.Surface((579, 579), flags=pygame.HWSURFACE)
    c.fill(color='#121010')
    d = pygame.Surface((576, 576), flags=pygame.HWSURFACE)
    d.fill(color="#DD954F")
    e = pygame.Surface((31, 31), flags=pygame.HWSURFACE)
    e.fill(color="#DD954F")
    screen.blit(a, (6.5, 6.5))
    screen.blit(b, (15, 15))
    screen.blit(c, (18, 18))
    for j in range(18):
        for i in range(18):
            screen.blit(e, (20 + 32 * i, 20 + 32 * j))
    alist = []
    for j in range(19):
        alistone = []
        for i in range(19):
            alistone.append(0)
        alist.append(alistone)
    pygame.draw.circle(screen, '#121010', [307.5, 307.5], 5)
    pygame.draw.circle(screen, '#121010', [115.5, 307.5], 5)
    pygame.draw.circle(screen, '#121010', [499.5, 307.5], 5)
    pygame.draw.circle(screen, '#121010', [115.5, 499.5], 5)
    pygame.draw.circle(screen, '#121010', [499.5, 499.5], 5)
    pygame.draw.circle(screen, '#121010', [115.5, 115.5], 5)
    pygame.draw.circle(screen, '#121010', [499.5, 115.5], 5)
    pygame.draw.circle(screen, '#121010', [307.5, 499.5], 5)
    pygame.draw.circle(screen, '#121010', [307.5, 115.5], 5)
    pygame.display.flip()
    wb = "black"
    font1 = pygame.font.SysFont('stxingkai', 70)
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.MOUSEBUTTONDOWN:
                x, y = pygame.mouse.get_pos()
                x = round((x - 19.5) / 32)
                y = round((y - 19.5) / 32)
                if x < 0:
                    x = 0
                if x > 18:
                    x = 18
                if y < 0:
                    y = 0
                if y > 18:
                    y = 18
                z = False
                if alist[x][y] == 0:
                    eval(wb + "({},{})".format(x, y))
                    if wb == "black":
                        alist[x][y] = 1
                        wb1 = "黑棋"
                        wb = "white"
                    elif wb == "white":
                        alist[x][y] = 2
                        wb1 = "白棋"
                        wb = "black"
                    xx = x
                    yy = y
                    while True:
                        if xx == 0:
                            break
                        elif alist[xx][yy] != alist[x][y]:
                            xx += 1
                            break
                        else:
                            xx -= 1
                    num = 0
                    while True:
                        if xx == 18:
                            break
                        elif alist[xx][yy] != alist[x][y]:
                            break
                        else:
                            xx += 1
                            num += 1
                    if num >= 5:
                        pygame.font.init()
                        text = font1.render("{}贏了".format(wb1), True, (0, 0, 0))
                        textRect = text.get_rect()
                        textRect.center = (307.5, 307.5)
                        screen.blit(text, textRect)
                        pygame.display.flip()
                        while True:
                            for event in pygame.event.get():
                                if event.type == pygame.QUIT:
                                    pygame.quit()
                                    sys.exit()
                                if event.type == pygame.MOUSEBUTTONDOWN:
                                    do()
                    xx = x
                    yy = y
                    while True:
                        if yy == 0:
                            break
                        elif alist[xx][yy] != alist[x][y]:
                            yy += 1
                            break
                        else:
                            yy -= 1
                    num = 0
                    while True:
                        if yy == 18:
                            break
                        elif alist[xx][yy] != alist[x][y]:
                            break
                        else:
                            yy += 1
                            num += 1
                    if num >= 5:
                        pygame.font.init()
                        text = font1.render("{}贏了".format(wb1), True, (0, 0, 0))
                        textRect = text.get_rect()
                        textRect.center = (307.5, 307.5)
                        screen.blit(text, textRect)
                        pygame.display.flip()
                        while True:
                            for event in pygame.event.get():
                                if event.type == pygame.QUIT:
                                    pygame.quit()
                                    sys.exit()
                                if event.type == pygame.MOUSEBUTTONDOWN:
                                    do()
                    xx = x
                    yy = y
                    while True:
                        if xx == 0:
                            break
                        elif yy == 0:
                            break
                        elif alist[xx][yy] != alist[x][y]:
                            xx += 1
                            yy += 1
                            break
                        else:
                            xx -= 1
                            yy -= 1
                    num = 0
                    while True:
                        if xx == 18:
                            break
                        elif yy == 18:
                            break
                        elif alist[xx][yy] != alist[x][y]:
                            break
                        else:
                            xx += 1
                            yy += 1
                            num += 1
                    if num >= 5:
                        pygame.font.init()
                        text = font1.render("{}贏了".format(wb1), True, (0, 0, 0))
                        textRect = text.get_rect()
                        textRect.center = (307.5, 307.5)
                        screen.blit(text, textRect)
                        pygame.display.flip()
                        while True:
                            for event in pygame.event.get():
                                if event.type == pygame.QUIT:
                                    pygame.quit()
                                    sys.exit()
                                if event.type == pygame.MOUSEBUTTONDOWN:
                                    do()
                    xx = x
                    yy = y
                    while True:
                        if xx == 0:
                            break
                        elif yy == 18:
                            break
                        elif alist[xx][yy] != alist[x][y]:
                            xx += 1
                            yy -= 1
                            break
                        else:
                            xx -= 1
                            yy += 1
                    num = 0
                    while True:
                        if xx == 18:
                            break
                        elif yy == 0:
                            break
                        elif alist[xx][yy] != alist[x][y]:
                            break
                        else:
                            xx += 1
                            yy -= 1
                            num += 1
                    if num >= 5:
                        pygame.font.init()
                        text = font1.render("{}贏了".format(wb1), True, (0, 0, 0))
                        textRect = text.get_rect()
                        textRect.center = (307.5, 307.5)
                        screen.blit(text, textRect)
                        pygame.display.flip()
                        while True:
                            for event in pygame.event.get():
                                if event.type == pygame.QUIT:
                                    pygame.quit()
                                    sys.exit()
                                if event.type == pygame.MOUSEBUTTONDOWN:
                                    do()
do()

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • SQL的約束 概述 概念:約束是作用於表中欄位上的規則,用於限制存儲表中的數據; 目的:保證資料庫中數據的正確性、有效性、完整性; 常見的約束分類: 約束 描述 關鍵字 非空約束 限制該欄位的數據不能為null not null 唯一約束 保證該欄位的所有數據都是唯一的、不重覆的 unique 主鍵 ...
  • 自定義封裝分頁器組件之前需要知道的數據: 1.當前的頁碼 2.總共多少條數據 3.每頁展示多少條數據 4.連續頁碼數(5|7) 5.總頁數 計算連續頁碼數的起始值和結束值 //通過計算屬性來計算出來 computed:{ startNumAndEndNum(){ //首先先結構出我們需要的值(當前頁 ...
  • 定義指令的變化 根據vue3文檔的描述 https://v3.cn.vuejs.org/guide/migration/introduction.html#%E6%B8%B2%E6%9F%93%E5%87%BD%E6%95%B0 自定義指令的 API 已更改為與組件生命周期一致。 且 binding ...
  • 這裡給大家分享我在網上總結出來的一些知識,希望對大家有所幫助 在地圖開發過程中,坐標的轉換是很常用的功能,國內的話一般西安80(EPSG:4610)、北京54(EPSG:2433)轉WGS84比較多,不同坐標系轉換,只要知道EPSG碼,通過 Openlayers 的方法就可以轉換。 但是,像國內商用 ...
  • 樣才能拿到大廠的offer,沒有掌握絕對的技術,那麼就要不斷的學習 他是如何拿下阿裡等大廠的offer的呢,今天分享他的秘密武器,美團資深架構師整理的Java核心知識點,面試時面試官必問的知識點,篇章包括了很多知識點,其中包括了有基礎知識、Java集合、JVM、多線程併發、spring原理、微服務、 ...
  • 運算符 運算符介紹 算數運算符 運算符 運算 範例 結果 + 正號 +7 7 - 負號 b=11; -b -11 + 加 9+9 18 - 減 10-8 2 * 乘 7*8 56 除 9/9 1 % 取模(取餘) 11%9 2 ++ 自增(前):先運算後取值自增(後):先取值後運算 a=2;b=a; ...
  • 大家好,我是二哥。前高級技術專家 & 增長黑客,現一枚愛折騰的小小創業者,專註於 RPA & SaaS 軟體這塊。這次給大家帶來如何利用 RPA 實現自動化獲客 一、RPA 是什麼?難嗎? RPA 對大家來說,可能挺陌生的,其實它很簡單。 Robotic Process Automation(簡稱 ...
  • 原文鏈接:http://www.zhoubotong.site/post/50.html defer語句用於延遲函數調用,每次會把一個函數壓入棧中,函數返回前再把延遲的函數取出並執行。延遲函數可以有參數: 延遲函數的參數在defer語句出現時就已確定下來(傳值的就是當前值) return先賦值(對於 ...
一周排行
    -Advertisement-
    Play Games
  • C#TMS系統代碼-基礎頁面BaseCity學習 本人純新手,剛進公司跟領導報道,我說我是java全棧,他問我會不會C#,我說大學學過,他說這個TMS系統就給你來管了。外包已經把代碼給我了,這幾天先把增刪改查的代碼背一下,說不定後面就要趕鴨子上架了 Service頁面 //using => impo ...
  • 委托與事件 委托 委托的定義 委托是C#中的一種類型,用於存儲對方法的引用。它允許將方法作為參數傳遞給其他方法,實現回調、事件處理和動態調用等功能。通俗來講,就是委托包含方法的記憶體地址,方法匹配與委托相同的簽名,因此通過使用正確的參數類型來調用方法。 委托的特性 引用方法:委托允許存儲對方法的引用, ...
  • 前言 這幾天閑來沒事看看ABP vNext的文檔和源碼,關於關於依賴註入(屬性註入)這塊兒產生了興趣。 我們都知道。Volo.ABP 依賴註入容器使用了第三方組件Autofac實現的。有三種註入方式,構造函數註入和方法註入和屬性註入。 ABP的屬性註入原則參考如下: 這時候我就開始疑惑了,因為我知道 ...
  • C#TMS系統代碼-業務頁面ShippingNotice學習 學一個業務頁面,ok,領導開完會就被裁掉了,很突然啊,他收拾東西的時候我還以為他要旅游提前請假了,還在尋思為什麼回家連自己買的幾箱飲料都要叫跑腿帶走,怕被偷嗎?還好我在他開會之前拿了兩瓶芬達 感覺感覺前面的BaseCity差不太多,這邊的 ...
  • 概述:在C#中,通過`Expression`類、`AndAlso`和`OrElse`方法可組合兩個`Expression<Func<T, bool>>`,實現多條件動態查詢。通過創建表達式樹,可輕鬆構建複雜的查詢條件。 在C#中,可以使用AndAlso和OrElse方法組合兩個Expression< ...
  • 閑來無聊在我的Biwen.QuickApi中實現一下極簡的事件匯流排,其實代碼還是蠻簡單的,對於初學者可能有些幫助 就貼出來,有什麼不足的地方也歡迎板磚交流~ 首先定義一個事件約定的空介面 public interface IEvent{} 然後定義事件訂閱者介面 public interface I ...
  • 1. 案例 成某三甲醫預約系統, 該項目在2024年初進行上線測試,在正常運行了兩天後,業務系統報錯:The connection pool has been exhausted, either raise MaxPoolSize (currently 800) or Timeout (curren ...
  • 背景 我們有些工具在 Web 版中已經有了很好的實踐,而在 WPF 中重新開發也是一種費時費力的操作,那麼直接集成則是最省事省力的方法了。 思路解釋 為什麼要使用 WPF?莫問為什麼,老 C# 開發的堅持,另外因為 Windows 上已經裝了 Webview2/edge 整體打包比 electron ...
  • EDP是一套集組織架構,許可權框架【功能許可權,操作許可權,數據訪問許可權,WebApi許可權】,自動化日誌,動態Interface,WebApi管理等基礎功能於一體的,基於.net的企業應用開發框架。通過友好的編碼方式實現數據行、列許可權的管控。 ...
  • .Net8.0 Blazor Hybird 桌面端 (WPF/Winform) 實測可以完整運行在 win7sp1/win10/win11. 如果用其他工具打包,還可以運行在mac/linux下, 傳送門BlazorHybrid 發佈為無依賴包方式 安裝 WebView2Runtime 1.57 M ...