The fourth article [Legendary Pistachio Weibo Series] Python micro-project technical point case example: Judge of beauty’s appearance

Legendary Pistachio Weibo Series

  • Series Weibo Directory
    • Python micro-project technical point case example series
  • Weibo directory
    • 1. Micro project goals
    • 2. Prototype sample code
    • 3. Expand ideas
    • 4. Add sample codes for different types of beauties
    • 5. Sample code for increasing difficulty level
    • 6. Add sample code for special props
    • 7. Design sample code for level system
    • 8. Add sound effects and background music sample code
    • 9. Multiplayer game mode sample code
    • 10. Ranking and achievement system sample code
    • 11. Add animation effect sample code

Series Weibo Directory

Python micro-project technical point case example series

Weibo directory

1. Micro project goals

Insert image description here
Use pygame to implement the object-oriented sample code of a small game of rating beauties, rate beauties, appreciate beautiful beauties with good looks, and make middle school programming fun.

2. Prototype sample code

Insert image description hereThe following is a sample code for using Pygame to implement an object-oriented program for rating beauties:

import pygame
import random

# 初始化游戏
pygame.init()

# 设置窗口大小和标题
screen_width = 800screen_height = 600
window = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("给美女打分")

# 定义美女类
class Beauty(pygame.sprite.Sprite):
    __init__(self, x, y):
       ().__init__()
        self.image = pygame.image.loadbeauty.png")  # 美女的
        self.rect = self.image.get_rect()
 self.rect.center = (x, y)
    
 def update(self):
        pass

