最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python+Pygame編寫一個Pong游戲

 更新時間:2023年01月05日 16:20:06   作者:Leleprogrammer  
Pong游戲模擬了兩個打乒乓球的人,就是在兩條線中間有一個點在動,操縱器就是一個搖桿上有一個按鈕的那種。本文就來用Python中的Pygame庫編寫一個Pong小游戲

前言

這次,我們要用Pygame寫一個Pong游戲

先看看效果:

需要的模塊:Pygame

在python文件同目錄下新建resources文件夾,在文件夾中新建Pong文件夾,文件夾中放入兩個音頻文件

代碼教學

導入需要的模塊

import pygame
from pygame.locals import *
import random
import sys

定義常量

COUNTDOWN=USEREVENT+1
path="resources/Pong/"

定義Class類,初始化函數內的代碼:

pygame.init()
self.screen=pygame.display.set_mode((750,800))
pygame.display.set_caption("Pong")
 
self.mode="welcome"
self.ball=None
self.xspeed=0
self.yspeed=0
self.r=0
self.p1=None
self.p2=None
self.p1y=0
self.p2y=0
self.boardWidth=0
self.boardHeight=0
self.countdown=0
self.p1score=0
self.p2score=0
self.ballr=None
self.min=2
self.max=7
self.win=11
self.matchpoint=0
self.boardSpeed=self.max
self.ding=pygame.mixer.Sound(path+"ding.mp3")
self.bo=pygame.mixer.Sound(path+"bo.mp3")

定義listen函數

    def listen(self):
        for event in pygame.event.get():
            if event.type==QUIT:
                sys.exit()
            elif event.type==KEYDOWN:
                if event.key==K_k and self.mode=="welcome":
                    self.mode="playing"
                    self.ball=[750/2,800/2]
                    self.r=10
                    self.p1y=100
                    self.p2y=100
                    self.boardWidth=10
                    self.boardHeight=100
                    self.countdown=5
                    self.p1score=0
                    self.p2score=0
                    self.ballr=Rect(100,100,1,1)
                    pygame.time.set_timer(COUNTDOWN,1000)
            elif event.type==COUNTDOWN:
                self.countdown-=1
                if self.countdown==0:
                    self.countdown=0
                    pygame.time.set_timer(COUNTDOWN,0)
                    self.xspeed=random.randint(self.min,self.max) if random.randint(0,1)==0 else random.randint(-self.max,-self.min)
                    self.yspeed=random.randint(self.min,self.max) if random.randint(0,1)==0 else random.randint(-self.max,-self.min)
                else:
                    self.ding.play()

 定義draw函數,用于屏幕顯示,進入游戲時的ui:

        if self.mode=="welcome":
            self.screen.fill((0,0,0))
            ts=[
                "Welcome to Pong",
                "This game needs 2 players",
                "Press K to start"
            ]
            y=100
            for t in ts:
                to=self.print_text("simhei",35,t,(255,255,255))
                self.screen.blit(to,(100,y))
                y+=40

