• 售前

  • 售后

热门帖子
入门百科

使用tkinter实现三子棋游戏

[复制链接]
贰十岁装成熟装s 显示全部楼层 发表于 2021-10-25 20:51:27 |阅读模式 打印 上一主题 下一主题
本文实例为大家分享了tkinter实现三子棋游戏的详细代码,供大家参考,详细内容如下
整体游戏很简朴。下棋,判断胜利大概平手。没有到场电脑下棋的算法。
游戏界面:

代码:
  1. import tkinter as tk
  2. from tkinter import messagebox, Label, Button
  3. from TicTacToeModel import TicTacToeModel
  4. import requests
  5. from PIL import ImageTk, Image
  6. from io import BytesIO
  7. class TicTacToeGUI:
  8. def __init__(self, root):
  9.   # Create the model instance ...
  10.   self.model = TicTacToeModel()
  11.   # Create a 2D list to hold an array of buttons ...
  12.   self.b = []
  13.   for row in range(self.model.boardSize):
  14.    q = []
  15.    for col in range(self.model.boardSize):
  16.     q.append(None)
  17.    self.b.append(q)
  18.   # You can now address b like a 2D matrix e.g. b[0][0]
  19.   # Create the GUI .....
  20.   menubar = tk.Menu()
  21.   menubar.add_command(label='ResetGame', command=self.resetGUI)
  22.   menubar.add_command(label='ResetImage', command=self.resetImg)
  23.   menubar.add_command(label='Quit', command=root.destroy)
  24.   root.config(menu=menubar)
  25.   self.frame1 = tk.Frame(root, width=400, height=300, bg="GREY", borderwidth=2)
  26.   self.frame2 = tk.Frame(root, width=400, height=200, bg="WHITE", borderwidth=2)
  27.   self.createGUIAssets()
  28.   self.createframe2()
  29.   self.frame2.pack()
  30.   self.frame1.pack()
  31.   messagebox.showinfo("Hello", "Human player to start!")
  32. def getImg(self):
  33.   headers = {
  34.    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36'
  35.   }
  36.   # img_src = ' https://api.ixiaowai.cn/api/api.php'
  37.   img_src = ' https://api.ixiaowai.cn/gqapi/gqapi.php'
  38.   response = requests.get(url=img_src, headers=headers)
  39.   # print(response)
  40.   image = Image.open(BytesIO(response.content))
  41.   x, y = image.size
  42.   y_s = 200
  43.   x_s = int(x * y_s / y)
  44.   img = image.resize((x_s, y_s), Image.ANTIALIAS)
  45.   image = ImageTk.PhotoImage(img)
  46.   return image
  47. def resetImg(self):
  48.   self.image = self.getImg()
  49.   self.Label.config(image=self.image)
  50. def createframe2(self):
  51.   self.image = self.getImg()
  52.   self.Label = tk.Label(self.frame2, image=self.image)
  53.   self.Label.pack()
  54.   # image.show()
  55. def createGUIAssets(self):
  56.   for x in range(self.model.boardSize):
  57.    self.frame1.columnconfigure(x, pad=20)
  58.    self.frame1.grid_rowconfigure(x, pad=20)
  59.   for row in range(self.model.boardSize):
  60.    for col in range(self.model.boardSize):
  61.     self.b[row][col] = Button(self.frame1, text='', bg='WHITE',
  62.            relief='groove', borderwidth=20,
  63.            height=3, width=8,
  64.            command=lambda row=row, col=col: self.takeTurn(row, col))
  65.     self.b[row][col].grid(row=row, column=col)
  66. def takeTurn(self, row, col):
  67.   if not self.model.playSpace(row, col):
  68.    return
  69.   else:
  70.    self.b[row][col].configure(bg="Green")
  71.    status = self.model.checkWinStatus()
  72.    if status == 1: # Player win
  73.     messagebox.showinfo("Result", "Player wins!!!!")
  74.     self.resetGUI()
  75.    elif status == 0: # Draw
  76.     messagebox.showinfo("Result", "Draw!!!!")
  77.     self.resetGUI()
  78.    elif status == -2: # On going ...
  79.     (r, c) = self.model.computerTurn()
  80.     self.b[r][c].configure(bg='red')
  81.     if self.model.checkWinStatus() == -1:
  82.      messagebox.showinfo("Result", "Computer wins!!!!")
  83.      self.resetGUI()
  84.    else:
  85.     # Should not get here ...
  86.     pass
  87. def resetGUI(self):
  88.   for row in range(self.model.boardSize):
  89.    for col in range(self.model.boardSize):
  90.     self.b[row][col].configure(bg='WHITE')
  91.   # And reset the model ...
  92.   self.model.resetBoard()
  93.   self.resetImg()
  94. def main():
  95. win = tk.Tk() # Create a window
  96. win.title("noughts-and-crosses") # Set window title
  97. win.geometry("400x580") # Set window size
  98. win.resizable(False, False) # Both x and y dimensions ...
  99. # Create the GUI as a Frame
  100. # and attach it to the window ...
  101. myApp = TicTacToeGUI(win)
  102. # Call the GUI mainloop ...
  103. win.mainloop()
  104. if __name__ == "__main__":
  105. main()
