ホームページ バックエンド開発 Python チュートリアル 使用Python编写一个简单的tic-tac-toe游戏的教程

使用Python编写一个简单的tic-tac-toe游戏的教程

Jun 06, 2016 am 11:25 AM
python

 这个教程,我们将展示如何用python创建一个井字游戏。 其中我们将使用函数、数组、if条件语句、while循环语句和错误捕获等。

首先我们需要创建两个函数,第一个函数用来显示游戏板:
 

def print_board():
  for i in range(0,3):
    for j in range(0,3):
      print map[2-i][j],
      if j != 2:
        print "|",
    print ""
ログイン後にコピー

这我们使用两个for循环来遍历map,该map是一个包含了位置信息的二维数组。

游戏板看起来是这样的:

|  | 
|  | 
|  |
 
X | X | 
O | X | O
 | O | X
 
X | X | X
X | X | X
X | X | X
ログイン後にコピー


下面我们需要一个函数check_done()来检查游戏是否结束。如果结束,则返回True并打印消息。

def check_done():
  for i in range(0,3):
    if map[i][0] == map[i][1] == map[i][2] != " " \
    or map[0][i] == map[1][i] == map[2][i] != " ":
      print turn, "won!!!"
      return True
     
  if map[0][0] == map[1][1] == map[2][2] != " " \
  or map[0][2] == map[1][1] == map[2][0] != " ":
    print turn, "won!!!"
    return True
 
  if " " not in map[0] and " " not in map[1] and " " not in map[2]:
    print "Draw"
    return True
     
  return False
ログイン後にコピー

有几个地方需要检查,首先检查水平和垂直方向,是否有一行或一列不为空且包含有三个相同的符号,然后我们再检查斜方向。如果上面有一个方向满足,游戏结束并打印“Won!!!”。请注意检查变量改变,它用来标记当前是哪一位玩家。

同时我们需要检查当前游戏板是否被填满且没有人获胜,游戏平局。

有了上面的两个函数,下面我们创建3个变量:

turn = "X"
map = [[" "," "," "],
    [" "," "," "],
    [" "," "," "]]
done = False
ログイン後にコピー

turn : 轮到谁
map : 游戏板
done : 游戏是否结束

现在启动游戏:

while done != True:
  print_board()
   
  print turn, "'s turn"
  print
 
  moved = False
  while moved != True:
ログイン後にコピー

这里使用了while循环直到游戏结束并返回true.在这个循环里面,使用了另外一个while循环来检查玩家是否移动,如果玩家没有移动,则程序会跳到下一次循环。

下一步告诉玩家怎么玩:

print "Please select position by typing in a number between 1 and 9, see below for which number that is which position..."
    print "7|8|9"
    print "4|5|6"
    print "1|2|3"
    print
 
try:
      pos = input("Select: ")
      if pos <=9 and pos >=1:
ログイン後にコピー

我们期望玩家输入一个数字,检查该数字是否是在1到9之间。另外,我们这里需要一段错误处理逻辑,我们还需要需要检查玩家是否能移动到一个位置:

Y = pos/3
        X = pos%3
        if X != 0:
          X -=1
        else:
           X = 2
           Y -=1
ログイン後にコピー

以下是全部的代码:

def print_board():
  for i in range(0,3):
    for j in range(0,3):
      print map[2-i][j],
      if j != 2:
        print "|",
    print ""
 
 
def check_done():
  for i in range(0,3):
    if map[i][0] == map[i][1] == map[i][2] != " " \
    or map[0][i] == map[1][i] == map[2][i] != " ":
      print turn, "won!!!"
      return True
     
  if map[0][0] == map[1][1] == map[2][2] != " " \
  or map[0][2] == map[1][1] == map[2][0] != " ":
    print turn, "won!!!"
    return True
 
  if " " not in map[0] and " " not in map[1] and " " not in map[2]:
    print "Draw"
    return True
     
 
  return False
 
 
 
 
 
turn = "X"
map = [[" "," "," "],
    [" "," "," "],
    [" "," "," "]]
done = False
 
 
while done != True:
  print_board()
   
  print turn, "'s turn"
  print
 
  moved = False
  while moved != True:
    print "Please select position by typing in a number between 1 and 9,\
    see below for which number that is which position..."
    print "7|8|9"
    print "4|5|6"
    print "1|2|3"
    print
 
    try:
      pos = input("Select: ")
      if pos <=9 and pos >=1:
        Y = pos/3
        X = pos%3
        if X != 0:
          X -=1
        else:
           X = 2
           Y -=1
           
        if map[Y][X] == " ":
          map[Y][X] = turn
          moved = True
          done = check_done()
 
          if done == False:
            if turn == "X":
              turn = "O"
            else:
              turn = "X"
         
       
    except:
      print "You need to add a numeric value"
ログイン後にコピー

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

テンプレートのメリットとデメリットは何ですか? テンプレートのメリットとデメリットは何ですか? May 08, 2024 pm 03:51 PM

テンプレートのメリットとデメリットは何ですか?

Google AI、開発者向けに Gemini 1.5 Pro と Gemma 2 を発表 Google AI、開発者向けに Gemini 1.5 Pro と Gemma 2 を発表 Jul 01, 2024 am 07:22 AM

Google AI、開発者向けに Gemini 1.5 Pro と Gemma 2 を発表

Deepseek Xiaomiをダウンロードする方法 Deepseek Xiaomiをダウンロードする方法 Feb 19, 2025 pm 05:27 PM

Deepseek Xiaomiをダウンロードする方法

いくつかの .NET オープンソース AI および LLM 関連プロジェクト フレームワークを共有する いくつかの .NET オープンソース AI および LLM 関連プロジェクト フレームワークを共有する May 06, 2024 pm 04:43 PM

いくつかの .NET オープンソース AI および LLM 関連プロジェクト フレームワークを共有する

どうやって彼にdeepseekに尋ねますか どうやって彼にdeepseekに尋ねますか Feb 19, 2025 pm 04:42 PM

どうやって彼にdeepseekに尋ねますか

評価関数の保存方法 評価関数の保存方法 May 07, 2024 am 01:09 AM

評価関数の保存方法

NET40とはどのようなソフトウェアですか? NET40とはどのようなソフトウェアですか? May 10, 2024 am 01:12 AM

NET40とはどのようなソフトウェアですか?

DeepSeekを検索する方法 DeepSeekを検索する方法 Feb 19, 2025 pm 05:18 PM

DeepSeekを検索する方法

See all articles