開始游戲后:

        elif self.mode=="playing":
            self.screen.fill((0,0,0))
            self.p1=pygame.draw.rect(self.screen,(255,255,255),(0,self.p1y,self.boardWidth,self.boardHeight))
            self.p2=pygame.draw.rect(self.screen,(255,255,255),(750-self.boardWidth,self.p2y,self.boardWidth,self.boardHeight))
            to=self.print_text("simhei",20,"Press WS to move",(255,255,255))
            to2=self.print_text("simhei",20,"Press ↑↓ to move",(255,255,255))
            tor=to.get_rect()
            tor2=to2.get_rect()
            d=10
            tor.bottomleft=d,800-d
            tor2.bottomright=750-d,800-d
            self.screen.blit(to,tor)
            self.screen.blit(to2,tor2)
            to=self.print_text("simhei",20,"Match Point!",(255,255,255))
            if self.matchpoint==1:
                self.screen.blit(to,(10,10))
            elif self.matchpoint==2:
                tor=to.get_rect()
                tor.topright=750-10,10
                self.screen.blit(to,tor)
            elif self.matchpoint==11:
                pygame.time.set_timer(COUNTDOWN,0)
                to=self.print_text("simhei",20,"Win!",(255,255,255))
                self.screen.blit(to,(10,10))
                to=self.print_text("simhei",20,"Lose!",(255,255,255))
                tor=to.get_rect()
                tor.topright=750-10,10
                self.screen.blit(to,tor)
            elif self.matchpoint==22:
                pygame.time.set_timer(COUNTDOWN,0)
                to=self.print_text("simhei",20,"Lose!",(255,255,255))
                self.screen.blit(to,(10,10))
                to=self.print_text("simhei",20,"Win!",(255,255,255))
                tor=to.get_rect()
                tor.topright=750-10,10
                self.screen.blit(to,tor)
            if not (self.matchpoint==11 or self.matchpoint==22):
                self.move()
                if not self.countdown:
                    pygame.draw.line(self.screen,(255,255,255),(750/2,0),(750/2,800),5)
                else:
                    to=self.print_text("simhei",72,str(self.countdown),(255,255,255))
                    tor=to.get_rect()
                    tor.midtop=750/2,50
                    self.screen.blit(to,tor)
            to=self.print_text("simhei",150,str(self.p1score),(255,255,255))
            to2=self.print_text("simhei",150,str(self.p2score),(255,255,255))
            tor=to.get_rect()
            tor2=to2.get_rect()
            tor.midtop=750/2/2,50
            tor2.midtop=750/2+750/2/2,50
            self.screen.blit(to,tor)
            self.screen.blit(to2,tor2)
            self.ballr=pygame.draw.circle(self.screen,(255,255,255),tuple(self.ball),self.r)

這里,為了可以顯示文字,我們自己寫一個print_text函數,用于顯示文字

    @staticmethod
    def print_text(name,size,text,color):
        font=pygame.font.SysFont(name,size)
        image=font.render(text,True,color)
        return image

定義一個move函數,用于移動小球和兩個玩家的“板”

    def move(self):
        if (not self.countdown) and (not (self.ballr.colliderect(self.p1) or self.ballr.colliderect(self.p2))):
            self.ball[0]+=self.xspeed
            self.ball[1]+=self.yspeed
            if self.ball[0]-self.r<=0:
                self.p2score+=1
                self.countdown=3
                self.ballr=Rect(100,100,1,1)
                self.ball=[750/2,800/2]
                pygame.time.set_timer(COUNTDOWN,1000)
            if self.ball[0]+self.r>=750:
                self.p1score+=1
                self.countdown=3
                self.ballr=Rect(100,100,1,1)
                self.ball=[750/2,800/2]
                pygame.time.set_timer(COUNTDOWN,1000)
            if self.ball[1]-self.r<=0 or self.ball[1]+self.r>=800:
                self.yspeed=-self.yspeed
                if self.yspeed<0:
                    self.yspeed=random.randint(-self.max,-self.min)
                else:
                    self.yspeed=random.randint(self.min,self.max)
                self.bo.play()
        elif self.ballr.colliderect(self.p1) or self.ballr.colliderect(self.p2):
            self.xspeed=-self.xspeed
            if self.xspeed<0:
                self.xspeed=random.randint(-self.max,-self.min)
            else:
                self.xspeed=random.randint(self.min,self.max)
            self.bo.play()
            self.ball[0]+=self.xspeed*2
        key=pygame.key.get_pressed()
        if key[K_w]:
            self.p1y-=self.boardSpeed
        if key[K_s]:
            self.p1y+=self.boardSpeed
        if key[K_UP]:
            self.p2y-=self.boardSpeed
        if key[K_DOWN]:
            self.p2y+=self.boardSpeed
        if self.p1y<=0:
            self.p1y=0
        if self.p2y<=0:
            self.p2y=0
        if self.p1y+self.boardHeight>=800:
            self.p1y=800-self.boardHeight
        if self.p2y+self.boardHeight>=800:
            self.p2y=800-self.boardHeight

