本文实例为大家分享了tkinter实现三子棋游戏的具体代码,供大家参考,具体内容如下

整体游戏很简单。下棋,判断胜利或者平局。没有加入电脑下棋的算法。

游戏界面:

代码:

import tkinter as tk
from tkinter import messagebox, label, button
from tictactoemodel import tictactoemodel
import requests
from pil import imagetk, image
from io import bytesio
 
 
class tictactoegui:
 
 def __init__(self, root):
  # create the model instance ...
  self.model = tictactoemodel()
 
  # create a 2d list to hold an array of buttons ...
  self.b = []
  for row in range(self.model.boardsize):
   q = []
   for col in range(self.model.boardsize):
    q.append(none)
   self.b.append(q)
  # you can now address b like a 2d matrix e.g. b[0][0]
 
  # create the gui .....
  menubar = tk.menu()
 
  menubar.add_command(label='resetgame', command=self.resetgui)
  menubar.add_command(label='resetimage', command=self.resetimg)
  menubar.add_command(label='quit', command=root.destroy)
  root.config(menu=menubar)
  self.frame1 = tk.frame(root, width=400, height=300, bg="grey", borderwidth=2)
  self.frame2 = tk.frame(root, width=400, height=200, bg="white", borderwidth=2)
  self.createguiassets()
  self.createframe2()
  self.frame2.pack()
  self.frame1.pack()
 
  messagebox.showinfo("hello", "human player to start!")
 
 def getimg(self):
  headers = {
   'user-agent': 'mozilla/5.0 (windows nt 10.0; wow64) applewebkit/537.36 (khtml, like gecko) chrome/88.0.4324.104 safari/537.36'
  }
  # img_src = ' https://api.ixiaowai.cn/api/api.php'
  img_src = ' https://api.ixiaowai.cn/gqapi/gqapi.php'
  response = requests.get(url=img_src, headers=headers)
  # print(response)
  image = image.open(bytesio(response.content))
  x, y = image.size
  y_s = 200
  x_s = int(x * y_s / y)
  img = image.resize((x_s, y_s), image.antialias)
  image = imagetk.photoimage(img)
  return image
 
 def resetimg(self):
  self.image = self.getimg()
  self.label.config(image=self.image)
 
 def createframe2(self):
  self.image = self.getimg()
  self.label = tk.label(self.frame2, image=self.image)
  self.label.pack()
  # image.show()
 
 def createguiassets(self):
  for x in range(self.model.boardsize):
   self.frame1.columnconfigure(x, pad=20)
   self.frame1.grid_rowconfigure(x, pad=20)
 
  for row in range(self.model.boardsize):
   for col in range(self.model.boardsize):
    self.b[row][col] = button(self.frame1, text='', bg='white',
           relief='groove', borderwidth=20,
           height=3, width=8,
           command=lambda row=row, col=col: self.taketurn(row, col))
    self.b[row][col].grid(row=row, column=col)
 
 def taketurn(self, row, col):
  if not self.model.playspace(row, col):
   return
  else:
   self.b[row][col].configure(bg="green")
   status = self.model.checkwinstatus()
   if status == 1: # player win
    messagebox.showinfo("result", "player wins!!!!")
    self.resetgui()
   elif status == 0: # draw
    messagebox.showinfo("result", "draw!!!!")
    self.resetgui()
   elif status == -2: # on going ...
    (r, c) = self.model.computerturn()
    self.b[r][c].configure(bg='red')
    if self.model.checkwinstatus() == -1:
     messagebox.showinfo("result", "computer wins!!!!")
     self.resetgui()
   else:
    # should not get here ...
    pass
 
 def resetgui(self):
  for row in range(self.model.boardsize):
   for col in range(self.model.boardsize):
    self.b[row][col].configure(bg='white')
  # and reset the model ...
  self.model.resetboard()
  self.resetimg()
 
 
def main():
 win = tk.tk() # create a window
 win.title("noughts-and-crosses") # set window title
 win.geometry("400x580") # set window size
 win.resizable(false, false) # both x and y dimensions ...
 
 # create the gui as a frame
 # and attach it to the window ...
 myapp = tictactoegui(win)
 
 # call the gui mainloop ...
 win.mainloop()
 
 
if __name__ == "__main__":
 main()

tictactoemodel:

import numpy as np
import random
 
 
class tictactoemodel:
 """ the board is represented as 2d numpy array.
  a player marks their space with a 1, the
  computer with a -1"""
 
 def __init__(self):
  """create the board as a 2d matrix"""
  self.resetboard()
 
 def resetboard(self):
  self.boardsize = 3
  a = (self.boardsize, self.boardsize)
  self.board = np.zeros(a)
 
 def playspace(self, row, col):
  """user plays a space
  return true if space can be played, false otherwise"""
  if row > self.boardsize or row < 0 \
    or col > self.boardsize or col < 0:
   return false
  else:
   # check if space is occupied ...
   if self.board[row][col] != 0:
    return false
   else:
    self.board[row][col] = 1
    return true
 
 def checkwinstatus(self):
  """ looks for 3 in a row, column or diagonal
   return 0 if draw, 1 if the player has won
   and -1 if the computer has won, and -2 is the game is
   ongoing"""
  # check the columns ...
  for row in range(self.boardsize):
   sum = 0
   for col in range(self.boardsize):
    sum += self.board[row][col]
   if sum == 3:
    return 1
   elif sum == -3:
    return -1
  # check the rows ...
  for col in range(self.boardsize):
   sum = 0
   for row in range(self.boardsize):
    sum += self.board[row][col]
   if sum == 3:
    return 1
   elif sum == -3:
    return -1
 
  # check the diagonals ...
  sum1 = 0
  sum2 = 0
  for diag in range(self.boardsize):
   sum1 += self.board[diag][diag]
   sum2 += self.board[diag][self.boardsize - 1 - diag]
  if sum1 == 3 or sum2 == 3:
   return 1
  elif sum1 == -3 or sum2 == -3:
   return -1
 
  # check for incomplete game ...
  for row in range(self.boardsize):
   for col in range(self.boardsize):
    if self.board[row][col] == 0:
     return -2
 
  # if we get here, it's a draw ...
  return 0
 
 def computerturn(self):
  """ the computer chooses an unoccupied
   space at random. returns a tuple
   (row, col) when chosen"""
  # to prevent infinite loops ....
  if self.checkwinstatus() != -2:
   return (-1, -1)
  played = false
 
  while played == false:
   row = random.randrange(self.boardsize)
   col = random.randrange(self.boardsize)
   if self.board[row][col] == 0:
    self.board[row][col] = -1
    played = true
 
  return (row, col)
 
 
def main():
 # basic check that the game works ...
 # you can expand this if you like ...
 game = tictactoemodel()
 
 game.playspace(0, 0)
 (r, c) = game.computerturn()
 print(game.board)
 print(game.checkwinstatus())
 
 
if __name__ == "__main__":
 main()

更多关于python游戏的精彩文章请点击查看以下专题:

python俄罗斯方块游戏集合

python经典小游戏汇总

python微信跳一跳游戏集合

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持www.887551.com。