Python 2D双人乒乓球小游戏

Python 2D双人乒乓球小游戏

Python 2D双人乒乓球小游戏

"""
   2D双人乒乓球小游戏
"""
__author__ = '李兴球'
__date__ = '2019年3月30日'

import random
import pygame
from pygame.locals import *

def main():
    """主要函数"""
    global collide_delay_counter,game_over,end_string,up_score_string,down_score_string
    width,height = 500,800
    pygame.init()
    screen = pygame.display.set_mode((width,height))
    pygame.display.set_caption("2D双人乒乓球小游戏")

    background = pygame.image.load("场地.png")

    Referee = pygame.image.load("cp.png")    # 裁判
    up_score_string = pygame.Surface((0,0))
    down_score_string = pygame.Surface((0,0))
    collide_delay_counter = 0                # 防止重复碰撞的变量    

    images_bat = "蓝拍右.png","红拍左.png"
    images_bat = [ pygame.image.load(image) for image in images_bat]    

    images_player = "人右.png","人左.png"
    images_player = [ pygame.image.load(image) for image in images_player]

    image_ball = pygame.image.load("ball2.png")
    # 生成球
    ball = Ball(image_ball,screen) 
    
    # 下玩家建立
    keys = [K_UP,K_DOWN,K_LEFT,K_RIGHT]
    position = (width//2,height-50)
    player_down = Player(images_player[0],keys,position)

    # 上玩家建立
    keys = [K_w,K_s,K_a,K_d]
    position = (width//2, 50)
    player_up = Player(images_player[1],keys,position)

    # 下拍子建立
    bat_down = Bat(images_bat[0],player_down,1)
    # 上拍子建立
    bat_up = Bat(images_bat[1],player_up,-1)         

    myfont = pygame.font.Font("msyh.ttf",32)
    scorefont = pygame.font.Font("msyh.ttf",22)
    蓝方赢 = myfont.render("蓝方赢",True,(5,0,255))
    红方赢 = myfont.render("红方赢",True,(205,0,5))
    end_string = ""
    game_over = False
    
    clock = pygame.time.Clock()
    running = True
    while running:
        if collide_delay_counter>0:collide_delay_counter-=1
        for event in pygame.event.get():
            if event.type == QUIT:running = False
        player_down.key_detect()
        player_down.update()
        player_up.key_detect()
        player_up.update()

        bat_down.update()
        bat_up.update()
        ball.update()        
        
        collide_check(ball,bat_up,bat_down,player_up,player_down,scorefont)
        game_over_check(ball,height,蓝方赢,红方赢)
        
        screen.blit(background,(0,0))
        screen.blit(player_down.image,player_down.rect)
        screen.blit(player_up.image,player_up.rect)
        screen.blit(bat_down.image,bat_down.rect)
        screen.blit(bat_up.image,bat_up.rect)
        if not game_over: screen.blit(ball.image,ball.rect)
        if game_over == True:
            screen.blit(end_string,(width//2,height//2))
            screen.blit(Referee,(width//2+50,height//2+50))
            
        screen.blit(up_score_string,(25,30))
        screen.blit(down_score_string,(width-50,height-60))        
        pygame.display.update()
        clock.tick(60)

    pygame.quit()

You must log in to read the rest of this article. Please log in or register as a user.