再定義一個函數,用于檢查是否有玩家已經到達賽點

    def checkMatchPoint(self):
        self.matchpoint=0
        if self.p1score==self.win:
            self.matchpoint=11
        if self.p2score==self.win:
            self.matchpoint=22
        if self.p1score+1==self.win:
            self.matchpoint=1
        if self.p2score+1==self.win:
            self.matchpoint=2
        if self.p1score+1==self.win and self.p2score+1==self.win:
            self.win+=1

定義用于進入游戲主循環(huán)的函數run

    def run(self):
        clock=pygame.time.Clock()
        while True:
            clock.tick(60)
            self.listen()
            if not (self.matchpoint==11 or self.matchpoint==22):
                self.checkMatchPoint()
            self.draw()
            pygame.display.update()

在類的外面,創(chuàng)建game對象,并進入游戲主循環(huán)

game=Game()
game.run()

最終代碼

import pygame
from pygame.locals import *
import random
import sys
 
COUNTDOWN=USEREVENT+1
path="resources/Pong/"
 
class Game:
    def __init__(self):
        pygame.init()
        self.screen=pygame.display.set_mode((750,800))
        pygame.display.set_caption("Pong")
 
        self.mode="welcome"
        self.ball=None
        self.xspeed=0
        self.yspeed=0
        self.r=0
        self.p1=None
        self.p2=None
        self.p1y=0
        self.p2y=0
        self.boardWidth=0
        self.boardHeight=0
        self.countdown=0
        self.p1score=0
        self.p2score=0
        self.ballr=None
        self.min=2
        self.max=7
        self.win=11
        self.matchpoint=0
        self.boardSpeed=self.max
        self.ding=pygame.mixer.Sound(path+"ding.mp3")
        self.bo=pygame.mixer.Sound(path+"bo.mp3")
 
    def listen(self):
        for event in pygame.event.get():
            if event.type==QUIT:
                sys.exit()
            elif event.type==KEYDOWN:
                if event.key==K_k and self.mode=="welcome":
                    self.mode="playing"
                    self.ball=[750/2,800/2]
                    self.r=10
                    self.p1y=100
                    self.p2y=100
                    self.boardWidth=10
                    self.boardHeight=100
                    self.countdown=5
                    self.p1score=0
                    self.p2score=0
                    self.ballr=Rect(100,100,1,1)
                    pygame.time.set_timer(COUNTDOWN,1000)
            elif event.type==COUNTDOWN:
                self.countdown-=1
                if self.countdown==0:
                    self.countdown=0
                    pygame.time.set_timer(COUNTDOWN,0)
                    self.xspeed=random.randint(self.min,self.max) if random.randint(0,1)==0 else random.randint(-self.max,-self.min)
                    self.yspeed=random.randint(self.min,self.max) if random.randint(0,1)==0 else random.randint(-self.max,-self.min)
                else:
                    self.ding.play()
 
    def draw(self):
        if self.mode=="welcome":
            self.screen.fill((0,0,0))
            ts=[
                "Welcome to Pong",
                "This game needs 2 players",
                "Press K to start"
            ]
            y=100
            for t in ts:
                to=self.print_text("simhei",35,t,(255,255,255))
                self.screen.blit(to,(100,y))
                y+=40
        elif self.mode=="playing":
            self.screen.fill((0,0,0))
            self.p1=pygame.draw.rect(self.screen,(255,255,255),(0,self.p1y,self.boardWidth,self.boardHeight))
            self.p2=pygame.draw.rect(self.screen,(255,255,255),(750-self.boardWidth,self.p2y,self.boardWidth,self.boardHeight))
            to=self.print_text("simhei",20,"Press WS to move",(255,255,255))
            to2=self.print_text("simhei",20,"Press ↑↓ to move",(255,255,255))
            tor=to.get_rect()
            tor2=to2.get_rect()
            d=10
            tor.bottomleft=d,800-d
            tor2.bottomright=750-d,800-d
            self.screen.blit(to,tor)
            self.screen.blit(to2,tor2)
            to=self.print_text("simhei",20,"Match Point!",(255,255,255))
            if self.matchpoint==1:
                self.screen.blit(to,(10,10))
            elif self.matchpoint==2:
                tor=to.get_rect()
                tor.topright=750-10,10
                self.screen.blit(to,tor)
            elif self.matchpoint==11:
                pygame.time.set_timer(COUNTDOWN,0)
                to=self.print_text("simhei",20,"Win!",(255,255,255))
                self.screen.blit(to,(10,10))
                to=self.print_text("simhei",20,"Lose!",(255,255,255))
                tor=to.get_rect()
                tor.topright=750-10,10
                self.screen.blit(to,tor)
            elif self.matchpoint==22:
                pygame.time.set_timer(COUNTDOWN,0)
                to=self.print_text("simhei",20,"Lose!",(255,255,255))
                self.screen.blit(to,(10,10))
                to=self.print_text("simhei",20,"Win!",(255,255,255))
                tor=to.get_rect()
                tor.topright=750-10,10
                self.screen.blit(to,tor)
            if not (self.matchpoint==11 or self.matchpoint==22):
                self.move()
                if not self.countdown:
                    pygame.draw.line(self.screen,(255,255,255),(750/2,0),(750/2,800),5)
                else:
                    to=self.print_text("simhei",72,str(self.countdown),(255,255,255))
                    tor=to.get_rect()
                    tor.midtop=750/2,50
                    self.screen.blit(to,tor)
            to=self.print_text("simhei",150,str(self.p1score),(255,255,255))
            to2=self.print_text("simhei",150,str(self.p2score),(255,255,255))
            tor=to.get_rect()
            tor2=to2.get_rect()
            tor.midtop=750/2/2,50
            tor2.midtop=750/2+750/2/2,50
            self.screen.blit(to,tor)
            self.screen.blit(to2,tor2)
            self.ballr=pygame.draw.circle(self.screen,(255,255,255),tuple(self.ball),self.r)
 
    @staticmethod
    def print_text(name,size,text,color):
        font=pygame.font.SysFont(name,size)
        image=font.render(text,True,color)
        return image
 
    def move(self):
        if (not self.countdown) and (not (self.ballr.colliderect(self.p1) or self.ballr.colliderect(self.p2))):
            self.ball[0]+=self.xspeed
            self.ball[1]+=self.yspeed
            if self.ball[0]-self.r<=0:
                self.p2score+=1
                self.countdown=3
                self.ballr=Rect(100,100,1,1)
                self.ball=[750/2,800/2]
                pygame.time.set_timer(COUNTDOWN,1000)
            if self.ball[0]+self.r>=750:
                self.p1score+=1
                self.countdown=3
                self.ballr=Rect(100,100,1,1)
                self.ball=[750/2,800/2]
                pygame.time.set_timer(COUNTDOWN,1000)
            if self.ball[1]-self.r<=0 or self.ball[1]+self.r>=800:
                self.yspeed=-self.yspeed
                if self.yspeed<0:
                    self.yspeed=random.randint(-self.max,-self.min)
                else:
                    self.yspeed=random.randint(self.min,self.max)
                self.bo.play()
        elif self.ballr.colliderect(self.p1) or self.ballr.colliderect(self.p2):
            self.xspeed=-self.xspeed
            if self.xspeed<0:
                self.xspeed=random.randint(-self.max,-self.min)
            else:
                self.xspeed=random.randint(self.min,self.max)
            self.bo.play()
            self.ball[0]+=self.xspeed*2
        key=pygame.key.get_pressed()
        if key[K_w]:
            self.p1y-=self.boardSpeed
        if key[K_s]:
            self.p1y+=self.boardSpeed
        if key[K_UP]:
            self.p2y-=self.boardSpeed
        if key[K_DOWN]:
            self.p2y+=self.boardSpeed
        if self.p1y<=0:
            self.p1y=0
        if self.p2y<=0:
            self.p2y=0
        if self.p1y+self.boardHeight>=800:
            self.p1y=800-self.boardHeight
        if self.p2y+self.boardHeight>=800:
            self.p2y=800-self.boardHeight
 
    def checkMatchPoint(self):
        self.matchpoint=0
        if self.p1score==self.win:
            self.matchpoint=11
        if self.p2score==self.win:
            self.matchpoint=22
        if self.p1score+1==self.win:
            self.matchpoint=1
        if self.p2score+1==self.win:
            self.matchpoint=2
        if self.p1score+1==self.win and self.p2score+1==self.win:
            self.win+=1
 
    def run(self):
        clock=pygame.time.Clock()
        while True:
            clock.tick(60)
            self.listen()
            if not (self.matchpoint==11 or self.matchpoint==22):
                self.checkMatchPoint()
            self.draw()
            pygame.display.update()
 
