如何用 Python 開發遊戲

Python 是最通用的語言,它幾乎出現在每個領域,包括網絡開發、機器學習、人工智能、圖形用戶界面應用以及遊戲開發。

Python 提供了一個名為 pygame、 的內置庫,用來開發遊戲。一旦我們理解了 Python 編程的基本概念,我們就可以使用 pygame 庫來製作具有吸引人的圖形、合適的動畫和聲音的遊戲。

Pygame 是一個用於設計視頻遊戲的跨平台庫。它包括計算機圖形和聲音庫,為用戶提供標準的遊戲體驗。

由 Pete Shinners 開發,取代 PySDL。

Pygame 的先決條件

要學習 pygame,必須對 Python 編程語言有所了解。

安裝 Pygame

打開命令行終端,鍵入以下命令安裝 pygame。


pip install pygame

我們也可以通過 IDE 安裝。欲了解更多安裝指南,請訪問我們完整的 pygame 教程(https://www.javatpoint.com/pygame)。在這裡你會發現所有必不可少的 pygame 解釋。

簡單的 Pygame 示例

下面是創建一個簡單 pygame 窗口的例子。


import pygame  

pygame.init()  
screen = pygame.display.set_mode((400,500))  
done = False  

while not done:  
    for event in pygame.event.get():  
        if event.type == pygame.QUIT:  
            done = True  
    pygame.display.flip()  

輸出:

所有圖形將在 pygame 窗口中繪製。

讓我們了解一下上述程序的基本語法。

導入 pygame – 就是這個模塊讓我們可以使用 pygame 的所有功能。

pygame.init() – 用於初始化 pygame 所有需要的模塊。

pygame.display.set_mode((寬度、高度))- 用於調整窗口大小。它將返回曲面對象。表面對象用於執行圖形操作。

pygame.event.get() – 它使事件隊列為空。如果我們不調用它,窗口消息將開始堆積,並且在操作系統看來,遊戲將變得無響應。

pygame。退出- 用來當我們點擊窗口角落的十字按鈕時,退出事件。

pygame.display.flip() – 用於反映遊戲的任何更新。如果我們做任何改變,那麼我們需要調用 display.flip()函數。

我們可以在 pygame 表面繪製任何形狀,包括添加圖像、吸引人的字體。Pygame 提供了許多內置功能,可以將幾何形狀繪製到屏幕上。這些形狀是開發遊戲的初始階段。

讓我們來理解以下將形狀繪製到屏幕上的示例。

示例-


import pygame  
from math import pi  
pygame.init()  
# size variable is using for set screen size  
size = [400, 300]  
screen = pygame.display.set_mode(size)  
pygame.display.set_caption("Example program to draw geometry")  
# done variable is using as flag   
done = False  
clock = pygame.time.Clock()  
while not done:  
    # clock.tick() limits the while loop to a max of 10 times per second.  
        clock.tick(10)  

    for event in pygame.event.get():  # User did something  
        if event.type == pygame.QUIT:  # If user clicked on close symbol   
            done = True  # done variable that we are complete, so we exit this loop  

    # All drawing code occurs after the for loop and but  
    # inside the main while done==False loop.  

    # Clear the default screen background and set the white screen background  
    screen.fill((0, 0, 0))  

    # Draw on the screen a green line which is 5 pixels wide.  
    pygame.draw.line(screen, (0, 255, 0), [0, 0], [50, 30], 5)  
    # Draw on the screen a green line which is 5 pixels wide.  
    pygame.draw.lines(screen, (0, 0, 0), False, [[0, 80], [50, 90], [200, 80], [220, 30]], 5)  

    # Draw a rectangle outline  
    pygame.draw.rect(screen, (0, 0, 0), [75, 10, 50, 20], 2)  

    # Draw a solid rectangle  
    pygame.draw.rect(screen, (0, 0, 0), [150, 10, 50, 20])  

    # This draw an ellipse outline, using a rectangle as the outside boundaries  
    pygame.draw.ellipse(screen, (255, 0, 0), [225, 10, 50, 20], 2)  

    # This draw a solid ellipse, using a rectangle as the outside boundaries  
    pygame.draw.ellipse(screen, (255, 0, 0), [300, 10, 50, 20])  

    # Draw a triangle using the polygon function  
    pygame.draw.polygon(screen, (0, 0, 0), [[100, 100], [0, 200], [200, 200]], 5)  

    # This draw a circle  
    pygame.draw.circle(screen, (0, 0, 255), [60, 250], 40)  

    # This draw an arc  
    pygame.draw.arc(screen, (0, 0, 0), [210, 75, 150, 125], 0, pi / 2, 2)  

    # This function must write after all the other drawing commands.  
    pygame.display.flip()  

# Quite the execution when clicking on close  
pygame.quit()  

輸出:

解釋-

在上例中,我們繪製了不同的形狀,如三角形、直線、矩形、橢圓形、圓形、弧形、實心圓和橢圓形。我們已經使用了 pygame.draw 函數根據形狀用合適的參數。

示例-使用 Pygame 開發貪食蛇遊戲

程序-


# Snake Tutorial Using Pygame 

import math
import random
import pygame
import tkinter as tk
from tkinter import messagebox

class cube(object):
    rows = 20
    w = 500

    def __init__(self, start, dirnx=1, dirny=0, color=(255, 0, 0)):
        self.pos = start
        self.dirnx = 1
        self.dirny = 0
        self.color = color

    def move(self, dirnx, dirny):
        self.dirnx = dirnx
        self.dirny = dirny
        self.pos = (self.pos[0] + self.dirnx, self.pos[1] + self.dirny)

    def draw(self, surface, eyes=False):
        dis = self.w // self.rows
        i = self.pos[0]
        j = self.pos[1]

        pygame.draw.rect(surface, self.color, (i * dis + 1, j * dis + 1, dis - 2, dis - 2))
        if eyes:
            centre = dis // 2
            radius = 3
            circleMiddle = (i * dis + centre - radius, j * dis + 8)
            circleMiddle2 = (i * dis + dis - radius * 2, j * dis + 8)
            pygame.draw.circle(surface, (0, 0, 0), circleMiddle, radius)
            pygame.draw.circle(surface, (0, 0, 0), circleMiddle2, radius)

# This class is defined for snake design and its movement
class snake(object):
    body = []
    turns = {}

    def __init__(self, color, pos):
        self.color = color
        self.head = cube(pos)
        self.body.append(self.head)
        self.dirnx = 0
        self.dirny = 1

    def move(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()

            keys = pygame.key.get_pressed()
            # It will manage the keys movement for the snake
            for key in keys:
                if keys[pygame.K_LEFT]:
                    self.dirnx = -1
                    self.dirny = 0
                    self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]

                elif keys[pygame.K_RIGHT]:
                    self.dirnx = 1
                    self.dirny = 0
                    self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]

                elif keys[pygame.K_UP]:
                    self.dirnx = 0
                    self.dirny = -1
                    self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]

                elif keys[pygame.K_DOWN]:
                    self.dirnx = 0
                    self.dirny = 1
                    self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]
        # Snake when hit the boundary wall
        for i, c in enumerate(self.body):
            p = c.pos[:]
            if p in self.turns:
                turn = self.turns[p]
                c.move(turn[0], turn[1])
                if i == len(self.body) - 1:
                    self.turns.pop(p)
            else:
                if c.dirnx == -1 and c.pos[0] <= 0:
                    c.pos = (c.rows - 1, c.pos[1])
                elif c.dirnx == 1 and c.pos[0] >= c.rows - 1:
                    c.pos = (0, c.pos[1])
                elif c.dirny == 1 and c.pos[1] >= c.rows - 1:
                    c.pos = (c.pos[0], 0)
                elif c.dirny == -1 and c.pos[1] <= 0:
                    c.pos = (c.pos[0], c.rows - 1)
                else:
                    c.move(c.dirnx, c.dirny)

    def reset(self, pos):
        self.head = cube(pos)
        self.body = []
        self.body.append(self.head)
        self.turns = {}
        self.dirnx = 0
        self.dirny = 1
