程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

【Python游戲】Python基於pygame實現的人機大戰的斗獸棋小游戲 | 附源碼

編輯:Python

前言

有粉絲說要我出一期Python版本的斗獸棋,今天寵粉狂魔的我不就來啦!!
雖然是一個簡單的小游戲,但是對於新手小伙伴來說還是有一定的小難度的喲!要是不理解都可以找到小編的哈!!

相關文件

關注小編,私信小編領取喲!
當然別忘了一件三連喲~~

公眾號:Python日志
可以關注小編公眾號,會不定時的發布一下Python小技巧,還有很多資源可以免費領取喲!!
源碼領取:加Python學習交流群:494958217 可以領取喲

開發工具

Python版本:3.7.8
相關模塊:
pygame模塊;
sys模塊;
os模塊;
以及一些python自帶的模塊。

環境搭建

安裝Python並添加到環境變量,pip安裝需要的相關模塊即可。

效果展示

游戲開始環節

游戲中

贏得游戲

部分代碼展示

模塊導入

import os
import sys
from typing import Tuple
import pygame
import settings
from board import Board
from strategies import get_random_move, get_eat_move,get_best_move,get_best_move2

監聽用戶鍵鼠事件

 while True:
if board.not_eat >= 20:
return (0, 0)
if board.game_over():
return board.get_result()
for event in pygame.event.get():
if event.type == pygame.QUIT:
terminate()
if event.type == pygame.MOUSEBUTTONUP:
if board.turn == 'red':
x,y = event.pos[0],event.pos[1]
board.collect_coordinates_and_make_move(x,y)
window_surface.fill(settings.WHITE)
# 繪制棋盤
board.draw_board(window_surface,stretched_images)
# 繪制輪到誰出牌的提示
color = board.get_turn_color()
text = '你的回合' if board.turn == 'red' else "對方回合"
write_text(big_font,
text,
color,
window_rect.centerx,
window_rect.centery+250,
window_surface)
pygame.display.update()
if board.turn == 'blue':
valid_moves = board.get_valid_moves()
if valid_moves:
pygame.time.delay(400)
move = get_best_move(valid_moves, board)
board.make_computer_move(move, window_surface)
main_clock.tick(settings.FPS)

主函數

if __name__ == "__main__":
# 初始化
pygame.init()
main_clock = pygame.time.Clock()
# 加載各種圖片並且保存到一個字典裡面
icon_image = pygame.image.load(os.path.join(settings.IMAGE_DIR,'bitbug_favicon.ico'))
back_image = pygame.image.load(os.path.join(settings.IMAGE_DIR,'問號.jpg'))
back_stretched_image = pygame.transform.scale(back_image,(settings.CELL_SIZE,settings.CELL_SIZE))
stretched_images = {
'back':back_stretched_image}
for color in ('red','blue'):
for animal in settings.ANIMALS:
filename = f'{
color}_{
animal}'
original_image = pygame.image.load(os.path.join(settings.IMAGE_DIR,filename+'.jpg'))
stretched_image = pygame.transform.scale(original_image,(settings.CELL_SIZE,settings.CELL_SIZE))
stretched_images[filename] = stretched_image
# 創建窗口
pygame.display.set_icon(icon_image)
window_surface = pygame.display.set_mode((settings.WINDOW_WIDTH,settings.WINDOW_HEIGHT))
window_rect = window_surface.get_rect()
pygame.display.set_caption('斗獸棋 Python學習交流群:494958217 源碼領取加群喲')
# 創建字體
big_font = pygame.font.Font(os.path.join(settings.FONT_DIR,'msyh.ttf'),48)
small_font = pygame.font.Font(os.path.join(settings.FONT_DIR,'msyh.ttf'),24)

棋盤類

class Board:
'''棋盤類'''
def __init__(self) -> None:
# 用於存放16顆棋子
pieces: List[Piece] = []
# 添加紅方的8顆棋子
for name in settings.ANIMALS:
pieces.append(Piece(name,'red'))
# 添加藍方的8顆棋子
for name in settings.ANIMALS:
pieces.append(Piece(name,'blue'))
# 隨機打亂棋子的順序
random.shuffle(pieces)
# 用於存放棋盤上的16個格子
# 這些格子是4行4列
self._container: List[List[Cell]] = []
# 把16顆棋子放到16個格子上
i = 0
for row in range(4):
row_of_board = []
for col in range(4):
row_of_board.append(
Cell(pieces[i],
settings.LEFT_OF_BOARD + col*settings.CELL_SIZE,
settings.TOP_OF_BOARD + row*settings.CELL_SIZE,
settings.CELL_SIZE)
)
i += 1
self._container.append(row_of_board)
self._turn = random.choice(['red','blue'])
# 保存的用戶第一次點擊的坐標
self.user_coordinates = None
# 10次沒有互相吃,就平局
self.not_eat = 0
@property
def turn(self) -> str:
return self._turn

棋子類

class Piece:
'''棋子類'''
def __init__(self,name: str, color: Tuple[int,int,int]) -> None:
# 動物的名字
self.name = name
# 動物的顏色,用它來區分是哪一隊的棋子
self.color = color
# 動物的權重
self.score = SCORES[name]
# 設置動物的天敵和食物
# 大象和老鼠比較特殊,其他都是按照列表裡的順序排列的
if name == 'elephant':
self.enemy = {
'mouse'}
self.food = {
 a for a in ANIMALS[1:-1]}
elif name == 'mouse':
self.enemy = {
a for a in ANIMALS[1:-1]}
self.food = {
'elephant'}
else:
index = ANIMALS.index(name)
self.enemy = {
a for a in ANIMALS[:index]}
self.food = {
a for a in ANIMALS[index+1:]}

總結

游戲最終結果如何其實不是很重要,重要的是一個學習的過程,只有自己弄懂了這個過程,學起來才會有動力,本游戲的一些主要的代碼我已經寫出來了,還有部分代碼我就沒有展示了,需要源碼的小伙伴可以看相關文件喲!!
源碼都是可以給大家作參考的喲!!!!
希望大家多多支持小編,這樣小編才能夠給大家帶來更多知識分享喲!!


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved