搜尋
首頁後端開發Python教學Python直列怎麼做遊戲

Python直列怎麼做遊戲

Jul 20, 2019 am 10:48 AM
python

PyGame是一個Python的函式庫,能夠讓你更容易的寫出一個遊戲。它提供的功能包括圖片處理和聲音重播的功能,它們能輕鬆的整合進你的遊戲裡。

Python直列怎麼做遊戲

下面是五子棋的程式碼,我的理解都寫在註解裡了(推薦學習:Python影片教學

import pygame
# 导入pygame模块
print(pygame.ver)
# 检查pygame的版本,检查pygame有没有导入成功

EMPTY = 0
BLACK = 1
WHITE = 2
# 定义三个常量函数,用来表示白棋,黑棋,以及 空

black_color = [0, 0, 0]
# 定义黑色(黑棋用,画棋盘)
white_color = [255, 255, 255]
# 定义白色(白棋用)

# 定义棋盘这个类
class RenjuBoard(object):

  def __init__(self):
    # self._board = board = [[EMPTY] * 15 for _ in range(15)]
    # 将棋盘每一个交叉点都看作列表的一个元素位,一共有15*15共225个元素
    self._board = [[]] * 15
    self.reset()
  #重置棋盘
  def reset(self):
    for row in range(len(self._board)):
      self._board[row] = [EMPTY] * 15
  #定义棋盘上的下棋函数,row表示行,col表示列,is_black表示判断当前点位该下黑棋,还是白棋
  def move(self, row, col, is_black):
    if self._board[row][col] == EMPTY:
      self._board[row][col] = BLACK if is_black else WHITE
      return True
    return False
  # 给棋盘定义一个函数将自己在screen上面画出来,使用pygame.draw()函数。并且顺便将下了的棋子也画出来
  def draw(self, screen):
    for h in range(1, 16):
      pygame.draw.line(screen, black_color,
               [40, h * 40], [600, h * 40], 1)
      pygame.draw.line(screen, black_color,
    # 给棋盘加一个外框,使美观
    pygame.draw.rect(screen, black_color, [36, 36, 568, 568], 3)
    # 在棋盘上标出,天元以及另外4个特殊点位
    pygame.draw.circle(screen, black_color, [320, 320], 5, 0)
    pygame.draw.circle(screen, black_color, [160, 160], 3, 0)
    pygame.draw.circle(screen, black_color, [160, 480], 3, 0)
    pygame.draw.circle(screen, black_color, [480, 160], 3, 0)
    pygame.draw.circle(screen, black_color, [480, 480], 3, 0)
    #做2次for循环取得棋盘上所有交叉点的坐标
    for row in range(len(self._board)):
      for col in range(len(self._board[row])):
        # 将下在棋盘上的棋子画出来
        if self._board[row][col] != EMPTY:
          ccolor = black_color \
            if self._board[row][col] == BLACK else white_color
          # 取得这个交叉点下的棋子的颜色,并将棋子画出来
          pos = [40 * (col + 1), 40 * (row + 1)]
          # 画出棋子
          pygame.draw.circle(screen, ccolor, pos, 18, 0)

# 定义函数,传入当前棋盘上的棋子列表,输出结果,不管黑棋白棋胜,都是传回False,未出结果则为True
def is_win(board):
  for n in range(15):
    # 判断垂直方向胜利
    flag = 0
    # flag是一个标签,表示是否有连续以上五个相同颜色的棋子
    for b in board._board:
      if b[n] == 1:
        flag += 1
        if flag == 5:
          print('黑棋胜')
          return False
      else:
      # else表示此时没有连续相同的棋子,标签flag重置为0
        flag = 0

    flag = 0
    for b in board._board:
      if b[n] == 2:
        flag += 1
        if flag == 5:
          print('白棋胜')
          return False
      else:
        flag = 0

    # 判断水平方向胜利
    flag = 0
    for b in board._board[n]:
      if b == 1:
        flag += 1
        if flag == 5:
          print('黑棋胜')
          return False
      else:
        flag = 0

    flag = 0
    for b in board._board[n]:
      if b == 2:
        flag += 1
        if flag == 5:
          print('白棋胜')
          return False
      else:
        flag = 0

    # 判断正斜方向胜利

    for x in range(4, 25):
      flag = 0
      for i,b in enumerate(board._board):
        if 14 >= x - i >= 0 and b[x - i] == 1:
          flag += 1
          if flag == 5:
            print('黑棋胜')
            return False
        else:
          flag = 0

    for x in range(4, 25):
      flag = 0
      for i,b in enumerate(board._board):
        if 14 >= x - i >= 0 and b[x - i] == 2:
          flag += 1
          if flag == 5:
            print('白棋胜')
            return False
        else:
          flag = 0

    #判断反斜方向胜利
    for x in range(11, -11, -1):
      flag = 0
      for i,b in enumerate(board._board):
        if 0 <p>更多Python相關技術文章,請造訪<a href="https://www.php.cn/python-tutorials.html" target="_self">Python教學</a>欄位進行學習! </p>

以上是Python直列怎麼做遊戲的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
Python:編譯器還是解釋器?Python:編譯器還是解釋器?May 13, 2025 am 12:10 AM

Python是解釋型語言,但也包含編譯過程。 1)Python代碼先編譯成字節碼。 2)字節碼由Python虛擬機解釋執行。 3)這種混合機制使Python既靈活又高效,但執行速度不如完全編譯型語言。

