当前位置:网站首页>[pyGame games] here it is. This Gobang game is super A. share it with your friends~
[pyGame games] here it is. This Gobang game is super A. share it with your friends~
2022-06-10 23:59:00 【Programmer pear】
Preface
author :“ Programmer pear ”
** The article brief introduction **: This article is mainly about pygame Gobang to achieve a small game !
** article Source code Free access : In order to thank everyone who pays attention to me, the project source code of each article is none
Compensation sharing drop
Welcome friends give the thumbs-up 、 Collection 、 Leaving a message.
Text
The white pieces of Gobang have 112 gold , Sunspots have 113 gold , And the white pieces of go have 180 gold , Black chessman 181 gold .
Hey , I guess many people don't know ?!
Today, Xiaobian will take you to know more about Gobang , Make a code version of Gobang game for everyone , Not only can it fight computers, man-machine ,
You can also fight online with your friends ~

1) Game interface

Code display ——
class gameStartUI(QWidget):
def __init__(self, parent=None, **kwargs):
super(gameStartUI, self).__init__(parent)
self.setFixedSize(760, 650)
self.setWindowTitle(' Gobang game against ')
self.setWindowIcon(QIcon(cfg.ICON_FILEPATH))
# Background image
palette = QPalette()
palette.setBrush(self.backgroundRole(), QBrush(QPixmap(cfg.BACKGROUND_IMAGEPATHS.get('bg_start'))))
self.setPalette(palette)
# Button
# -- Man machine battle
self.ai_button = PushButton(cfg.BUTTON_IMAGEPATHS.get('ai'), self)
self.ai_button.move(250, 200)
self.ai_button.show()
self.ai_button.click_signal.connect(self.playWithAI)
# -- Online versus
self.online_button = PushButton(cfg.BUTTON_IMAGEPATHS.get('online'), self)
self.online_button.move(250, 350)
self.online_button.show()
self.online_button.click_signal.connect(self.playOnline)
''' Man machine battle '''
def playWithAI(self):
self.close()
self.gaming_ui = playWithAIUI(cfg)
self.gaming_ui.exit_signal.connect(lambda: sys.exit())
self.gaming_ui.back_signal.connect(self.show)
self.gaming_ui.show()
''' Online versus '''
def playOnline(self):
self.close()
self.gaming_ui = playOnlineUI(cfg, self)
self.gaming_ui.show()
'''run'''
if __name__ == '__main__':
app = QApplication(sys.argv)
handle = gameStartUI()
font = QFont()
font.setPointSize(12)
handle.setFont(font)
handle.show()
sys.exit(app.exec_())2) Man machine battle