# It will add the new cube in snake tail after every successful score
    def addCube(self):
        tail = self.body[-1]
        dx, dy = tail.dirnx, tail.dirny

        if dx == 1 and dy == 0:
            self.body.append(cube((tail.pos[0] - 1, tail.pos[1])))
        elif dx == -1 and dy == 0:
            self.body.append(cube((tail.pos[0] + 1, tail.pos[1])))
        elif dx == 0 and dy == 1:
            self.body.append(cube((tail.pos[0], tail.pos[1] - 1)))
        elif dx == 0 and dy == -1:
            self.body.append(cube((tail.pos[0], tail.pos[1] + 1)))

        self.body[-1].dirnx = dx
        self.body[-1].dirny = dy

    def draw(self, surface):
        for i, c in enumerate(self.body):
            if i == 0:
                c.draw(surface, True)
            else:
                c.draw(surface)

def drawGrid(w, rows, surface):
    sizeBtwn = w // rows

    x = 0
    y = 0
    for l in range(rows):
        x = x + sizeBtwn
        y = y + sizeBtwn
        # draw grid line
        pygame.draw.line(surface, (255, 255, 255), (x, 0), (x, w))
        pygame.draw.line(surface, (255, 255, 255), (0, y), (w, y))

# This class define for draw game surface
def redrawWindow(surface):
    global rows, width, s, snack
    # This is used to grid surface
    surface.fill((0, 0, 0))
    s.draw(surface)
    snack.draw(surface)
    drawGrid(width, rows, surface)
    pygame.display.update()