# 定义分数类
class Score(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__()
        self.score = 0
        self.font = pygame.font.Font(None, 36)
        self.text = self.font.render("Score: " + str(self.score), True, (255, 255, 255))
        self.rect = self.text.get_rect()
        self.rect.center = (x, y)
    
    def update(self):
        self.text = self.font.render("Score: " + str(self.score), True, (255, 255, 255))

# 创建精灵组
all_sprites = pygame.sprite.Group()

# 创建美女对象
beauty = Beauty(screen_width // 2, screen_height // 2)
all_sprites.add(beauty)

# 创建分数对象
score = Score(screen_width // 2, 50)
all_sprites.add(score)

# 游戏主循环
running = True
clock = pygame.time.Clock()
while running:
    clock.tick(60)
    
    # 事件处理
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    
    # 更新精灵组中的所有精灵
    all_sprites.update()
    
    # 绘制背景
    window.fill((0, 0, 0))
    
    # 绘制所有精灵
    all_sprites.draw(window)
    
    # 刷新屏幕
    pygame.display.flip()

# 退出游戏
pygame.quit()

Please note that in the above code, a beauty picture named "beauty.png" needs to be prepared as a resource file required for the program to run. You can replace it with other pictures of beautiful women according to your needs. After running the code, you can use your mouse to rate beauties in the window. The program will display the current score in the window title bar.

3. Expand ideas

Insert image description hereUsing Pygame to implement an object-oriented beauty scoring program is just a simple example. There can be many extension ideas. Here are some possible extension ideas:

  1. Add different types of beauties: You can create multiple beauties objects and use different picture resources to represent different types of beauties. Each beauty can have her own score and special attributes.

  2. Increase the difficulty level: The difficulty of the game can be adjusted according to the player's score, such as increasing the movement speed and appearance frequency of beauties or increasing the difficulty of obtaining scores.

  3. Add special props: Some special props can be added to the game. Players can click to obtain the props to increase scores or change the rules of the game.

  4. Design level system: You can design multiple levels, each with different beauties and game goals. Players need to score the beauties as required to pass the level.

  5. Add sound effects and background music: You can add sound effects and background music to the game to increase the fun and atmosphere of the game.

  6. Multiplayer game mode: You can add a multiplayer game mode, allowing multiple players to participate in scoring at the same time and compare who has higher scores.

  7. Ranking and Achievement System: Players’ highest scores can be recorded, and a ranking and achievement system are provided to allow players to compete and compare.

  8. Add animation effects: You can add some animation effects to the appearance, disappearance or scoring of beauties to make the game more vivid and interesting.

These are just some possible expansion ideas. You can design and implement more interesting functions and gameplay according to your own creativity and needs. Using the rich functionality and flexibility provided by Pygame, you can extend this simple scoring program into a fun game.

4. Add sample codes for different types of beauties

Insert image description hereHere is sample code expanded on different types of beauties:

import pygame
import random

# 初始化游戏
pygame.init()

# 设置窗口大小和标题
screen_width = 800
screen_height = 600
window = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("给美女打分")

# 定义美女类
class Beauty(pygame.sprite.Sprite):
    def __init__(self, x, y, image, score, special_attribute):
        super().__init__()
        self.image = pygame.image.load(image)  # 美女的图片资源
        self.rect = self.image.get_rect()
        self.rect.center = (x, y)
        self.score = score  # 美女的得分
        self.special_attribute = special_attribute  # 美女的特殊属性

    def update(self):
        pass

# 定义分数类
class Score(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__()
        self.score = 0
        self.font = pygame.font.Font(None, 36)
        self.text = self.font.render("Score: " + str(self.score), True, (255, 255, 255))
        self.rect = self.text.get_rect()
        self.rect.center = (x, y)

    def update(self):
        self.text = self.font.render("Score: " + str(self.score), True, (255, 255, 255))

# 创建精灵组
all_sprites = pygame.sprite.Group()

# 创建美女对象
beauty1 = Beauty(screen_width // 2 - 100, screen_height // 2, "beauty1.png", 10, "可爱")
beauty2 = Beauty(screen_width // 2 + 100, screen_height // 2, "beauty2.png", 20, "靓丽")
all_sprites.add(beauty1)
all_sprites.add(beauty2)

# 创建分数对象
score = Score(screen_width // 2, 50)
all_sprites.add(score)

# 游戏主循环
running = True
clock = pygame.time.Clock()
while running:
    clock.tick(60)

    # 事件处理
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # 更新精灵组中的所有精灵
    all_sprites.update()

    # 绘制背景
    window.fill((0, 0, 0))

    # 绘制所有精灵
    all_sprites.draw(window)

    # 刷新屏幕
    pygame.display.flip()

# 退出游戏
pygame.quit()

In this sample code, we create two different types of beauty objects: beauty1 and beauty2. They use different image resources ("beauty1.png" and "beauty2.png") respectively, and have different scores and special attributes. You can add more beauty objects according to your needs and set different attributes for each beauty.

Note: You need to prepare the corresponding beauty picture resources, name them "beauty1.png" and "beauty2.png", and put them in the same directory as the sample code.

5. Sample code for increasing difficulty level

Insert image description hereHere's example code for adjusting game difficulty based on player score:

import pygame
import random

# 初始化游戏
pygame.init()

# 设置窗口大小和标题
screen_width = 800
screen_height = 600
window = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("给美女打分")

# 定义美女类
class Beauty(pygame.sprite.Sprite):
    def __init__(self, x, y, image, score, special_attribute, speed):
        super().__init__()
        self.image = pygame.image.load(image)  # 美女的图片资源
        self.rect = self.image.get_rect()
        self.rect.center = (x, y)
        self.score = score  # 美女的得分
        self.special_attribute = special_attribute  # 美女的特殊属性
        self.speed = speed  # 美女的移动速度

    def update(self):
        self.rect.x += self.speed

# 定义分数类
class Score(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__()
        self.score = 0
        self.font = pygame.font.Font(None, 36)
        self.text = self.font.render("Score: " + str(self.score), True, (255, 255, 255))
        self.rect = self.text.get_rect()
        self.rect.center = (x, y)

    def update(self):
        self.text = self.font.render("Score: " + str(self.score), True, (255, 255, 255))

# 创建精灵组
all_sprites = pygame.sprite.Group()

# 创建美女对象
beauty1 = Beauty(screen_width // 2 - 100, screen_height // 2, "beauty1.png", 10, "可爱", 2)
beauty2 = Beauty(screen_width // 2 + 100, screen_height // 2, "beauty2.png", 20, "性感", 3)
all_sprites.add(beauty1)
all_sprites.add(beauty2)

# 创建分数对象
score = Score(screen_width // 2, 50)
all_sprites.add(score)

# 游戏主循环
running = True
clock = pygame.time.Clock()
spawn_timer = 0
difficulty_level = 1
while running:
    clock.tick(60)

    # 事件处理
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # 更新精灵组中的所有精灵
    all_sprites.update()

    # 控制美女的出现频率和移动速度
    spawn_timer += 1
    if spawn_timer >= 60 / difficulty_level:
        beauty = Beauty(screen_width + 50, random.randint(50, screen_height - 50), "beauty1.png", 10, "可爱", random.randint(2, 4))
        all_sprites.add(beauty)
        spawn_timer = 0
    
    # 碰撞检测
    collisions = pygame.sprite.spritecollide(beauty1, all_sprites, True)
    for collision in collisions:
        score.score += collision.score
    
    # 根据得分调整难度
    if score.score >= 50 and difficulty_level < 3:
        difficulty_level = 2
    elif score.score >= 100 and difficulty_level < 4:
        difficulty_level = 3

    # 绘制背景
    window.fill((0, 0, 0))

    # 绘制所有精灵
    all_sprites.draw(window)

    # 刷新屏幕
    pygame.display.flip()

# 退出游戏
pygame.quit()

In this sample code, we introduce a spawn_timervariable to control the frequency of beautiful women. It is incremented every frame spawn_timerand when it reaches a certain value, a new beauty object is created and spawn_timerreset to 0. As the score increases, difficulty_levelthe variables will gradually increase, thus affecting the movement speed and frequency of beauty.

Note: You need to prepare the corresponding beauty picture resources, name them "beauty1.png" and "beauty2.png", and put them in the same directory as the sample code.

6. Add sample code for special props

Insert image description hereHere is sample code for adding special props:

import pygame
import random

# 初始化游戏
pygame.init()

# 设置窗口大小和标题
screen_width = 800
screen_height = 600
window = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("给美女打分")

# 定义美女类
class Beauty(pygame.sprite.Sprite):
    def __init__(self, x, y, image, score, special_attribute, speed):
        super().__init__()
        self.image = pygame.image.load(image)  # 美女的图片资源
        self.rect = self.image.get_rect()
        self.rect.center = (x, y)
        self.score = score  # 美女的得分
        self.special_attribute = special_attribute  # 美女的特殊属性
        self.speed = speed  # 美女的移动速度

    def update(self):
        self.rect.x += self.speed

# 定义分数类
class Score(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__()
        self.score = 0
        self.font = pygame.font.Font(None, 36)
        self.text = self.font.render("Score: " + str(self.score), True, (255, 255, 255))
        self.rect = self.text.get_rect()
        self.rect.center = (x, y)

    def update(self):
        self.text = self.font.render("Score: " + str(self.score), True, (255, 255, 255))

# 定义道具类
class PowerUp(pygame.sprite.Sprite):
    def __init__(self, x, y, image, effect):
        super().__init__()
        self.image = pygame.image.load(image)  # 道具的图片资源
        self.rect = self.image.get_rect()
        self.rect.center = (x, y)
        self.effect = effect  # 道具的效果

    def update(self):
        pass

# 创建精灵组
all_sprites = pygame.sprite.Group()

# 创建美女对象
beauty1 = Beauty(screen_width // 2 - 100, screen_height // 2, "beauty1.png", 10, "可爱", 2)
beauty2 = Beauty(screen_width // 2 + 100, screen_height // 2, "beauty2.png", 20, "性感", 3)
all_sprites.add(beauty1)
all_sprites.add(beauty2)

# 创建分数对象
score = Score(screen_width // 2, 50)
all_sprites.add(score)

# 创建道具对象
power_up = PowerUp(screen_width // 2, screen_height // 2, "power_up.png", "double_score")
all_sprites.add(power_up)

# 游戏主循环
running = True
clock = pygame.time.Clock()
spawn_timer = 0
difficulty_level = 1
while running:
    clock.tick(60)

    # 事件处理
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN:
            if power_up.rect.collidepoint(event.pos):
                if power_up.effect == "double_score":
                    score.score *= 2
                    power_up.kill()

    # 更新精灵组中的所有精灵
    all_sprites.update()

    # 控制美女的出现频率和移动速度
    spawn_timer += 1
    if spawn_timer >= 60 / difficulty_level:
        beauty = Beauty(screen_width + 50, random.randint(50, screen_height - 50), "beauty1.png", 10, "可爱", random.randint(2, 4))
        all_sprites.add(beauty)
        spawn_timer = 0
    
    # 碰撞检测
    collisions = pygame.sprite.spritecollide(beauty1, all_sprites, True)
    for collision in collisions:
        score.score += collision.score

    # 绘制背景
    window.fill((0, 0, 0))

    # 绘制所有精灵
    all_sprites.draw(window)

    # 刷新屏幕
    pygame.display.flip()

# 退出游戏
pygame.quit()

In this sample code, we create a PowerUpclass to represent props that can be obtained by clicking on them. When we click on the props, we increase the score or change the game rules according to the effect of the props. In the example, the effect of the prop is to double the score. When the player clicks on the prop, the score will be doubled.

Note: You need to prepare the corresponding beauty image resources ("beauty1.png" and "beauty2.png") and prop image resources ("power_up.png"), and place them in the same directory as the sample code.

7. Design sample code for level system

Insert image description hereHere is sample code for designing a level system:

import pygame
import random

# 初始化游戏
pygame.init()

# 设置窗口大小和标题
screen_width = 800
screen_height = 600
window = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("给美女打分")

# 定义美女类
class Beauty(pygame.sprite.Sprite):
    def __init__(self, x, y, image, score, special_attribute, speed):
        super().__init__()
        self.image = pygame.image.load(image)  # 美女的图片资源
        self.rect = self.image.get_rect()
        self.rect.center = (x, y)
        self.score = score  # 美女的得分
        self.special_attribute = special_attribute  # 美女的特殊属性
        self.speed = speed  # 美女的移动速度

    def update(self):
        self.rect.x += self.speed

# 定义分数类
class Score(pygame.sprite.Sprite):
    def __init__(self, x, y, target_score):
        super().__init__()
        self.score = 0
        self.target_score = target_score  # 目标得分
        self.font = pygame.font.Font(None, 36)
        self.text = self.font.render("Score: " + str(self.score), True, (255, 255, 255))
        self.rect = self.text.get_rect()
        self.rect.center = (x, y)

    def update(self):
        self.text = self.font.render("Score: " + str(self.score), True, (255, 255, 255))

# 定义关卡类
class Level:
    def __init__(self, target_score, beauties):
        self.target_score = target_score  # 目标得分
        self.beauties = beauties  # 美女列表

    def is_completed(self, score):
        return score >= self.target_score

# 创建精灵组
all_sprites = pygame.sprite.Group()

# 创建关卡列表
levels = [
    Level(50, [
        Beauty(screen_width // 2 - 100, screen_height // 2, "beauty1.png", 10, "可爱", 2),
        Beauty(screen_width // 2 + 100, screen_height // 2, "beauty2.png", 20, "性感", 3)
    ]),
    Level(100, [
        Beauty(screen_width // 2 - 100, screen_height // 2, "beauty3.png", 15, "甜美", 3),
        Beauty(screen_width // 2 + 100, screen_height // 2, "beauty4.png", 25, "迷人", 4)
    ])
]

current_level = 0
level = levels[current_level]

# 创建分数对象
score = Score(screen_width // 2, 50, level.target_score)
all_sprites.add(score)

# 将当前关卡的美女添加到精灵组中
for beauty in level.beauties:
    all_sprites.add(beauty)

# 游戏主循环
running = True
clock = pygame.time.Clock()
spawn_timer = 0
difficulty_level = 1
while running:
    clock.tick(60)

    # 事件处理
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # 更新精灵组中的所有精灵
    all_sprites.update()

    # 控制美女的出现频率和移动速度
    spawn_timer += 1
    if spawn_timer >= 60 / difficulty_level:
        beauty = random.choice(level.beauties)
        beauty = Beauty(screen_width + 50, random.randint(50, screen_height - 50), beauty.image, beauty.score, beauty.special_attribute, random.randint(2, 4))
        all_sprites.add(beauty)
        spawn_timer = 0
    
    # 碰撞检测
    collisions = pygame.sprite.spritecollide(beauty, all_sprites, True)
    for collision in collisions:
        score.score += collision.score

    # 检查当前关卡是否完成
    if level.is_completed(score.score):
        current_level += 1
        if current_level < len(levels):
            level = levels[current_level]
            score = Score(screen_width // 2, 50, level.target_score)
            all_sprites.add(score)
            for beauty in level.beauties:
                all_sprites.add(beauty)
        else:
            running = False

    # 绘制背景
    window.fill((0, 0, 0))

    # 绘制所有精灵
    all_sprites.draw(window)

    # 刷新屏幕
    pygame.display.flip()

# 退出游戏
pygame.quit()

In this sample code, we create a Levelclass to represent levels, each with a target score and a set of beauties. In the main loop of the game, we check whether the score of the current level reaches the target score, and if so, go to the next level. If all levels are completed, the game is over.

Note: You need to prepare the corresponding beauty image resources ("beauty1.png", "beauty2.png", "beauty3.png", "beauty4.png") and put them in the same directory as the sample code. Each level can be designed with different beauties and target scores according to needs.

8. Add sound effects and background music sample code

Insert image description hereHere is sample code for adding sound effects and background music to your game:

import pygame
import random

# 初始化游戏
pygame.init()

# 设置窗口大小和标题
screen_width = 800
screen_height = 600
window = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("给美女打分")

# 加载背景音乐
pygame.mixer.music.load("background_music.mp3")
pygame.mixer.music.set_volume(0.5)  # 设置音量
pygame.mixer.music.play(-1)  # 循环播放背景音乐

# 加载音效
score_sound = pygame.mixer.Sound("score_sound.wav")

# 定义美女类
class Beauty(pygame.sprite.Sprite):
    def __init__(self, x, y, image, score, special_attribute, speed):
        super().__init__()
        self.image = pygame.image.load(image)  # 美女的图片资源
        self.rect = self.image.get_rect()
        self.rect.center = (x, y)
        self.score = score  # 美女的得分
        self.special_attribute = special_attribute  # 美女的特殊属性
        self.speed = speed  # 美女的移动速度

    def update(self):
        self.rect.x += self.speed

# 定义分数类
class Score(pygame.sprite.Sprite):
    def __init__(self, x, y, target_score):
        super().__init__()
        self.score = 0
        self.target_score = target_score  # 目标得分
        self.font = pygame.font.Font(None, 36)
        self.text = self.font.render("Score: " + str(self.score), True, (255, 255, 255))
        self.rect = self.text.get_rect()
        self.rect.center = (x, y)

    def update(self):
        self.text = self.font.render("Score: " + str(self.score), True, (255, 255, 255))

# 定义关卡类
class Level:
    def __init__(self, target_score, beauties):
        self.target_score = target_score  # 目标得分
        self.beauties = beauties  # 美女列表

    def is_completed(self, score):
        return score >= self.target_score

# 创建精灵组
all_sprites = pygame.sprite.Group()

# 创建关卡列表
levels = [
    Level(50, [
        Beauty(screen_width // 2 - 100, screen_height // 2, "beauty1.png", 10, "可爱", 2),
        Beauty(screen_width // 2 + 100, screen_height // 2, "beauty2.png", 20, "性感", 3)
    ]),
    Level(100, [
        Beauty(screen_width // 2 - 100, screen_height // 2, "beauty3.png", 15, "甜美", 3),
        Beauty(screen_width // 2 + 100, screen_height // 2, "beauty4.png", 25, "迷人", 4)
    ])
]

current_level = 0
level = levels[current_level]

# 创建分数对象
score = Score(screen_width // 2, 50, level.target_score)
all_sprites.add(score)

# 将当前关卡的美女添加到精灵组中
for beauty in level.beauties:
    all_sprites.add(beauty)

# 游戏主循环
running = True
clock = pygame.time.Clock()
spawn_timer = 0
difficulty_level = 1
while running:
    clock.tick(60)

    # 事件处理
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # 更新精灵组中的所有精灵
    all_sprites.update()

    # 控制美女的出现频率和移动速度
    spawn_timer += 1
    if spawn_timer >= 60 / difficulty_level:
        beauty = random.choice(level.beauties)
        beauty = Beauty(screen_width + 50, random.randint(50, screen_height - 50), beauty.image, beauty.score, beauty.special_attribute, random.randint(2, 4))
        all_sprites.add(beauty)
        spawn_timer = 0
    
    # 碰撞检测
    collisions = pygame.sprite.spritecollide(beauty, all_sprites, True)
    for collision in collisions:
        score.score += collision.score
        score_sound.play()  # 播放得分音效

    # 检查当前关卡是否完成
    if level.is_completed(score.score):
        current_level += 1
        if current_level < len(levels):
            level = levels[current_level]
            score = Score(screen_width // 2, 50, level.target_score)
            all_sprites.add(score)
            for beauty in level.beauties:
                all_sprites.add(beauty)
        else:
            running = False

    # 绘制背景
    window.fill((0, 0, 0))

    # 绘制所有精灵
    all_sprites.draw(window)

    # 刷新屏幕
    pygame.display.flip()

# 停止背景音乐
pygame.mixer.music.stop()

# 退出游戏
pygame.quit()

In this sample code, we use pygame.mixer.musica module to load and play background music. We also use pygame.mixer.Sounda class to load the sound effect file and play the score sound effect when the beauty is hit.

Note: You need to prepare the corresponding music file ("background_music.mp3") and sound effect file ("score_sound.wav"), and put them in the same directory as the sample code. Make sure the file paths for the music files and sound effects files are correct.

9. Multiplayer game mode sample code

Insert image description hereHere is sample code to add multiplayer mode:

import pygame
import random

# 初始化游戏
pygame.init()

# 设置窗口大小和标题
screen_width = 800
screen_height = 600
window = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("给美女打分 - 多人游戏模式")

# 加载背景音乐
pygame.mixer.music.load("background_music.mp3")
pygame.mixer.music.set_volume(0.5)  # 设置音量
pygame.mixer.music.play(-1)  # 循环播放背景音乐

# 加载音效
score_sound = pygame.mixer.Sound("score_sound.wav")

# 定义美女类
class Beauty(pygame.sprite.Sprite):
    def __init__(self, x, y, image, score, special_attribute, speed):
        super().__init__()
        self.image = pygame.image.load(image)  # 美女的图片资源
        self.rect = self.image.get_rect()
        self.rect.center = (x, y)
        self.score = score  # 美女的得分
        self.special_attribute = special_attribute  # 美女的特殊属性
        self.speed = speed  # 美女的移动速度

    def update(self):
        self.rect.x += self.speed

# 定义分数类
class Score(pygame.sprite.Sprite):
    def __init__(self, x, y, player_name):
        super().__init__()
        self.score = 0
        self.player_name = player_name  # 玩家名称
        self.font = pygame.font.Font(None, 36)
        self.text = self.font.render(self.player_name + ": " + str(self.score), True, (255, 255, 255))
        self.rect = self.text.get_rect()
        self.rect.center = (x, y)

    def update(self):
        self.text = self.font.render(self.player_name + ": " + str(self.score), True, (255, 255, 255))

# 定义关卡类
class Level:
    def __init__(self, target_score, beauties):
        self.target_score = target_score  # 目标得分
        self.beauties = beauties  # 美女列表

    def is_completed(self, score):
        return score >= self.target_score

# 创建精灵组
all_sprites = pygame.sprite.Group()

# 创建关卡列表
levels = [
    Level(50, [
        Beauty(screen_width // 2 - 100, screen_height // 2, "beauty1.png", 10, "可爱", 2),
        Beauty(screen_width // 2 + 100, screen_height // 2, "beauty2.png", 20, "性感", 3)
    ]),
    Level(100, [
        Beauty(screen_width // 2 - 100, screen_height // 2, "beauty3.png", 15, "甜美", 3),
        Beauty(screen_width // 2 + 100, screen_height // 2, "beauty4.png", 25, "迷人", 4)
    ])
]

num_players = 2  # 玩家数量
players = []  # 玩家列表

# 创建玩家对象和分数对象
for i in range(num_players):
    player_name = "Player " + str(i+1)
    player_score = Score(screen_width // 2, 50 + i*50, player_name)
    players.append(player_score)
    all_sprites.add(player_score)

current_level = 0
level = levels[current_level]

# 将当前关卡的美女添加到精灵组中
for beauty in level.beauties:
    all_sprites.add(beauty)

# 游戏主循环
running = True
clock = pygame.time.Clock()
spawn_timer = 0
difficulty_level = 1
while running:
    clock.tick(60)

    # 事件处理
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN:
            mouse_pos = pygame.mouse.get_pos()
            clicked_sprites = [s for s in all_sprites if s.rect.collidepoint(mouse_pos)]
            for sprite in clicked_sprites:
                if isinstance(sprite, Beauty):
                    for player in players:
                        if player.rect.collidepoint(mouse_pos):
                            player.score += sprite.score
                            score_sound.play()  # 播放得分音效

    # 更新精灵组中的所有精灵
    all_sprites.update()

    # 控制美女的出现频率和移动速度
    spawn_timer += 1
    if spawn_timer >= 60 / difficulty_level:
        beauty = random.choice(level.beauties)
        beauty = Beauty(screen_width + 50, random.randint(50, screen_height - 50), beauty.image, beauty.score, beauty.special_attribute, random.randint(2, 4))
        all_sprites.add(beauty)
        spawn_timer = 0
    
    # 检查当前关卡是否完成
    if level.is_completed(players[0].score):
        current_level += 1
        if current_level < len(levels):
            level = levels[current_level]
            for player in players:
                player.score = 0
            for beauty in level.beauties:
                all_sprites.add(beauty)
        else:
            running = False

    # 绘制背景
    window.fill((0, 0, 0))

    # 绘制所有精灵
    all_sprites.draw(window)

    # 刷新屏幕
    pygame.display.flip()

# 停止背景音乐
pygame.mixer.music.stop()

# 退出游戏
pygame.quit()

In this sample code, we create a playerslist to store score objects for multiple players. In the main loop of the game, we check the mouse click event and increase the player's score based on the click position and collision detection of the beauty object. Each player has their own scoring object, which is displayed on the screen.

Note: You need to prepare the corresponding beauty image resources ("beauty1.png", "beauty2.png", "beauty3.png", "beauty4.png") and put them in the same directory as the sample code. You can adjust the number of players and related settings as needed.

10. Ranking and achievement system sample code

Insert image description hereHere is sample code for adding a leaderboard and achievement system:

import pygame
import random
import json

# 初始化游戏
pygame.init()

# 设置窗口大小和标题
screen_width = 800
screen_height = 600
window = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("给美女打分 - 多人游戏模式")

# 加载背景音乐
pygame.mixer.music.load("background_music.mp3")
pygame.mixer.music.set_volume(0.5)  # 设置音量
pygame.mixer.music.play(-1)  # 循环播放背景音乐

# 加载音效
score_sound = pygame.mixer.Sound("score_sound.wav")

# 定义美女类
class Beauty(pygame.sprite.Sprite):
    def __init__(self, x, y, image, score, special_attribute, speed):
        super().__init__()
        self.image = pygame.image.load(image)  # 美女的图片资源
        self.rect = self.image.get_rect()
        self.rect.center = (x, y)
        self.score = score  # 美女的得分
        self.special_attribute = special_attribute  # 美女的特殊属性
        self.speed = speed  # 美女的移动速度

    def update(self):
        self.rect.x += self.speed

# 定义分数类
class Score(pygame.sprite.Sprite):
    def __init__(self, x, y, player_name):
        super().__init__()
        self.score = 0
        self.player_name = player_name  # 玩家名称
        self.font = pygame.font.Font(None, 36)
        self.text = self.font.render(self.player_name + ": " + str(self.score), True, (255, 255, 255))
        self.rect = self.text.get_rect()
        self.rect.center = (x, y)

    def update(self):
        self.text = self.font.render(self.player_name + ": " + str(self.score), True, (255, 255, 255))

# 定义关卡类
class Level:
    def __init__(self, target_score, beauties):
        self.target_score = target_score  # 目标得分
        self.beauties = beauties  # 美女列表

    def is_completed(self, score):
        return score >= self.target_score

# 创建精灵组
all_sprites = pygame.sprite.Group()

# 创建关卡列表
levels = [
    Level(50, [
        Beauty(screen_width // 2 - 100, screen_height // 2, "beauty1.png", 10, "可爱", 2),
        Beauty(screen_width // 2 + 100, screen_height // 2, "beauty2.png", 20, "性感", 3)
    ]),
    Level(100, [
        Beauty(screen_width // 2 - 100, screen_height // 2, "beauty3.png", 15, "甜美", 3),
        Beauty(screen_width // 2 + 100, screen_height // 2, "beauty4.png", 25, "迷人", 4)
    ])
]

num_players = 2  # 玩家数量
players = []  # 玩家列表

# 创建玩家对象和分数对象
for i in range(num_players):
    player_name = "Player " + str(i+1)
    player_score = Score(screen_width // 2, 50 + i*50, player_name)
    players.append(player_score)
    all_sprites.add(player_score)

current_level = 0
level = levels[current_level]

# 将当前关卡的美女添加到精灵组中
for beauty in level.beauties:
    all_sprites.add(beauty)

# 加载排行榜数据
leaderboard_data = {
    
    }
try:
    with open("leaderboard.json", "r") as f:
        leaderboard_data = json.load(f)
except FileNotFoundError:
    pass

# 游戏主循环
running = True
clock = pygame.time.Clock()
spawn_timer = 0
difficulty_level = 1
while running:
    clock.tick(60)

    # 事件处理
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN:
            mouse_pos = pygame.mouse.get_pos()
            clicked_sprites = [s for s in all_sprites if s.rect.collidepoint(mouse_pos)]
            for sprite in clicked_sprites:
                if isinstance(sprite, Beauty):
                    for player in players:
                        if player.rect.collidepoint(mouse_pos):
                            player.score += sprite.score
                            score_sound.play()  # 播放得分音效

    # 更新精灵组中的所有精灵
    all_sprites.update()

    # 控制美女的出现频率和移动速度
    spawn_timer += 1
    if spawn_timer >= 60 / difficulty_level:
        beauty = random.choice(level.beauties)
        beauty = Beauty(screen_width + 50, random.randint(50, screen_height - 50), beauty.image, beauty.score, beauty.special_attribute, random.randint(2, 4))
        all_sprites.add(beauty)
        spawn_timer = 0
    
    # 检查当前关卡是否完成
    if level.is_completed(players[0].score):
        current_level += 1
        if current_level < len(levels):
            level = levels[current_level]
            for player in players:
                player.score = 0
            for beauty in level.beauties:
                all_sprites.add(beauty)
        else:
            running = False

    # 绘制背景
    window.fill((0, 0, 0))

    # 绘制所有精灵
    all_sprites.draw(window)

    # 刷新屏幕
    pygame.display.flip()

# 停止背景音乐
pygame.mixer.music.stop()

# 更新排行榜数据
for player in players:
    if player.player_name not in leaderboard_data:
        leaderboard_data[player.player_name] = player.score
    else:
        leaderboard_data[player.player_name] = max(leaderboard_data[player.player_name], player.score)

# 保存排行榜数据
with open("leaderboard.json", "w") as f:
    json.dump(leaderboard_data, f)

# 输出排行榜
sorted_leaderboard = sorted(leaderboard_data.items(), key=lambda x: x[1], reverse=True)
print("排行榜:")
for i, (player_name, score) in enumerate(sorted_leaderboard):
    print(f"{
      
      i+1}. {
      
      player_name}: {
      
      score}")

# 退出游戏
pygame.quit()

In this sample code, we use jsonmodules to load and save leaderboard data. After the main loop of the game ends, we update the leaderboard data based on the player's score and save the leaderboard data to a leaderboard.jsonfile. Finally, we sort the ranking data and output the contents of the ranking.

Note: You need to prepare the corresponding beauty image resources ("beauty1.png", "beauty2.png", "beauty3.png", "beauty4.png") and put them in the same directory as the sample code. Make sure the file paths for the music files and sound effects files are correct.

11. Add animation effect sample code

Insert image description hereHere's sample code to animate the appearance, disappearance, and scoring of beauties:

import pygame
import random

# 初始化游戏
pygame.init()

# 设置窗口大小和标题
screen_width = 800
screen_height = 600
window = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("给美女打分 - 多人游戏模式")

# 加载背景音乐
pygame.mixer.music.load("background_music.mp3")
pygame.mixer.music.set_volume(0.5)  # 设置音量
pygame.mixer.music.play(-1)  # 循环播放背景音乐

# 加载音效
score_sound = pygame.mixer.Sound("score_sound.wav")

# 定义美女类
class Beauty(pygame.sprite.Sprite):
    def __init__(self, x, y, image, score, special_attribute, speed):
        super().__init__()
        self.image = pygame.image.load(image)  # 美女的图片资源
        self.rect = self.image.get_rect()
        self.rect.center = (x, y)
        self.score = score  # 美女的得分
        self.special_attribute = special_attribute  # 美女的特殊属性
        self.speed = speed  # 美女的移动速度
        self.animation_timer = 0
        self.animation_duration = 30

    def update(self):
        self.rect.x += self.speed

        # 美女出现动画效果
        if self.animation_timer < self.animation_duration:
            self.rect.y -= 2
            self.animation_timer += 1

# 定义分数类
class Score(pygame.sprite.Sprite):
    def __init__(self, x, y, player_name):
        super().__init__()
        self.score = 0
        self.player_name = player_name  # 玩家名称
        self.font = pygame.font.Font(None, 36)
        self.text = self.font.render(self.player_name + ": " + str(self.score), True, (255, 255, 255))
        self.rect = self.text.get_rect()
        self.rect.center = (x, y)
        self.animation_timer = 0
        self.animation_duration = 30

    def update(self):
        # 分数增加动画效果
        if self.animation_timer < self.animation_duration:
            self.rect.y -= 2
            self.animation_timer += 1

# 定义关卡类
class Level:
    def __init__(self, target_score, beauties):
        self.target_score = target_score  # 目标得分
        self.beauties = beauties  # 美女列表

    def is_completed(self, score):
        return score >= self.target_score

# 创建精灵组
all_sprites = pygame.sprite.Group()

# 创建关卡列表
levels = [
    Level(50, [
        Beauty(screen_width // 2 - 100, screen_height // 2, "beauty1.png", 10, "可爱", 2),
        Beauty(screen_width // 2 + 100, screen_height // 2, "beauty2.png", 20, "性感", 3)
    ]),
    Level(100, [
        Beauty(screen_width // 2 - 100, screen_height // 2, "beauty3.png", 15, "甜美", 3),
        Beauty(screen_width // 2 + 100, screen_height // 2, "beauty4.png", 25, "迷人", 4)
    ])
]

num_players = 2  # 玩家数量
players = []  # 玩家列表

# 创建玩家对象和分数对象
for i in range(num_players):
    player_name = "Player " + str(i+1)
    player_score = Score(screen_width // 2, 50 + i*50, player_name)
    players.append(player_score)
    all_sprites.add(player_score)

current_level = 0
level = levels[current_level]

# 将当前关卡的美女添加到精灵组中
for beauty in level.beauties:
    all_sprites.add(beauty)

# 加载排行榜数据
leaderboard_data = {
    
    }
try:
    with open("leaderboard.json", "r") as f:
        leaderboard_data = json.load(f)
except FileNotFoundError:
    pass

# 游戏主循环
running = True
clock = pygame.time.Clock()
spawn_timer = 0
difficulty_level = 1
while running:
    clock.tick(60)

    # 事件处理
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN:
            mouse_pos = pygame.mouse.get_pos()
            clicked_sprites = [s for s in all_sprites if s.rect.collidepoint(mouse_pos)]
            for sprite in clicked_sprites:
                if isinstance(sprite, Beauty):
                    for player in players:
                        if player.rect.collidepoint(mouse_pos):
                            player.score += sprite.score
                            score_sound.play()  # 播放得分音效

    # 更新精灵组中的所有精灵
    all_sprites.update()

    # 控制美女的出现频率和移动速度
    spawn_timer += 1
    if spawn_timer >= 60 / difficulty_level:
        beauty = random.choice(level.beauties)
        beauty = Beauty(screen_width + 50, random.randint(50, screen_height - 50), beauty.image, beauty.score, beauty.special_attribute, random.randint(2, 4))
        all_sprites.add(beauty)
        spawn_timer = 0
    
    # 检查当前关卡是否完成
    if level.is_completed(players[0].score):
        current_level += 1
        if current_level < len(levels):
            level = levels[current_level]
            for player in players:
                player.score = 0
            for beauty in level.beauties:
                all_sprites.add(beauty)
        else:
            running = False

    # 绘制背景
    window.fill((0, 0, 0))

    # 绘制所有精灵
    all_sprites.draw(window)

    # 刷新屏幕
    pygame.display.flip()

# 停止背景音乐
pygame.mixer.music.stop()

# 更新排行榜数据
for player in players:
    if player.player_name not in leaderboard_data:
        leaderboard_data[player.player_name] = player.score
    else:
        leaderboard_data[player.player_name] = max(leaderboard_data[player.player_name], player.score)

# 保存排行榜数据
with open("leaderboard.json", "w") as f:
    json.dump(leaderboard_data, f)

# 输出排行榜
sorted_leaderboard = sorted(leaderboard_data.items(), key=lambda x: x[1], reverse=True)
print("排行榜:")
for i, (player_name, score) in enumerate(sorted_leaderboard):
    print(f"{
      
      i+1}. {
      
      player_name}: {
      
      score}")

# 退出游戏
pygame.quit()

In this sample code, we animate the beauty's appearance and score points. In Beautythe class and Scoreclass, we added animation_timerthe and animation_durationproperties to control the duration and current time of the animation. In updatethe method, we modify the positions of the beauty and score objects according to the progress of the animation to achieve the animation effect.
Insert image description here

Note: You need to prepare the corresponding beauty image resources ("beauty1.png", "beauty2.png", "beauty3.png", "beauty4.png") and put them in the same directory as the sample code. Make sure the file paths for the music files and sound effects files are correct.

Guess you like

Origin blog.csdn.net/jackchuanqi/article/details/136109070