Code display ——
import pygame
from ..misc import *
from PyQt5 import QtCore
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from itertools import product
from .aiGobang import aiGobang
''' Man machine battle '''
class playWithAIUI(QWidget):
back_signal = pyqtSignal()
exit_signal = pyqtSignal()
send_back_signal = False
def __init__(self, cfg, parent=None, **kwargs):
super(playWithAIUI, self).__init__(parent)
self.cfg = cfg
self.setFixedSize(760, 650)
self.setWindowTitle(' Gobang man-machine battle ')
self.setWindowIcon(QIcon(cfg.ICON_FILEPATH))
# Background image
palette = QPalette()
palette.setBrush(self.backgroundRole(), QBrush(QPixmap(cfg.BACKGROUND_IMAGEPATHS.get('bg_game'))))
self.setPalette(palette)
# Button
self.home_button = PushButton(cfg.BUTTON_IMAGEPATHS.get('home'), self)
self.home_button.click_signal.connect(self.goHome)
self.home_button.move(680, 10)
self.startgame_button = PushButton(cfg.BUTTON_IMAGEPATHS.get('startgame'), self)
self.startgame_button.click_signal.connect(self.startgame)
self.startgame_button.move(640, 240)
self.regret_button = PushButton(cfg.BUTTON_IMAGEPATHS.get('regret'), self)
self.regret_button.click_signal.connect(self.regret)
self.regret_button.move(640, 310)
self.givein_button = PushButton(cfg.BUTTON_IMAGEPATHS.get('givein'), self)
self.givein_button.click_signal.connect(self.givein)
self.givein_button.move(640, 380)
# Drop sign
self.chessman_sign = QLabel(self)
sign = QPixmap(cfg.CHESSMAN_IMAGEPATHS.get('sign'))
self.chessman_sign.setPixmap(sign)
self.chessman_sign.setFixedSize(sign.size())
self.chessman_sign.show()
self.chessman_sign.hide()
# The board (19*19 matrix )
self.chessboard = [[None for i in range(19)] for _ in range(19)]
# Historical record ( Repentance chess )
self.history_record = []
# Whether in the game
self.is_gaming = True
# The victorious side
self.winner = None
self.winner_info_label = None
# Color assignment and Whose turn is it now
self.player_color = 'white'
self.ai_color = 'black'
self.whoseround = self.player_color
# Instantiation ai
self.ai_player = aiGobang(self.ai_color, self.player_color)
# Falling sound loading
pygame.mixer.init()
self.drop_sound = pygame.mixer.Sound(cfg.SOUNDS_PATHS.get('drop'))
''' Left mouse click events - Player turn '''
def mousePressEvent(self, event):
if (event.buttons() != QtCore.Qt.LeftButton) or (self.winner is not None) or (self.whoseround != self.player_color) or (not self.is_gaming):
return
# Make sure to respond only within the chessboard range
if event.x() >= 50 and event.x() <= 50 + 30 * 18 + 14 and event.y() >= 50 and event.y() <= 50 + 30 * 18 + 14:
pos = Pixel2Chesspos(event)
# There was no one in the place where they were guaranteed to fall
if self.chessboard[pos[0]][pos[1]]:
return
# Instantiate a chess piece and display
c = Chessman(self.cfg.CHESSMAN_IMAGEPATHS.get(self.whoseround), self)
c.move(event.pos())
c.show()
self.chessboard[pos[0]][pos[1]] = c
# The falling sound sounded
self.drop_sound.play()
# Finally, the falling position mark follows the falling position
self.chessman_sign.show()
self.chessman_sign.move(c.pos())
self.chessman_sign.raise_()
# Record this fall
self.history_record.append([*pos, self.whoseround])
# Whether we won
self.winner = checkWin(self.chessboard)
if self.winner:
self.showGameEndInfo()
return
# Switch round side ( It's actually changing the color )
self.nextRound()
''' Left mouse button release operation - Call the computer round '''
def mouseReleaseEvent(self, event):
if (self.winner is not None) or (self.whoseround != self.ai_color) or (not self.is_gaming):
return
self.aiAct()
''' The computer automatically -AI round '''
def aiAct(self):
if (self.winner is not None) or (self.whoseround == self.player_color) or (not self.is_gaming):
return
next_pos = self.ai_player.act(self.history_record)
# Instantiate a chess piece and display
c = Chessman(self.cfg.CHESSMAN_IMAGEPATHS.get(self.whoseround), self)
c.move(QPoint(*Chesspos2Pixel(next_pos)))
c.show()
self.chessboard[next_pos[0]][next_pos[1]] = c
# The falling sound sounded
self.drop_sound.play()
# Finally, the falling position mark follows the falling position
self.chessman_sign.show()
self.chessman_sign.move(c.pos())
self.chessman_sign.raise_()
# Record this fall
self.history_record.append([*next_pos, self.whoseround])
# Whether we won
self.winner = checkWin(self.chessboard)
if self.winner:
self.showGameEndInfo()
return
# Switch round side ( It's actually changing the color )
self.nextRound()
''' Change the falling square '''
def nextRound(self):
self.whoseround = self.player_color if self.whoseround == self.ai_color else self.ai_color
''' Show the end result of the game '''
def showGameEndInfo(self):
self.is_gaming = False
info_img = QPixmap(self.cfg.WIN_IMAGEPATHS.get(self.winner))
self.winner_info_label = QLabel(self)
self.winner_info_label.setPixmap(info_img)
self.winner_info_label.resize(info_img.size())
self.winner_info_label.move(50, 50)
self.winner_info_label.show()
''' Throw in the towel '''
def givein(self):
if self.is_gaming and (self.winner is None) and (self.whoseround == self.player_color):
self.winner = self.ai_color
self.showGameEndInfo()
''' Repentance - Only our turn can repent '''
def regret(self):
if (self.winner is not None) or (len(self.history_record) == 0) or (not self.is_gaming) and (self.whoseround != self.player_color):
return
for _ in range(2):
pre_round = self.history_record.pop(-1)
self.chessboard[pre_round[0]][pre_round[1]].close()
self.chessboard[pre_round[0]][pre_round[1]] = None
self.chessman_sign.hide()
''' Start the game - The previous game must be over '''
def startgame(self):
if self.is_gaming:
return
self.is_gaming = True
self.whoseround = self.player_color
for i, j in product(range(19), range(19)):
if self.chessboard[i][j]:
self.chessboard[i][j].close()
self.chessboard[i][j] = None
self.winner = None
self.winner_info_label.close()
self.winner_info_label = None
self.history_record.clear()
self.chessman_sign.hide()
''' Close window events '''
def closeEvent(self, event):
if not self.send_back_signal:
self.exit_signal.emit()
''' Return to the main page of the game '''
def goHome(self):
self.send_back_signal = True
self.close()
self.back_signal.emit()3) Online versus