复制代码
TicTacToeModel:
  1. import numpy as np
  2. import random
  3. class TicTacToeModel:
  4. """ The board is represented as 2D numpy array.
  5.   A player marks their space with a 1, the
  6.   computer with a -1"""
  7. def __init__(self):
  8.   """Create the board as a 2D matrix"""
  9.   self.resetBoard()
  10. def resetBoard(self):
  11.   self.boardSize = 3
  12.   a = (self.boardSize, self.boardSize)
  13.   self.board = np.zeros(a)
  14. def playSpace(self, row, col):
  15.   """User plays a space
  16.   Return True if space can be played, False otherwise"""
  17.   if row > self.boardSize or row < 0 \
  18.     or col > self.boardSize or col < 0:
  19.    return False
  20.   else:
  21.    # Check if space is occupied ...
  22.    if self.board[row][col] != 0:
  23.     return False
  24.    else:
  25.     self.board[row][col] = 1
  26.     return True
  27. def checkWinStatus(self):
  28.   """ Looks for 3 in a row, column or diagonal
  29.    Return 0 if draw, 1 if the player has won
  30.    and -1 if the computer has won, and -2 is the game is
  31.    ongoing"""
  32.   # Check the columns ...
  33.   for row in range(self.boardSize):
  34.    sum = 0
  35.    for col in range(self.boardSize):
  36.     sum += self.board[row][col]
  37.    if sum == 3:
  38.     return 1
  39.    elif sum == -3:
  40.     return -1
  41.   # Check the rows ...
  42.   for col in range(self.boardSize):
  43.    sum = 0
  44.    for row in range(self.boardSize):
  45.     sum += self.board[row][col]
  46.    if sum == 3:
  47.     return 1
  48.    elif sum == -3:
  49.     return -1
  50.   # Check the diagonals ...
  51.   sum1 = 0
  52.   sum2 = 0
  53.   for diag in range(self.boardSize):
  54.    sum1 += self.board[diag][diag]
  55.    sum2 += self.board[diag][self.boardSize - 1 - diag]
  56.   if sum1 == 3 or sum2 == 3:
  57.    return 1
  58.   elif sum1 == -3 or sum2 == -3:
  59.    return -1
  60.   # Check for incomplete game ...
  61.   for row in range(self.boardSize):
  62.    for col in range(self.boardSize):
  63.     if self.board[row][col] == 0:
  64.      return -2
  65.   # If we get here, it's a draw ...
  66.   return 0
  67. def computerTurn(self):
  68.   """ The computer chooses an unoccupied
  69.    space at random. Returns a tuple
  70.    (row, col) when chosen"""
  71.   # To prevent infinite loops ....
  72.   if self.checkWinStatus() != -2:
  73.    return (-1, -1)
  74.   played = False
  75.   while played == False:
  76.    row = random.randrange(self.boardSize)
  77.    col = random.randrange(self.boardSize)
  78.    if self.board[row][col] == 0:
  79.     self.board[row][col] = -1
  80.     played = True
  81.   return (row, col)
  82. def main():
  83. # Basic check that the game works ...
  84. # You can expand this if you like ...
  85. game = TicTacToeModel()
  86. game.playSpace(0, 0)
  87. (r, c) = game.computerTurn()
  88. print(game.board)
  89. print(game.checkWinStatus())
  90. if __name__ == "__main__":
  91. main()
复制代码
更多关于python游戏的精彩文章请点击查察以下专题:
python俄罗斯方块游戏集合
python经典小游戏汇总
python微信跳一跳游戏集合
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持草根技术分享。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有帐号?立即注册

x

帖子地址: 

回复

使用道具 举报

分享
推广
火星云矿 | 预约S19Pro,享500抵1000!
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

草根技术分享(草根吧)是全球知名中文IT技术交流平台,创建于2021年,包含原创博客、精品问答、职业培训、技术社区、资源下载等产品服务,提供原创、优质、完整内容的专业IT技术开发社区。
  • 官方手机版

  • 微信公众号

  • 商务合作