game=Game()
game.run()

到此這篇關于Python+Pygame編寫一個Pong游戲的文章就介紹到這了,更多相關Python Pygame Pong游戲內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • python?Copula?實現繪制散點模型

    python?Copula?實現繪制散點模型

    這篇文章主要介紹了python?Copula實現繪制散點模型,文章圍繞主題展開詳細的內容介紹,具有一定的參考價值,需要的朋友可以參考一下
    2022-07-07
  • Python裝飾器如何實現修復過程解析

    Python裝飾器如何實現修復過程解析

    這篇文章主要介紹了Python裝飾器如何實現修復過程解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-09-09
  • Python定時任務隨機時間執(zhí)行的實現方法

    Python定時任務隨機時間執(zhí)行的實現方法

    這篇文章主要介紹了Python定時任務隨機時間執(zhí)行的實現方法,文中給大家提到了python定時執(zhí)行任務的三種方式 ,本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下
    2019-08-08
  • Python標準庫之urllib和urllib3的使用及說明

    Python標準庫之urllib和urllib3的使用及說明

    這篇文章主要介紹了Python標準庫之urllib和urllib3使用及說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-12-12
  • 微信跳一跳python自動代碼解讀1.0

    微信跳一跳python自動代碼解讀1.0

    這篇文章主要為大家詳細介紹了微信跳一跳python自動代碼解讀1.0,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-01-01
  • 圖解Python變量與賦值

    圖解Python變量與賦值

    Python是一門獨特的語言,與C語言有很大區(qū)別,初學Python很多萌新表示對變量與賦值不理解,這里就大家介紹一下,需要的朋友可以參考下
    2018-04-04
  • Python中sklearn實現交叉驗證示例分析

    Python中sklearn實現交叉驗證示例分析

    這篇文章主要介紹了Python中sklearn實現交叉驗證,本文python的版本為3.8,各個版本之間函數名字略有不同,但是原理都是一樣的,集成開發(fā)環(huán)境使用的是Anaconda的Spyder,需要的朋友可以參考下
    2023-08-08
  • python保存兩位小數的多種方法匯總

    python保存兩位小數的多種方法匯總

    很多小伙伴在學習python的時候可能會遇到對數據進行格式化輸出的需求,其中最常見的需求為:保留幾位小數,下面這篇文章主要給大家介紹了關于python保存兩位小數的多種方法,需要的朋友可以參考下
    2021-12-12
  • Python爬蟲之網絡請求

    Python爬蟲之網絡請求

    這篇文章主要介紹了Python爬蟲之網絡請求,文章基于Python展開對網絡請求的相關介紹,需要的小伙伴可以參考一下
    2022-04-04
  • keras 特征圖可視化實例(中間層)

    keras 特征圖可視化實例(中間層)

    今天小編就為大家分享一篇keras 特征圖可視化實例(中間層),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-01-01

最新評論

积石山| 镇坪县| 华宁县| 永嘉县| 赤壁市| 云阳县| 微山县| 临澧县| 安吉县| 历史| 镶黄旗| 南木林县| 浦北县| 友谊县| 安西县| 措勤县| 靖远县| 元氏县| 澄城县| 昌邑市| 荣成市| 金乡县| 上蔡县| 哈巴河县| 英吉沙县| 隆子县| 四子王旗| 崇左市| 邵武市| 临泽县| 静乐县| 奉新县| 腾冲县| 大埔县| 敦化市| 浪卡子县| 集贤县| 广饶县| 荆州市| 江北区| 建水县|