python用於循環與循環時:何時使用哪個?python用於循環與循環時:何時使用哪個?May 13, 2025 am 12:07 AM

UseeAforloopWheniteratingOveraseQuenceOrforAspecificnumberoftimes; useAwhiLeLoopWhenconTinuingUntilAcIntiment.forloopsareIdealForkNownsences,而WhileLeleLeleLeleLeleLoopSituationSituationsItuationsItuationSuationSituationswithUndEtermentersitations。

Python循環:最常見的錯誤Python循環:最常見的錯誤May 13, 2025 am 12:07 AM

pythonloopscanleadtoerrorslikeinfiniteloops,modifyingListsDuringteritation,逐個偏置,零indexingissues,andnestedloopineflinefficiencies

對於循環和python中的循環時:每個循環的優點是什麼?對於循環和python中的循環時:每個循環的優點是什麼?May 13, 2025 am 12:01 AM

forloopsareadvantageousforknowniterations and sequests,供應模擬性和可讀性;而LileLoopSareIdealFordyNamicConcitionSandunknowniterations,提供ControloperRoverTermination.1)forloopsareperfectForeTectForeTerToratingOrtratingRiteratingOrtratingRitterlistlistslists,callings conspass,calplace,cal,ofstrings ofstrings,orstrings,orstrings,orstrings ofcces

Python:深入研究彙編和解釋Python:深入研究彙編和解釋May 12, 2025 am 12:14 AM

pythonisehybridmodeLofCompilation和interpretation:1)thepythoninterpretercompilesourcecececodeintoplatform- interpententbybytecode.2)thepythonvirtualmachine(pvm)thenexecutecutestestestestestesthisbytecode,ballancingEaseofuseEfuseWithPerformance。

Python是一種解釋或編譯語言,為什麼重要?Python是一種解釋或編譯語言,為什麼重要?May 12, 2025 am 12:09 AM

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允許fordingfordforderynamictynamictymictymictymictyandrapiddefupment,儘管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

對於python中的循環時循環與循環:解釋了關鍵差異對於python中的循環時循環與循環:解釋了關鍵差異May 12, 2025 am 12:08 AM

在您的知識之際,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations則youneedtoloopuntilaconditionismet

循環時:實用指南循環時:實用指南May 12, 2025 am 12:07 AM

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境