Code display ——
import sys
import random
from .server import *
from .client import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
''' Online versus '''
class playOnlineUI(QWidget):
def __init__(self, cfg, home_ui, parent=None, **kwargs):
super(playOnlineUI, self).__init__(parent)
self.cfg = cfg
self.home_ui = home_ui
self.setWindowTitle(' Online versus ')
self.setWindowIcon(QIcon(cfg.ICON_FILEPATH))
self.setFixedSize(300, 200)
# nickname
self.nickname = random.choice([' Jenny turtle ', ' Pikachu ', ' Little fire dragon ', ' Little saw crocodile ', ' Frog seed ', ' Chikorita '])
self.layout0 = QHBoxLayout()
self.nickname_label = QLabel(' Game nickname :', self)
self.nickname_edit = QLineEdit(self)
self.nickname_edit.setText(self.nickname)
self.layout0.addWidget(self.nickname_label, 1)
self.layout0.addWidget(self.nickname_edit, 3)
# IP
self.target_ip = '127.0.0.1'
self.layout1 = QHBoxLayout()
self.ip_label = QLabel(' other party IP:', self)
self.ip_edit = QLineEdit(self)
self.ip_edit.setText(self.target_ip)
self.layout1.addWidget(self.ip_label, 1)
self.layout1.addWidget(self.ip_edit, 3)
# Button
self.layout2 = QHBoxLayout()
self.connect_button = QPushButton(' As a client ', self)
self.connect_button.clicked.connect(self.becomeClient)
self.ashost_button = QPushButton(' As a server ', self)
self.ashost_button.clicked.connect(self.becomeHost)
self.layout2.addWidget(self.connect_button)
self.layout2.addWidget(self.ashost_button)
# Layout
self.layout = QVBoxLayout()
self.layout.addLayout(self.layout0)
self.layout.addLayout(self.layout1)
self.layout.addLayout(self.layout2)
self.setLayout(self.layout)
''' As a client '''
def becomeClient(self):
self.close()
self.nickname = self.nickname_edit.text()
self.target_ip = self.ip_edit.text()
self.client_ui = gobangClient(cfg=self.cfg, nickname=self.nickname, server_ip=self.target_ip)
self.client_ui.exit_signal.connect(lambda: sys.exit())
self.client_ui.back_signal.connect(self.home_ui.show)
self.client_ui.show()
''' As a server '''
def becomeHost(self):
self.close()
self.nickname = self.nickname_edit.text()
self.server_ui = gobangSever(cfg=self.cfg, nickname=self.nickname)
self.server_ui.exit_signal.connect(lambda: sys.exit())
self.server_ui.back_signal.connect(self.home_ui.show)
self.server_ui.show()summary
An LA ! This is the article , Your support is my biggest motivation , Remember Sanlian ~
Follow Xiaobian for more wonderful content ! Remember to click on the portal
Remember Sanlian ! If you need to package the complete source code + Free sharing of materials ! Portal

边栏推荐
- Lambda 学习记录
- 【Turtle表白合集】“海底月是天上月,眼前人是心上人。”余生多喜乐,长平安~(附3款源码)
- MySQL learning child query
- LeetCode 501 :二叉搜索樹中的眾數
- Easyrecovery15 simple and convenient data recovery tool
- 给线程池里面线程添加名称的4种方式
- Binary tree pruning
- Apple CMS collection station source code - building tutorial - attached source code - new source code - development documents
- A simple understanding of B tree
- Kubernetes 基本介绍及核心组件
猜你喜欢

easyrecovery15操作简单方便的数据恢复工具

【Pygame小游戏】别找了,休闲游戏专题来了丨泡泡龙小程序——休闲游戏研发推荐

【Pygame合集】滴~穿越童年游戏指南 请查收:这里面有你玩过的游戏嘛?(附五款源码自取)

Analysis of Genesis public chain

示波器和频谱分析仪的区别

Opencv实战之图像的基本操作:这效果出来惊艳了众人(附代码解析)
![[pyGame games] don't look for it. Here comes the leisure game topic - bubble dragon widget - recommendation for leisure game research and development](/img/fb/a966b4bf52cdab4030578d4595e09b.png)
[pyGame games] don't look for it. Here comes the leisure game topic - bubble dragon widget - recommendation for leisure game research and development

Hyperleger fabric installation

【Turtle表白合集】“海底月是天上月,眼前人是心上人。”余生多喜乐,长平安~(附3款源码)

【Pygame小游戏】剧情流推荐:什么样的游戏才能获得大家的喜欢呢?(魔鬼恋人、霸总娇妻版)
随机推荐
File转为MultipartFile的方法
Fiddler creates an autoresponder
2022年高考量化卷|请各位量化考生答题
How to generate automatic references (simple drawings)
Analysis of Genesis public chain
flutter 如何去掉listview顶部空白的问题
Binary tree pruning
【Pygame小遊戲】別找了,休閑遊戲專題來了丨泡泡龍小程序——休閑遊戲研發推薦
Leetcode 501: mode in binary search tree
Error 1046 when LabVIEW uses MathScript node or matlab script
LabVIEW用VISA Read函数来读取USB中断数据
Lambda 学习记录
Ilruntime hotfix framework installation and breakpoint debugging
Error report of curl import postman
希尔排序
What Fiddler does for testing
LeetCode 501 :二叉搜索樹中的眾數
【Pygame小游戏】这款“打地鼠”小游戏要火了(来来来)
【Pygame小游戏】别找了,休闲游戏专题来了丨泡泡龙小程序——休闲游戏研发推荐
How to handle the database query error with Emoji expression in Typecho- Xingze V Club