def randomSnack(rows, item):
    positions = item.body

    while True:
        x = random.randrange(rows)
        y = random.randrange(rows)
        if len(list(filter(lambda z: z.pos == (x, y), positions))) > 0:
            continue
        else:
            break

    return (x, y)

# Using Tkinter function to display message
def message_box(subject, content):
    root = tk.Tk()
    root.attributes("-topmost", True)
    root.withdraw()
    messagebox.showinfo(subject, content)
    try:
        root.destroy()
    except:
        pass

# main() function
def main():
    global width, rows, s, snack
    width = 500
    rows = 20
    win = pygame.display.set_mode((width, width))
    s = snake((255, 0, 0), (10, 10))
    snack = cube(randomSnack(rows, s), color=(0, 255, 0))
    flag = True

    clock = pygame.time.Clock()

    while flag:
        pygame.time.delay(50)
        clock.tick(10)
        s.move()
        if s.body[0].pos == snack.pos:
            s.addCube()
            snack = cube(randomSnack(rows, s), color=(0, 255, 0))

        for x in range(len(s.body)):
            if s.body[x].pos in list(map(lambda z: z.pos, s.body[x + 1:])):
                print('Score: \n', len(s.body))
                message_box('You Lost!\n', 'Play again...\n')
                s.reset((10, 10))
                break

        redrawWindow(win)

    pass

main()

輸出:

如果蛇觸碰到自己,它將終止遊戲並顯示以下信息。

我們可以點擊確定按鈕再次播放。我們可以在 Pycharm 終端看到我們的分數(我們已經使用了 Pycharm IDE 可以使用任何 Python IDE)。

複製上面的代碼,粘貼到你的 IDE 中,玩得開心。要了解 Pygame 的概念,請訪問我們完整的 pygame 教程。


原創文章,作者:簡單一點,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/128983.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
簡單一點的頭像簡單一點
上一篇 2024-10-03 23:25
下一篇 2024-10-03 23:25

相關推薦

  • Python中引入上一級目錄中函數

    Python中經常需要調用其他文件夾中的模塊或函數,其中一個常見的操作是引入上一級目錄中的函數。在此,我們將從多個角度詳細解釋如何在Python中引入上一級目錄的函數。 一、加入環…

    編程 2025-04-29
  • Python列表中負數的個數

    Python列表是一個有序的集合,可以存儲多個不同類型的元素。而負數是指小於0的整數。在Python列表中,我們想要找到負數的個數,可以通過以下幾個方面進行實現。 一、使用循環遍歷…

    編程 2025-04-29
  • 如何查看Anaconda中Python路徑

    對Anaconda中Python路徑即conda環境的查看進行詳細的闡述。 一、使用命令行查看 1、在Windows系統中,可以使用命令提示符(cmd)或者Anaconda Pro…

    編程 2025-04-29
  • Python計算陽曆日期對應周幾

    本文介紹如何通過Python計算任意陽曆日期對應周幾。 一、獲取日期 獲取日期可以通過Python內置的模塊datetime實現,示例代碼如下: from datetime imp…

    編程 2025-04-29
  • Python周杰倫代碼用法介紹

    本文將從多個方面對Python周杰倫代碼進行詳細的闡述。 一、代碼介紹 from urllib.request import urlopen from bs4 import Bea…

    編程 2025-04-29
  • Python程序需要編譯才能執行

    Python 被廣泛應用於數據分析、人工智能、科學計算等領域,它的靈活性和簡單易學的性質使得越來越多的人喜歡使用 Python 進行編程。然而,在 Python 中程序執行的方式不…

    編程 2025-04-29
  • Python清華鏡像下載

    Python清華鏡像是一個高質量的Python開發資源鏡像站,提供了Python及其相關的開發工具、框架和文檔的下載服務。本文將從以下幾個方面對Python清華鏡像下載進行詳細的闡…

    編程 2025-04-29
  • Python字典去重複工具

    使用Python語言編寫字典去重複工具,可幫助用戶快速去重複。 一、字典去重複工具的需求 在使用Python編寫程序時,我們經常需要處理數據文件,其中包含了大量的重複數據。為了方便…

    編程 2025-04-29
  • python強行終止程序快捷鍵

    本文將從多個方面對python強行終止程序快捷鍵進行詳細闡述,並提供相應代碼示例。 一、Ctrl+C快捷鍵 Ctrl+C快捷鍵是在終端中經常用來強行終止運行的程序。當你在終端中運行…

    編程 2025-04-29
  • 蝴蝶優化算法Python版

    蝴蝶優化算法是一種基於仿生學的優化算法,模仿自然界中的蝴蝶進行搜索。它可以應用於多個領域的優化問題,包括數學優化、工程問題、機器學習等。本文將從多個方面對蝴蝶優化算法Python版…

    編程 2025-04-29

發表回復

登錄後才能評論