用python实现围棋(动图演示+源码分享)
Posted 梦执.py
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用python实现围棋(动图演示+源码分享)相关的知识,希望对你有一定的参考价值。
大家好,我是梦执,对梦执着。希望能和大家共同进步! |
今天给大家带来一期围棋的源码分享。下面我们先看看效果。游戏进去默认为九路玩法,当然也可以选择十三路或是十九路玩法。
目录-文末领取所有文件
1.导入模块
tkinter:ttk覆盖tkinter部分对象,ttk对tkinter进行了优化
copy:深拷贝时需要用到copy模块
tkinter.messagebox:围棋应用对象定义
如没有以上模块,在pycharm终端输入以下指令:
pip install 相应模块 -i https://pypi.douban.com/simple
from tkinter import *
from tkinter.ttk import *
import copy
import tkinter.messagebox
2.初始化棋盘
对棋盘进行初始化和棋盘右侧的按钮设置,以及对棋子的控制。
class Application(Tk):
# 初始化棋盘,默认九路棋盘
def __init__(self,my_mode_num=9):
Tk.__init__(self)
# 模式,九路棋:9,十三路棋:13,十九路棋:19
self.mode_num=my_mode_num
# 窗口尺寸设置,默认:1.8
self.size=1.8
# 棋盘每格的边长
self.dd=360*self.size/(self.mode_num-1)
# 相对九路棋盘的矫正比例
self.p=1 if self.mode_num==9 else (2/3 if self.mode_num==13 else 4/9)
# 定义棋盘阵列,超过边界:-1,无子:0,黑棋:1,白棋:2
self.positions=[[0 for i in range(self.mode_num+2)] for i in range(self.mode_num+2)]
# 初始化棋盘,所有超过边界的值置-1
for m in range(self.mode_num+2):
for n in range(self.mode_num+2):
if (m*n==0 or m==self.mode_num+1 or n==self.mode_num+1):
self.positions[m][n]=-1
# 拷贝三份棋盘“快照”,悔棋和判断“打劫”时需要作参考
self.last_3_positions=copy.deepcopy(self.positions)
self.last_2_positions=copy.deepcopy(self.positions)
self.last_1_positions=copy.deepcopy(self.positions)
# 记录鼠标经过的地方,用于显示shadow时
self.cross_last=None
# 当前轮到的玩家,黑:0,白:1,执黑先行
self.present=0
# 初始停止运行,点击“开始游戏”运行游戏
self.stop=True
# 悔棋次数,次数大于0才可悔棋,初始置0(初始不能悔棋),悔棋后置0,下棋或弃手时恢复为1,以禁止连续悔棋
self.regretchance=0
# 图片资源,存放在当前目录下的/Pictures/中
self.photoW=PhotoImage(file = "./Pictures/W.png")
self.photoB=PhotoImage(file = "./Pictures/B.png")
self.photoBD=PhotoImage(file = "./Pictures/"+"BD"+"-"+str(self.mode_num)+".png")
self.photoWD=PhotoImage(file = "./Pictures/"+"WD"+"-"+str(self.mode_num)+".png")
self.photoBU=PhotoImage(file = "./Pictures/"+"BU"+"-"+str(self.mode_num)+".png")
self.photoWU=PhotoImage(file = "./Pictures/"+"WU"+"-"+str(self.mode_num)+".png")
# 用于黑白棋子图片切换的列表
self.photoWBU_list=[self.photoBU,self.photoWU]
self.photoWBD_list=[self.photoBD,self.photoWD]
# 窗口大小
self.geometry(str(int(600*self.size))+'x'+str(int(400*self.size)))
# 画布控件,作为容器
self.canvas_bottom=Canvas(self,bg='#369',bd=0,width=600*self.size,height=400*self.size)
self.canvas_bottom.place(x=0,y=0)
# 几个功能按钮
self.startButton=Button(self,text='开始游戏',command=self.start)
self.startButton.place(x=480*self.size,y=200*self.size)
self.passmeButton=Button(self,text='弃一手',command=self.passme)
self.passmeButton.place(x=480*self.size,y=225*self.size)
self.regretButton=Button(self,text='悔棋',command=self.regret)
self.regretButton.place(x=480*self.size,y=250*self.size)
# 初始悔棋按钮禁用
self.regretButton['state']=DISABLED
self.replayButton=Button(self,text='重新开始',command=self.reload)
self.replayButton.place(x=480*self.size,y=275*self.size)
self.newGameButton1=Button(self,text=('十三' if self.mode_num==9 else '九')+'路棋',command=self.newGame1)
self.newGameButton1.place(x=480*self.size,y=300*self.size)
self.newGameButton2=Button(self,text=('十三' if self.mode_num==19 else '十九')+'路棋',command=self.newGame2)
self.newGameButton2.place(x=480*self.size,y=325*self.size)
self.quitButton=Button(self,text='退出游戏',command=self.quit)
self.quitButton.place(x=480*self.size,y=350*self.size)
# 画棋盘,填充颜色
self.canvas_bottom.create_rectangle(0*self.size,0*self.size,400*self.size,400*self.size,fill='#c51')
# 刻画棋盘线及九个点
# 先画外框粗线
self.canvas_bottom.create_rectangle(20*self.size,20*self.size,380*self.size,380*self.size,width=3)
# 棋盘上的九个定位点,以中点为模型,移动位置,以作出其余八个点
for m in [-1,0,1]:
for n in [-1,0,1]:
self.oringinal=self.canvas_bottom.create_oval(200*self.size-self.size*2,200*self.size-self.size*2,
200*self.size+self.size*2,200*self.size+self.size*2,fill='#000')
self.canvas_bottom.move(self.oringinal,m*self.dd*(2 if self.mode_num==9 else (3 if self.mode_num==13 else 6)),
n*self.dd*(2 if self.mode_num==9 else (3 if self.mode_num==13 else 6)))
# 画中间的线条
for i in range(1,self.mode_num-1):
self.canvas_bottom.create_line(20*self.size,20*self.size+i*self.dd,380*self.size,20*self.size+i*self.dd,width=2)
self.canvas_bottom.create_line(20*self.size+i*self.dd,20*self.size,20*self.size+i*self.dd,380*self.size,width=2)
# 放置右侧初始图片
self.pW=self.canvas_bottom.create_image(500*self.size+11, 65*self.size,image=self.photoW)
self.pB=self.canvas_bottom.create_image(500*self.size-11, 65*self.size,image=self.photoB)
# 每张图片都添加image标签,方便reload函数删除图片
self.canvas_bottom.addtag_withtag('image',self.pW)
self.canvas_bottom.addtag_withtag('image',self.pB)
# 鼠标移动时,调用shadow函数,显示随鼠标移动的棋子
self.canvas_bottom.bind('<Motion>',self.shadow)
# 鼠标左键单击时,调用getdown函数,放下棋子
self.canvas_bottom.bind('<Button-1>',self.getDown)
# 设置退出快捷键<Ctrl>+<D>,快速退出游戏
self.bind('<Control-KeyPress-d>',self.keyboardQuit)
3. 开始游戏
def start(self):
# 删除右侧太极图
self.canvas_bottom.delete(self.pW)
self.canvas_bottom.delete(self.pB)
# 利用右侧图案提示开始时谁先落子
if self.present==0:
self.create_pB()
self.del_pW()
else:
self.create_pW()
self.del_pB()
# 开始标志,解除stop
self.stop=None
4.放弃当前回合落子
点击弃一手,可跳过当前回合落子。
def passme(self):
# 悔棋恢复
if not self.regretchance==1:
self.regretchance+=1
else:
self.regretButton['state']=NORMAL
# 拷贝棋盘状态,记录前三次棋局
self.last_3_positions=copy.deepcopy(self.last_2_positions)
self.last_2_positions=copy.deepcopy(self.last_1_positions)
self.last_1_positions=copy.deepcopy(self.positions)
self.canvas_bottom.delete('image_added_sign')
# 轮到下一玩家
if self.present==0:
self.create_pW()
self.del_pB()
self.present=1
else:
self.create_pB()
self.del_pW()
self.present=0
5.悔棋判断
若当前回合悔棋,则下两个回合都不能悔棋。
def regret(self):
# 判定是否可以悔棋
if self.regretchance==1:
self.regretchance=0
self.regretButton['state']=DISABLED
list_of_b=[]
list_of_w=[]
self.canvas_bottom.delete('image')
if self.present==0:
self.create_pB()
else:
self.create_pW()
for m in range(1,self.mode_num+1):
for n in range(1,self.mode_num+1):
self.positions[m][n]=0
for m in range(len(self.last_3_positions)):
for n in range(len(self.last_3_positions[m])):
if self.last_3_positions[m][n]==1:
list_of_b+=[[n,m]]
elif self.last_3_positions[m][n]==2:
list_of_w+=[[n,m]]
self.recover(list_of_b,0)
self.recover(list_of_w,1)
self.last_1_positions=copy.deepcopy(self.last_3_positions)
for m in range(1,self.mode_num+1):
for n in range(1,self.mode_num+1):
self.last_2_positions[m][n]=0
self.last_3_positions[m][n]=0
6.重新开始
点击重新开始,恢复棋盘。
def reload(self):
if self.stop==1:
self.stop=0
self.canvas_bottom.delete('image')
self.regretchance=0
self.present=0
self.create_pB()
for m in range(1,self.mode_num+1):
for n in range(1,self.mode_num+1):
self.positions[m][n]=0
self.last_3_positions[m][n]=0
self.last_2_positions[m][n]=0
self.last_1_positions[m][n]=0
7.右侧太极图的设置
def create_pW(self):
self.pW=self.canvas_bottom.create_image(500*self.size+11, 65*self.size,image=self.photoW)
self.canvas_bottom.addtag_withtag('image',self.pW)
def create_pB(self):
self.pB=self.canvas_bottom.create_image(500*self.size-11, 65*self.size,image=self.photoB)
self.canvas_bottom.addtag_withtag('image',self.pB)
def del_pW(self):
self.canvas_bottom.delete(self.pW)
def del_pB(self):
self.canvas_bottom.delete(self.pB)
8.落子设置
def shadow(self,event):
if not self.stop:
# 找到最近格点,在当前位置靠近的格点出显示棋子图片,并删除上一位置的棋子图片
if (20*self.size<event.x<380*self.size) and (20*self.size<event.y<380*self.size):
dx=(event.x-20*self.size)%self.dd
dy=(event.y-20*self.size)%self.dd
self.cross=self.canvas_bottom.create_image(event.x-dx+round(dx/self.dd)*self.dd+22*self.p, event.y-dy+round(dy/self.dd)*self.dd-27*self.p,image=self.photoWBU_list[self.present])
self.canvas_bottom.addtag_withtag('image',self.cross)
if self.cross_last!=None:
self.canvas_bottom.delete(self.cross_last)
self.cross_last=self.cross
# 落子,并驱动玩家的轮流下棋行为
def getDown(self,event):
if not self.stop:
# 先找到最近格点
if (20*self.size-self.dd*0.4<event.x<self.dd*0.4+380*self.size) and (用python实现植物大战僵尸(游戏截图+动态演示+源码分享)
大家好,我是梦执,对梦执着。希望能和大家共同进步!
下面给大家带来python实现植物大战僵尸的的源码分享,只含有冒险模式。
截图+动态演示+源码分享
游戏截图
动态演示
源码分享
state/tool.py
import os
import json
from abc import abstractmethod
import pygame as pg
from . import constants as c
class State():
def __init__(self):
self.start_time = 0.0
self.current_time = 0.0
self.done = False
self.next = None
self.persist =
@abstractmethod
def startup(self, current_time, persist):
'''abstract method'''
def cleanup(self):
self.done = False
return self.persist
@abstractmethod
def update(self, surface, keys, current_time):
'''abstract method'''
class Control():
def __init__(self):
self.screen = pg.display.get_surface()
self.done = False
self.clock = pg.time.Clock()
self.fps = 60
self.keys = pg.key.get_pressed()
self.mouse_pos = None
self.mouse_click = [False, False] # value:[left mouse click, right mouse click]
self.current_time = 0.0
self.state_dict =
self.state_name = None
self.state = None
self.game_info = c.CURRENT_TIME:0.0,
c.LEVEL_NUM:c.START_LEVEL_NUM
def setup_states(self, state_dict, start_state):
self.state_dict = state_dict
self.state_name = start_state
self.state = self.state_dict[self.state_name]
self.state.startup(self.current_time, self.game_info)
def update(self):
self.current_time = pg.time.get_ticks()
if self.state.done:
self.flip_state()
self.state.update(self.screen, self.current_time, self.mouse_pos, self.mouse_click)
self.mouse_pos = None
self.mouse_click[0] = False
self.mouse_click[1] = False
def flip_state(self):
previous, self.state_name = self.state_name, self.state.next
persist = self.state.cleanup()
self.state = self.state_dict[self.state_name]
self.state.startup(self.current_time, persist)
def event_loop(self):
for event in pg.event.get():
if event.type == pg.QUIT:
self.done = True
elif event.type == pg.KEYDOWN:
self.keys = pg.key.get_pressed()
elif event.type == pg.KEYUP:
self.keys = pg.key.get_pressed()
elif event.type == pg.MOUSEBUTTONDOWN:
self.mouse_pos = pg.mouse.get_pos()
self.mouse_click[0], _, self.mouse_click[1] = pg.mouse.get_pressed()
print('pos:', self.mouse_pos, ' mouse:', self.mouse_click)
def main(self):
while not self.done:
self.event_loop()
self.update()
pg.display.update()
self.clock.tick(self.fps)
print('game over')
def get_image(sheet, x, y, width, height, colorkey=c.BLACK, scale=1):
image = pg.Surface([width, height])
rect = image.get_rect()
image.blit(sheet, (0, 0), (x, y, width, height))
image.set_colorkey(colorkey)
image = pg.transform.scale(image,
(int(rect.width*scale),
int(rect.height*scale)))
return image
def load_image_frames(directory, image_name, colorkey, accept):
frame_list = []
tmp =
# image_name is "Peashooter", pic name is 'Peashooter_1', get the index 1
index_start = len(image_name) + 1
frame_num = 0;
for pic in os.listdir(directory):
name, ext = os.path.splitext(pic)
if ext.lower() in accept:
index = int(name[index_start:])
img = pg.image.load(os.path.join(directory, pic))
if img.get_alpha():
img = img.convert_alpha()
else:
img = img.convert()
img.set_colorkey(colorkey)
tmp[index]= img
frame_num += 1
for i in range(frame_num):
frame_list.append(tmp[i])
return frame_list
def load_all_gfx(directory, colorkey=c.WHITE, accept=('.png', '.jpg', '.bmp', '.gif')):
graphics =
for name1 in os.listdir(directory):
# subfolders under the folder resources\\graphics
dir1 = os.path.join(directory, name1)
if os.path.isdir(dir1):
for name2 in os.listdir(dir1):
dir2 = os.path.join(dir1, name2)
if os.path.isdir(dir2):
# e.g. subfolders under the folder resources\\graphics\\Zombies
for name3 in os.listdir(dir2):
dir3 = os.path.join(dir2, name3)
# e.g. subfolders or pics under the folder resources\\graphics\\Zombies\\ConeheadZombie
if os.path.isdir(dir3):
# e.g. it's the folder resources\\graphics\\Zombies\\ConeheadZombie\\ConeheadZombieAttack
image_name, _ = os.path.splitext(name3)
graphics[image_name] = load_image_frames(dir3, image_name, colorkey, accept)
else:
# e.g. pics under the folder resources\\graphics\\Plants\\Peashooter
image_name, _ = os.path.splitext(name2)
graphics[image_name] = load_image_frames(dir2, image_name, colorkey, accept)
break
else:
# e.g. pics under the folder resources\\graphics\\Screen
name, ext = os.path.splitext(name2)
if ext.lower() in accept:
img = pg.image.load(dir2)
if img.get_alpha():
img = img.convert_alpha()
else:
img = img.convert()
img.set_colorkey(colorkey)
graphics[name] = img
return graphics
def loadZombieImageRect():
file_path = os.path.join('source', 'data', 'entity', 'zombie.json')
f = open(file_path)
data = json.load(f)
f.close()
return data[c.ZOMBIE_IMAGE_RECT]
def loadPlantImageRect():
file_path = os.path.join('source', 'data', 'entity', 'plant.json')
f = open(file_path)
data = json.load(f)
f.close()
return data[c.PLANT_IMAGE_RECT]
pg.init()
pg.display.set_caption(c.ORIGINAL_CAPTION)
SCREEN = pg.display.set_mode(c.SCREEN_SIZE)
GFX = load_all_gfx(os.path.join("resources","graphics"))
ZOMBIE_RECT = loadZombieImageRect()
PLANT_RECT = loadPlantImageRect()
state/constants.py
START_LEVEL_NUM = 1
ORIGINAL_CAPTION = 'Plant VS Zombies Game'
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
SCREEN_SIZE = (SCREEN_WIDTH, SCREEN_HEIGHT)
GRID_X_LEN = 9
GRID_Y_LEN = 5
GRID_X_SIZE = 80
GRID_Y_SIZE = 100
WHITE = (255, 255, 255)
NAVYBLUE = ( 60, 60, 100)
SKY_BLUE = ( 39, 145, 251)
BLACK = ( 0, 0, 0)
LIGHTYELLOW = (234, 233, 171)
RED = (255, 0, 0)
PURPLE = (255, 0, 255)
GOLD = (255, 215, 0)
GREEN = ( 0, 255, 0)
SIZE_MULTIPLIER = 1.3
#GAME INFO DICTIONARY KEYS
CURRENT_TIME = 'current time'
LEVEL_NUM = 'level num'
#STATES FOR ENTIRE GAME
MAIN_MENU = 'main menu'
LOAD_SCREEN = 'load screen'
GAME_LOSE = 'game los'
GAME_VICTORY = 'game victory'
LEVEL = 'level'
MAIN_MENU_IMAGE = 'MainMenu'
OPTION_ADVENTURE = 'Adventure'
GAME_LOOSE_IMAGE = 'GameLoose'
GAME_VICTORY_IMAGE = 'GameVictory'
#MAP COMPONENTS
BACKGROUND_NAME = 'Background'
BACKGROUND_TYPE = 'background_type'
INIT_SUN_NAME = 'init_sun_value'
ZOMBIE_LIST = 'zombie_list'
MAP_EMPTY = 0
MAP_EXIST = 1
BACKGROUND_OFFSET_X = 220
MAP_OFFSET_X = 35
MAP_OFFSET_Y = 100
#MENUBAR
CHOOSEBAR_TYPE = 'choosebar_type'
CHOOSEBAR_STATIC = 0
CHOOSEBAR_MOVE = 1
CHOSSEBAR_BOWLING = 2
MENUBAR_BACKGROUND = 'ChooserBackground'
MOVEBAR_BACKGROUND = 'MoveBackground'
PANEL_BACKGROUND = 'PanelBackground'
START_BUTTON = 'StartButton'
CARD_POOL = 'card_pool'
MOVEBAR_CARD_FRESH_TIME = 6000
CARD_MOVE_TIME = 60
#PLANT INFO
PLANT_IMAGE_RECT = 'plant_image_rect'
CAR = 'car'
SUN = 'Sun'
SUNFLOWER = 'SunFlower'
PEASHOOTER = 'Peashooter'
SNOWPEASHOOTER = 'SnowPea'
WALLNUT = 'WallNut'
CHERRYBOMB = 'CherryBomb'
THREEPEASHOOTER = 'Threepeater'
REPEATERPEA = 'RepeaterPea'
CHOMPER = 'Chomper'
CHERRY_BOOM_IMAGE = 'Boom'
PUFFSHROOM = 'PuffShroom'
POTATOMINE = 'PotatoMine'
SQUASH = 'Squash'
SPIKEWEED = 'Spikeweed'
JALAPENO = 'Jalapeno'
SCAREDYSHROOM = 'ScaredyShroom'
SUNSHROOM = 'SunShroom'
ICESHROOM = 'IceShroom'
HYPNOSHROOM = 'HypnoShroom'
WALLNUTBOWLING = 'WallNutBowling'
REDWALLNUTBOWLING = 'RedWallNutBowling'
PLANT_HEALTH = 5
WALLNUT_HEALTH = 30
WALLNUT_CRACKED1_HEALTH = 20
WALLNUT_CRACKED2_HEALTH = 10
WALLNUT_BOWLING_DAMAGE = 10
PRODUCE_SUN_INTERVAL = 7000
FLOWER_SUN_INTERVAL = 22000
SUN_LIVE_TIME = 7000
SUN_VALUE = 25
ICE_SLOW_TIME = 2000
FREEZE_TIME = 7500
ICETRAP = 'IceTrap'
#PLANT CARD INFO
CARD_SUNFLOWER = 'card_sunflower'
CARD_PEASHOOTER = 'card_peashooter'
CARD_SNOWPEASHOOTER = 'card_snowpea'
CARD_WALLNUT = 'card_wallnut'
CARD_CHERRYBOMB = 'card_cherrybomb'
CARD_THREEPEASHOOTER = 'card_threepeashooter'
CARD_REPEATERPEA = 'card_repeaterpea'
CARD_CHOMPER = 'card_chomper'
CARD_PUFFSHROOM = 'card_puffshroom'
CARD_POTATOMINE = 'card_potatomine'
CARD_SQUASH = 'card_squash'
CARD_SPIKEWEED = 'card_spikeweed'
CARD_JALAPENO = 'card_jalapeno'
CARD_SCAREDYSHROOM = 'card_scaredyshroom'
CARD_SUNSHROOM = 'card_sunshroom'
CARD_ICESHROOM = 'card_iceshroom'
CARD_HYPNOSHROOM = 'card_hypnoshroom'
CARD_REDWALLNUT = 'card_redwallnut'
#BULLET INFO
BULLET_PEA = 'PeaNormal'
BULLET_PEA_ICE = 'PeaIce'
BULLET_MUSHROOM = 'BulletMushRoom'
BULLET_DAMAGE_NORMAL = 1
#ZOMBIE INFO
ZOMBIE_IMAGE_RECT = 'zombie_image_rect'
ZOMBIE_HEAD = 'ZombieHead'
NORMAL_ZOMBIE = 'Zombie'
CONEHEAD_ZOMBIE = 'ConeheadZombie'
BUCKETHEAD_ZOMBIE = 'BucketheadZombie'
FLAG_ZOMBIE = 'FlagZombie'
NEWSPAPER_ZOMBIE = 'NewspaperZombie'
BOOMDIE = 'BoomDie'
LOSTHEAD_HEALTH = 5
NORMAL_HEALTH = 10
FLAG_HEALTH = 15
CONEHEAD_HEALTH = 20
BUCKETHEAD_HEALTH = 30
NEWSPAPER_HEALTH = 15
ATTACK_INTERVAL = 1000
ZOMBIE_WALK_INTERVAL = 70
ZOMBIE_START_X = SCREEN_WIDTH + 50
#STATE
IDLE = 'idle'
FLY = 'fly'
EXPLODE = 'explode'
ATTACK = 'attack'
ATTACKED = 'attacked'
DIGEST = 'digest'
WALK = 'walk'
DIE = 'die'
CRY = 'cry'
FREEZE = 'freeze'
SLEEP = 'sleep'
#LEVEL STATE
CHOOSE = 'choose'
PLAY = 'play'
#BACKGROUND
BACKGROUND_DAY = 0
BACKGROUND_NIGHT = 1
state/main.py
from . import tool
from . import constants as c
from .state import mainmenu, screen, level
def main():
game = tool.Control()
state_dict = c.MAIN_MENU: mainmenu.Menu(),
c.GAME_VICTORY: screen.GameVictoryScreen(),
c.GAME_LOSE: screen.GameLoseScreen(),
c.LEVEL: level.Level()
game.setup_states(state_dict, c.MAIN_MENU)
game.main()
主执行文件main.py
import pygame as pg
from source.main import main
if __name__=='__main__':
main()
pg.quit()
还有植物和僵尸的源码,实在太多了,需要的小伙伴直接私聊我领取!!
以上是关于用python实现围棋(动图演示+源码分享)的主要内容,如果未能解决你的问题,请参考以下文章
python实现五子棋-人机对战/人人对战(动图演示+源码分享)
10个python经典小游戏(上)-五一嗨起来(动图演示+源码分享)
用python实现植物大战僵尸(游戏截图+动态演示+源码分享)