首页 > 编程语言 >边玩边学,10个Python小游戏(含源码)

边玩边学,10个Python小游戏(含源码)

时间:2024-07-01 13:56:40浏览次数:22  
标签:边玩 10 group img win 源码 pygame False page

经常听到有朋友说,学习编程是一件非常枯燥无味的事情。其实,大家有没有认真想过,可能是我们的学习方法不对?

比方说,你有没有想过,可以通过打游戏来学编程?

今天我想跟大家分享10个Python小游戏,教你如何通过边打游戏边学编程!

接下来就一起来看看吧~

1、飞机大战

在这里插入图片描述

源码分享:

import random
import pygame
from objects import Background, Player, Enemy, Bullet, Explosion, Fuel, \
                    Powerup, Button, Message, BlinkingText

pygame.init()
SCREEN = WIDTH, HEIGHT = 288, 512

info = pygame.display.Info()
width = info.current_w
height = info.current_h

if width >= height:
    win = pygame.display.set_mode(SCREEN, pygame.NOFRAME)
else:
    win = pygame.display.set_mode(SCREEN, pygame.NOFRAME | pygame.SCALED | pygame.FULLSCREEN)

clock = pygame.time.Clock()
FPS = 60

# COLORS **********************************************************************

WHITE = (255, 255, 255)
BLUE = (30, 144,255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLACK = (0, 0, 20)

# IMAGES **********************************************************************

plane_img = pygame.image.load('Assets/plane.png')
logo_img = pygame.image.load('Assets/logo.png')
fighter_img = pygame.image.load('Assets/fighter.png')
clouds_img = pygame.image.load('Assets/clouds.png')
clouds_img = pygame.transform.scale(clouds_img, (WIDTH, 350))

home_img = pygame.image.load('Assets/Buttons/homeBtn.png')
replay_img = pygame.image.load('Assets/Buttons/replay.png')
sound_off_img = pygame.image.load("Assets/Buttons/soundOffBtn.png")
sound_on_img = pygame.image.load("Assets/Buttons/soundOnBtn.png")


# BUTTONS *********************************************************************

home_btn = Button(home_img, (24, 24), WIDTH // 4 - 18, HEIGHT//2 + 120)
replay_btn = Button(replay_img, (36,36), WIDTH // 2  - 18, HEIGHT//2 + 115)
sound_btn = Button(sound_on_img, (24, 24), WIDTH - WIDTH // 4 - 18, HEIGHT//2 + 120)


# FONTS ***********************************************************************

game_over_font = 'Fonts/ghostclan.ttf'
tap_to_play_font = 'Fonts/BubblegumSans-Regular.ttf'
score_font = 'Fonts/DalelandsUncialBold-82zA.ttf'
final_score_font = 'Fonts/DroneflyRegular-K78LA.ttf'

game_over_msg = Message(WIDTH//2, 230, 30, 'Game Over', game_over_font, WHITE, win)
score_msg = Message(WIDTH-50, 28, 30, '0', final_score_font, RED, win)
final_score_msg = Message(WIDTH//2, 280, 30, '0', final_score_font, RED, win)
tap_to_play_msg = tap_to_play = BlinkingText(WIDTH//2, HEIGHT-60, 25, "Tap To Play",
                 tap_to_play_font, WHITE, win)


# SOUNDS **********************************************************************

player_bullet_fx = pygame.mixer.Sound('Sounds/gunshot.wav')
click_fx = pygame.mixer.Sound('Sounds/click.mp3')
collision_fx = pygame.mixer.Sound('Sounds/mini_exp.mp3')
blast_fx = pygame.mixer.Sound('Sounds/blast.wav')
fuel_fx = pygame.mixer.Sound('Sounds/fuel.wav')

pygame.mixer.music.load('Sounds/Defrini - Spookie.mp3')
pygame.mixer.music.play(loops=-1)
pygame.mixer.music.set_volume(0.1)


# GROUPS & OBJECTS ************************************************************

bg = Background(win)
p = Player(144, HEIGHT - 100)

enemy_group = pygame.sprite.Group()
player_bullet_group = pygame.sprite.Group()
enemy_bullet_group = pygame.sprite.Group()
explosion_group = pygame.sprite.Group()
fuel_group = pygame.sprite.Group()
powerup_group = pygame.sprite.Group()

# FUNCTIONS *******************************************************************

def shoot_bullet():
    x, y = p.rect.center[0], p.rect.y

    if p.powerup > 0:
        for dx in range(-3, 4):
            b = Bullet(x, y, 4, dx)
            player_bullet_group.add(b)
        p.powerup -= 1
    else:
        b = Bullet(x-30, y, 6)
        player_bullet_group.add(b)
        b = Bullet(x+30, y, 6)
        player_bullet_group.add(b)
    player_bullet_fx.play()

def reset():
    enemy_group.empty()
    player_bullet_group.empty()
    enemy_bullet_group.empty()
    explosion_group.empty()
    fuel_group.empty()
    powerup_group.empty()

    p.reset(p.x, p.y)

# VARIABLES *******************************************************************

level = 1
plane_destroy_count = 0
plane_frequency = 5000
start_time = pygame.time.get_ticks()

moving_left = False
moving_right = False

home_page = True
game_page = False
score_page = False

score = 0
sound_on = True

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE or event.key == pygame.K_q:
                running = False

        if event.type == pygame.KEYDOWN and game_page:
            if event.key == pygame.K_LEFT:
                moving_left = True
            if event.key == pygame.K_RIGHT:
                moving_right = True
            if event.key == pygame.K_SPACE:
                shoot_bullet()

        if event.type == pygame.MOUSEBUTTONDOWN:
            if home_page:
                home_page = False
                game_page = True
                click_fx.play()
            elif game_page:
                x, y = event.pos
                if p.rect.collidepoint((x,y)):
                    shoot_bullet()
                elif x <= WIDTH // 2:
                    moving_left = True
                elif x > WIDTH // 2:
                    moving_right = True

        if event.type == pygame.KEYUP:
            moving_left = False
            moving_right = False

        if event.type == pygame.MOUSEBUTTONUP:
            moving_left = False
            moving_right = False

    if home_page:
        win.fill(BLACK)
        win.blit(logo_img, (30, 80))
        win.blit(fighter_img, (WIDTH//2 - 50, HEIGHT//2))
        pygame.draw.circle(win, WHITE, (WIDTH//2, HEIGHT//2 + 50), 50, 4)
        tap_to_play_msg.update()

    if score_page:
        win.fill(BLACK)
        win.blit(logo_img, (30, 50))
        game_over_msg.update()
        final_score_msg.update(score)

        if home_btn.draw(win):
            home_page = True
            game_page = False
            score_page = False
            reset()
            click_fx.play()

            plane_destroy_count = 0
            level = 1
            score = 0

        if replay_btn.draw(win):
            score_page = False
            game_page = True
            reset()
            click_fx.play()

            plane_destroy_count = 0
            score = 0

        if sound_btn.draw(win):
            sound_on = not sound_on

            if sound_on:
                sound_btn.update_image(sound_on_img)
                pygame.mixer.music.play(loops=-1)
            else:
                sound_btn.update_image(sound_off_img)
                pygame.mixer.music.stop()

    if game_page:

        current_time = pygame.time.get_ticks()
        delta_time = current_time - start_time
        if delta_time >= plane_frequency:
            if level == 1:
                type = 1
            elif level == 2:
                type = 2
            elif level == 3:
                type = 3
            elif level == 4:
                type = random.randint(4, 5)
            elif level == 5:
                type = random.randint(1, 5)

            x = random.randint(10, WIDTH - 100)
            e = Enemy(x, -150, type)
            enemy_group.add(e)
            start_time = current_time

        if plane_destroy_count:
            if plane_destroy_count % 5 == 0 and level < 5:
                level += 1
                plane_destroy_count = 0

        p.fuel -= 0.05
        bg.update(1)
        win.blit(clouds_img, (0, 70))

        p.update(moving_left, moving_right, explosion_group)
        p.draw(win)

        player_bullet_group.update()
        player_bullet_group.draw(win)
        enemy_bullet_group.update()
        enemy_bullet_group.draw(win)
        explosion_group.update()
        explosion_group.draw(win)
        fuel_group.update()
        fuel_group.draw(win)
        powerup_group.update()
        powerup_group.draw(win)

        enemy_group.update(enemy_bullet_group, explosion_group)
        enemy_group.draw(win)

        if p.alive:
            player_hit = pygame.sprite.spritecollide(p, enemy_bullet_group, False)
            for bullet in player_hit:
                p.health -= bullet.damage

                x, y = bullet.rect.center
                explosion = Explosion(x, y, 1)
                explosion_group.add(explosion)

                bullet.kill()
                collision_fx.play()

            for bullet in player_bullet_group:
                planes_hit = pygame.sprite.spritecollide(bullet, enemy_group, False)
                for plane in planes_hit:
                    plane.health -= bullet.damage
                    if plane.health <= 0:
                        x, y = plane.rect.center
                        rand = random.random()
                        if rand >= 0.9:
                            power = Powerup(x, y)
                            powerup_group.add(power)
                        elif rand >= 0.3:
                            fuel = Fuel(x, y)
                            fuel_group.add(fuel)

                        plane_destroy_count += 1
                        blast_fx.play()

                    x, y = bullet.rect.center
                    explosion = Explosion(x, y, 1)
                    explosion_group.add(explosion)

                    bullet.kill()
                    collision_fx.play()

            player_collide = pygame.sprite.spritecollide(p, enemy_group, True)
            if player_collide:
                x, y = p.rect.center
                explosion = Explosion(x, y, 2)
                explosion_group.add(explosion)

                x, y = player_collide[0].rect.center
                explosion = Explosion(x, y, 2)
                explosion_group.add(explosion)

                p.health = 0
                p.alive = False

            if pygame.sprite.spritecollide(p, fuel_group, True):
                p.fuel += 25
                if p.fuel >= 100:
                    p.fuel = 100
                fuel_fx.play()

            if pygame.sprite.spritecollide(p, powerup_group, True):
                p.powerup += 2
                fuel_fx.play()

        if not p.alive or p.fuel <= -10:
            if len(explosion_group) == 0:
                game_page = False
                score_page = True
                reset()

        score += 1
        score_msg.update(score)

        fuel_color = RED if p.fuel <= 40 else GREEN
        pygame.draw.rect(win, fuel_color, (30, 20, p.fuel, 10), border_radius=4)
        pygame.draw.rect(win, WHITE, (30, 20, 100, 10), 2, border_radius=4)
        pygame.draw.rect(win, BLUE, (30, 32, p.health, 10), border_radius=4)
        pygame.draw.rect(win, WHITE, (30, 32, 100, 10), 2, border_radius=4)
        win.blit(plane_img, (10, 15))

    pygame.draw.rect(win, WHITE, (0,0, WIDTH, HEIGHT), 5, border_radius=4)
    clock.tick(FPS)
    pygame.display.update()

pygame.quit()

2、愤怒的墙

在这里插入图片描述

源码分享:

import pygame
import random

from objects import Player, Bar, Ball, Block, ScoreCard, Message, Particle, generate_particles

pygame.init()
SCREEN = WIDTH, HEIGHT = 288, 512

info = pygame.display.Info()
width = info.current_w
height = info.current_h

if width >= height:
    win = pygame.display.set_mode(SCREEN, pygame.NOFRAME)
else:
    win = pygame.display.set_mode(SCREEN, pygame.NOFRAME | pygame.SCALED | pygame.FULLSCREEN)

clock = pygame.time.Clock()
FPS = 45

# COLORS

RED = (255, 0, 0)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GRAY = (54, 69, 79)
c_list = [RED, BLACK, WHITE]

# Fonts

pygame.font.init()
score_font = pygame.font.Font('Fonts/BubblegumSans-Regular.ttf', 50)

# Sounds

coin_fx = pygame.mixer.Sound('Sounds/coin.mp3')
death_fx = pygame.mixer.Sound('Sounds/death.mp3')
move_fx = pygame.mixer.Sound('Sounds/move.mp3')

# backgrounds

bg_list = []
for i in range(1,5):
    if i == 2:
        ext = "jpeg"
    else:
        ext = "jpg"
    img = pygame.image.load(f"Assets/Backgrounds/bg{i}.{ext}")
    img = pygame.transform.scale(img, (WIDTH, HEIGHT))
    bg_list.append(img)

home_bg = pygame.image.load(f"Assets/Backgrounds/home.jpeg")

bg = home_bg

# objects
bar_group = pygame.sprite.Group()
ball_group = pygame.sprite.Group()
block_group = pygame.sprite.Group()
destruct_group = pygame.sprite.Group()
win_particle_group = pygame.sprite.Group()
bar_gap = 120

particles = []

p = Player(win)
score_card = ScoreCard(140, 40, win)

# Functions

def destroy_bird():
    x, y = p.rect.center
    for i in range (50):
        c = random.choice(c_list)
        particle = Particle(x,y, 1,c, win)
        destruct_group.add(particle)

def win_particles():
    for x,y in [(40, 120), (WIDTH - 20, 240), (15, HEIGHT - 30)]:
        for i in range(10):
            particle = Particle (x,y, 2, WHITE, win)
            win_particle_group.add(particle)

# Messages
title_font = "Fonts/Robus-BWqOd.otf"
dodgy = Message(134, 90, 100, "Angry",title_font, WHITE, win)
walls = Message(164, 145, 80, "Walls",title_font, WHITE, win)

tap_to_play_font = "Fonts/DebugFreeTrial-MVdYB.otf"
tap_to_play = Message(144, 400, 32, "TAP TO PLAY",tap_to_play_font, WHITE, win)
tap_to_replay = Message(144, 400, 30, "Tap to Replay",tap_to_play_font, WHITE, win)

# Variables

bar_width_list = [i for i in range (40,150,10)]
bar_frequency = 1200
bar_speed = 4
touched = False
pos = None
home_page = True
score_page = False
bird_dead = False
score = 0
high_score = 0
move_left = False
move_right = True
prev_x = 0
p_count = 0

running = True
while running:
    win.blit(bg, (0,0))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                running = False

        if event.type == pygame.MOUSEBUTTONDOWN and (home_page or score_page):
            home_page = False
            score_page = False
            win_particle_group.empty()

            bg = random.choice(bg_list)

            particles = []
            last_bar = pygame.time.get_ticks() - bar_frequency
            next_bar = 0
            bar_speed = 4
            bar_frequency = 1200
            bird_dead = False
            score = 0
            p_count = 0
            score_list = []

            for _ in range(15):
                x = random.randint(30, WIDTH - 30)
                y = random.randint(60, HEIGHT - 60)
                max = random.randint(8,16)
                b = Block(x,y,max, win)
                block_group.add(b)

        if event.type == pygame.MOUSEBUTTONDOWN and not home_page:
            if p.rect.collidepoint(event.pos):
                touched = True
                x, y = event.pos
                offset_x = p.rect.x - x

        if event.type == pygame.MOUSEBUTTONUP and not home_page:
            touched = False

        if event.type == pygame.MOUSEMOTION and not home_page:
            if touched:
                x, y = event.pos
                if move_right and prev_x > x:
                    move_right = False
                    move_left = True
                    move_fx.play()
                if move_left and  prev_x < x:
                    move_right = True
                    move_left = False
                    move_fx.play()

                prev_x = x
                p.rect.x =  x + offset_x

    if home_page:
        bg = home_bg
        particles = generate_particles(p, particles, WHITE, win)
        dodgy.update()
        walls.update()
        tap_to_play.update()
        p.update()

    elif score_page:
        bg = home_bg
        particles = generate_particles(p, particles, WHITE, win)
        tap_to_replay.update()
        p.update()
        score_msg.update()
        score_point.update()
        if p_count % 5 == 0:
            win_particles()
        p_count += 1
        win_particle_group.update()

    else:

        next_bar = pygame.time.get_ticks()
        if next_bar - last_bar >= bar_frequency and not bird_dead:
            bwidth = random.choice(bar_width_list)

            b1prime = Bar(0,0,bwidth+3,GRAY, win)
            b1 = Bar(0,-3,bwidth,WHITE,win)

            b2prime = Bar(bwidth+bar_gap+3, 0, WIDTH - bwidth - bar_gap, GRAY, win)
            b2 = Bar(bwidth+bar_gap, -3, WIDTH - bwidth - bar_gap, WHITE, win)

            bar_group.add(b1prime)
            bar_group.add(b1)
            bar_group.add(b2prime)
            bar_group.add(b2)

            color = random.choice(["red", "white"])
            pos = random.choice([0,1])
            if pos == 0:
                x = bwidth + 12
            elif pos == 1:
                x = bwidth + bar_gap - 12
            ball = Ball(x, 10, 1, color, win)

            ball_group.add(ball)
            last_bar = next_bar

        for ball in ball_group:
            if ball.rect.colliderect(p):
                if ball.color == "white":
                    ball.kill()
                    coin_fx.play()
                    score += 1
                    if score > high_score:
                        high_score += 1
                    score_card.animate = True
                elif ball.color == "red":
                    if not bird_dead:
                        death_fx.play()
                        destroy_bird()

                    bird_dead = True
                    bar_speed = 0

        if pygame.sprite.spritecollide(p, bar_group, False):
            if not bird_dead:
                death_fx.play()
                destroy_bird()

            bird_dead = True
            bar_speed = 0

        block_group.update()
        bar_group.update(bar_speed)
        ball_group.update(bar_speed)

        if bird_dead:
                destruct_group.update()

        score_card.update(score)

        if not bird_dead:
            particles = generate_particles(p, particles, WHITE, win)
            p.update()

        if score and score % 10 == 0:
            rem = score // 10
            if rem not in score_list:
                score_list.append(rem)
                bar_speed += 1
                bar_frequency -= 200

        if bird_dead and len(destruct_group) == 0:
            score_page = True
            font =  "Fonts/BubblegumSans-Regular.ttf"
            if score < high_score:
                score_msg = Message(144, 60, 55, "Score",font, WHITE, win)
            else:
                score_msg = Message(144, 60, 55, "New High",font, WHITE, win)

            score_point = Message(144, 110, 45, f"{score}", font, WHITE, win)

        if score_page:
            block_group.empty()
            bar_group.empty()
            ball_group.empty()

            p.reset()

    clock.tick(FPS)
    pygame.display.update()

pygame.quit()

3、圆弧冲刺

在这里插入图片描述

源码分享:

import random
import pygame

from objects import Player, Balls, Dot, Shadow, Particle, Message, BlinkingText, Button

pygame.init()
SCREEN = WIDTH, HEIGHT = 288, 512
CENTER = WIDTH //2, HEIGHT // 2

info = pygame.display.Info()
width = info.current_w
height = info.current_h

if width >= height:
    win = pygame.display.set_mode(SCREEN, pygame.NOFRAME)
else:
    win = pygame.display.set_mode(SCREEN, pygame.NOFRAME | pygame.SCALED | pygame.FULLSCREEN)

clock = pygame.time.Clock()
FPS = 60

# COLORS **********************************************************************

RED = (255,0,0)
GREEN = (0,177,64)
BLUE = (30, 144,255)
ORANGE = (252,76,2)
YELLOW = (254,221,0)
PURPLE = (155,38,182)
AQUA = (0,103,127)
WHITE = (255,255,255)
BLACK = (0,0,0)

color_list = [RED, GREEN, BLUE, ORANGE, YELLOW, PURPLE]
color_index = 0
color = color_list[color_index]

# FONTS ***********************************************************************

title_font = "Fonts/Aladin-Regular.ttf"
tap_to_play_font = "Fonts/BubblegumSans-Regular.ttf"
score_font = "Fonts/DalelandsUncialBold-82zA.ttf"
game_over_font = "Fonts/ghostclan.ttf"

# MESSAGES ********************************************************************

arc = Message(WIDTH-90, 200, 80, "Arc", title_font, WHITE, win)
dash = Message(80, 300, 60, "Dash", title_font, WHITE, win)
tap_to_play = BlinkingText(WIDTH//2, HEIGHT-60, 20, "Tap To Play", tap_to_play_font, WHITE, win)
game_msg = Message(80, 150, 40, "GAME", game_over_font, BLACK, win)
over_msg = Message(210, 150, 40, "OVER!", game_over_font, WHITE, win)
score_text = Message(90, 230, 20, "SCORE", None, BLACK, win)
best_text = Message(200, 230, 20, "BEST", None, BLACK, win)

score_msg = Message(WIDTH-60, 50, 50, "0", score_font, WHITE, win)
final_score_msg = Message(90, 280, 40, "0", tap_to_play_font, BLACK, win)
high_score_msg = Message(200, 280, 40, "0", tap_to_play_font, BLACK, win)

# SOUNDS **********************************************************************

score_fx = pygame.mixer.Sound('Sounds/point.mp3')
death_fx = pygame.mixer.Sound('Sounds/dead.mp3')
score_page_fx = pygame.mixer.Sound('Sounds/score_page.mp3')

pygame.mixer.music.load('Sounds/hk.mp3')
pygame.mixer.music.play(loops=-1)
pygame.mixer.music.set_volume(0.5)

# Button images

home_img = pygame.image.load('Assets/homeBtn.png')
replay_img = pygame.image.load('Assets/replay.png')
sound_off_img = pygame.image.load("Assets/soundOffBtn.png")
sound_on_img = pygame.image.load("Assets/soundOnBtn.png")

# Buttons

home_btn = Button(home_img, (24, 24), WIDTH // 4 - 18, 390)
replay_btn = Button(replay_img, (36,36), WIDTH // 2  - 18, 382)
sound_btn = Button(sound_on_img, (24, 24), WIDTH - WIDTH // 4 - 18, 390)

# GAME VARIABLES **************************************************************

MAX_RAD = 120
rad_delta = 50

# OBJECTS *********************************************************************

ball_group = pygame.sprite.Group()
dot_group = pygame.sprite.Group()
shadow_group = pygame.sprite.Group()
particle_group = pygame.sprite.Group()
p = Player(win)

ball_positions = [(CENTER[0]-105, CENTER[1]), (CENTER[0]+105, CENTER[1]),
                    (CENTER[0]-45, CENTER[1]), (CENTER[0]+45, CENTER[1]),
                    (CENTER[0], CENTER[1]-75), (CENTER[0], CENTER[1]+75)]
for index, pos in enumerate(ball_positions):
    if index in (0,1):
        type_ = 1
        inverter = 5
    if index in (2,3):
        type_ = 1
        inverter = 3
    if index in (4,5):
        type_ = 2
        inverter = 1
    ball = Balls(pos, type_, inverter, win)
    ball_group.add(ball)

dot_list = [(CENTER[0], CENTER[1]-MAX_RAD+3), (CENTER[0]+MAX_RAD-3, CENTER[1]),
            (CENTER[0], CENTER[1]+MAX_RAD-3), (CENTER[0]-MAX_RAD+3, CENTER[1])]
dot_index = random.choice([1,2,3,4])
dot_pos = dot_list[dot_index-1]
dot = Dot(*dot_pos, win)
dot_group.add(dot)

shadow = Shadow(dot_index, win)
shadow_group.add(shadow)


# VARIABLES *******************************************************************

clicked = False
num_clicks = 0
player_alive = True
sound_on = True

score = 0
highscore = 0

home_page = True
game_page = False
score_page = False

running = True
while running:
    win.fill(color)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE or \
                event.key == pygame.K_q:
                running = False

        if event.type == pygame.MOUSEBUTTONDOWN and home_page:
            home_page = False
            game_page = True
            score_page = False

            rad_delta = 50
            clicked = True
            score = 0
            num_clicks = 0
            player_alive = True

        if event.type == pygame.MOUSEBUTTONDOWN and game_page:
            if not clicked:
                clicked = True
                for ball in ball_group:
                    if num_clicks % ball.inverter == 0:
                        ball.dtheta *= -1

                p.set_move(dot_index)

                num_clicks += 1
                if num_clicks % 5 == 0:
                    color_index += 1
                    if color_index > len(color_list) - 1:
                        color_index = 0

                    color = color_list[color_index]

        if event.type == pygame.MOUSEBUTTONDOWN and game_page:
            clicked = False

    if home_page:
        for radius in [30, 60, 90, 120]:
            pygame.draw.circle(win, (0,0,0), CENTER, radius, 8)
            pygame.draw.circle(win, (255,255,255), CENTER, radius, 5)

        pygame.draw.rect(win, color, [CENTER[0]-10, CENTER[1]-MAX_RAD, MAX_RAD+50, MAX_RAD])
        pygame.draw.rect(win, color, [CENTER[0]-MAX_RAD, CENTER[1]-10, MAX_RAD, MAX_RAD+50])

        arc.update()
        dash.update()
        tap_to_play.update()

    if score_page:
        game_msg.update()
        over_msg.update()
        score_text.update(shadow=False)
        best_text.update(shadow=False)

        final_score_msg.update(score, shadow=False)
        high_score_msg.update(highscore, shadow=False)

        if home_btn.draw(win):
            home_page = True
            score_page = False
            game_page = False
            score = 0
            score_msg = Message(WIDTH-60, 50, 50, "0", score_font, WHITE, win)

        if replay_btn.draw(win):
            home_page = False
            score_page = False
            game_page = True

            player_alive = True
            score = 0
            score_msg = Message(WIDTH-60, 50, 50, "0", score_font, WHITE, win)
            p = Player(win)

        if sound_btn.draw(win):
            sound_on = not sound_on

            if sound_on:
                sound_btn.update_image(sound_on_img)
                pygame.mixer.music.play(loops=-1)
            else:
                sound_btn.update_image(sound_off_img)
                pygame.mixer.music.stop()

    if game_page:

        for radius in [30 + rad_delta, 60 + rad_delta, 90 + rad_delta, 120 + rad_delta]:
            if rad_delta > 0:
                radius -= 1
                rad_delta -= 1
            pygame.draw.circle(win, (0,0,0), CENTER, radius, 5)


        pygame.draw.rect(win, color, [CENTER[0]-10, CENTER[1]-MAX_RAD, 20, MAX_RAD*2])
        pygame.draw.rect(win, color, [CENTER[0]-MAX_RAD, CENTER[1]-10, MAX_RAD*2, 20])

        if rad_delta <= 0:
            p.update(player_alive, color, shadow_group)
            shadow_group.update()
            ball_group.update()
            dot_group.update()
            particle_group.update()
            score_msg.update(score)

            for dot in dot_group:
                if dot.rect.colliderect(p):
                    dot.kill()
                    score_fx.play()

                    score += 1
                    if highscore <= score:
                        highscore = score

            if pygame.sprite.spritecollide(p, ball_group, False) and player_alive:
                death_fx.play()
                x, y = p.rect.center
                for i in range(20):
                    particle = Particle(x, y, WHITE, win)
                    particle_group.add(particle)
                player_alive = False
                p.reset()

            if p.can_move and len(dot_group) == 0 and player_alive:
                dot_index = random.randint(1,4)
                dot_pos = dot_list[dot_index-1]
                dot = Dot(*dot_pos, win)
                dot_group.add(dot)

                shadow_group.empty()
                shadow = Shadow(dot_index, win)
                shadow_group.add(shadow)

            if not player_alive and len(particle_group) == 0:
                game_page = False
                score_page = True

                dot_group.empty()
                shadow_group.empty()
                for ball in ball_group:
                    ball.reset()
                score_page_fx.play()


    pygame.draw.rect(win, WHITE, (0, 0, WIDTH, HEIGHT), 5, border_radius=10)
    clock.tick(FPS)
    pygame.display.update()

pygame.quit()

4、行星游戏

在这里插入图片描述

源码分享:

import random
import pygame
from pygame.locals import KEYDOWN, QUIT, K_ESCAPE, K_SPACE, K_q, K_e

from objects import Rocket, Asteroid, Bullet, Explosion


### SETUP *********************************************************************
SIZE = SCREEN_WIDTH, SCREEN_HEIGHT = 500, 500

pygame.mixer.init()
pygame.init()
clock = pygame.time.Clock()
win = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Asteroids')

gunshot_sound = pygame.mixer.Sound("music/laser.wav")
explosion_sound = pygame.mixer.Sound("music/explosion.mp3")

font = pygame.font.Font('freesansbold.ttf', 32)
# text = font.render('', True, green, blue)


### Objects & Events **********************************************************
ADDAST1 = pygame.USEREVENT + 1
ADDAST2 = pygame.USEREVENT + 2
ADDAST3 = pygame.USEREVENT + 3
ADDAST4 = pygame.USEREVENT + 4
ADDAST5 = pygame.USEREVENT + 5
pygame.time.set_timer(ADDAST1, 2000)
pygame.time.set_timer(ADDAST2, 6000)
pygame.time.set_timer(ADDAST3, 10000)
pygame.time.set_timer(ADDAST4, 15000)
pygame.time.set_timer(ADDAST5, 20000)

rocket = Rocket(SIZE)

asteroids = pygame.sprite.Group()
bullets = pygame.sprite.Group()
explosions = pygame.sprite.Group()
all_sprites = pygame.sprite.Group()
all_sprites.add(rocket)

backgrounds = [f'assets/background/bg{i}s.png' for i in range(1,5)]
bg = pygame.image.load(random.choice(backgrounds))

startbg = pygame.image.load('assets/start.jpg')

### Game **********************************************************************
if __name__ == '__main__':
    score = 0
    running = True
    gameStarted = False
    musicStarted = False
    while running:
        if not gameStarted:
            if not musicStarted:
                pygame.mixer.music.load('music/Apoxode_-_Electric_1.mp3')
                pygame.mixer.music.play(loops=-1)
                musicStarted = True
            for event in pygame.event.get():
                if event.type == QUIT:
                    running = False

                if event.type == KEYDOWN:
                    if event.key == K_SPACE:
                        gameStarted = True
                        musicStarted = False

                win.blit(startbg, (0,0))        
        else:
            if not musicStarted:
                pygame.mixer.music.load('music/rpg_ambience_-_exploration.ogg')
                pygame.mixer.music.play(loops=-1)
                musicStarted = True
            for event in pygame.event.get():
                if event.type == QUIT:
                    running = False

                if event.type == KEYDOWN:
                    if event.key == K_ESCAPE:
                        running = False
                    if event.key == K_SPACE:
                        pos = rocket.rect[:2]
                        bullet = Bullet(pos, rocket.dir, SIZE)
                        bullets.add(bullet)
                        all_sprites.add(bullet)
                        gunshot_sound.play()
                    if event.key == K_q:
                        rocket.rotate_left()
                    if event.key == K_e:
                        rocket.rotate_right()

                elif event.type == ADDAST1:
                    ast = Asteroid(1, SIZE)
                    asteroids.add(ast)
                    all_sprites.add(ast)
                elif event.type == ADDAST2:
                    ast = Asteroid(2, SIZE)
                    asteroids.add(ast)
                    all_sprites.add(ast)
                elif event.type == ADDAST3:
                    ast = Asteroid(3, SIZE)
                    asteroids.add(ast)
                    all_sprites.add(ast)
                elif event.type == ADDAST4:
                    ast = Asteroid(4, SIZE)
                    asteroids.add(ast)
                    all_sprites.add(ast)
                elif event.type == ADDAST5:
                    ast = Asteroid(5, SIZE)
                    asteroids.add(ast)
                    all_sprites.add(ast)


            pressed_keys = pygame.key.get_pressed()
            rocket.update(pressed_keys)

            asteroids.update()
            bullets.update()
            explosions.update()

            win.blit(bg, (0,0))
            explosions.draw(win)

            for sprite in all_sprites:
                win.blit(sprite.surf, sprite.rect)
            win.blit(rocket.surf, rocket.rect)

            if pygame.sprite.spritecollideany(rocket, asteroids):
                rocket.kill()
                score = 0
                for sprite in all_sprites:
                    sprite.kill()
                all_sprites.empty()
                rocket = Rocket(SIZE)
                all_sprites.add(rocket)
                gameStarted = False
                musicStarted = False

            for bullet in bullets:
                collision = pygame.sprite.spritecollide(bullet, asteroids, True)
                if collision:
                    pos = bullet.rect[:2]
                    explosion = Explosion(pos)
                    explosions.add(explosion)
                    score += 1
                    explosion_sound.play()

                    bullet.kill()
                    bullets.remove(bullet)

            text = font.render('Score : ' + str(score), 1, (200,255,0))
            win.blit(text, (340, 10))

        pygame.display.flip()
        clock.tick(30)

    pygame.quit()

5、弹跳的球
在这里插入图片描述

源码分享:

import os
import pygame

from player import Ball
from world import World, load_level
from texts import Text, Message
from button import Button, LevelButton

pygame.init()
WIDTH, HEIGHT = 192, 212
win = pygame.display.set_mode((WIDTH, HEIGHT), pygame.NOFRAME)
pygame.display.set_caption('Bounce')

clock = pygame.time.Clock()
FPS = 30

# GAME VARIABLES **************************************************************
ROWS = 12
MAX_COLS = 150
TILE_SIZE = 16
MAX_LEVEL = 8

# COLORS **********************************************************************

BLUE = (175, 207, 240)
BLUE2 = (0, 0, 255)
WHITE = (255, 255, 255)

# FONTS ***********************************************************************

health_font = "Fonts/ARCADECLASSIC.TTF"

level_text = Text(health_font, 24)
health_text = Message(40, WIDTH + 10, 19, "x3", health_font, WHITE, win)
select_level_text = Message(WIDTH//2, 20, 24, "Select  Level", health_font, BLUE2, win)
current_level_text = Message(WIDTH - 40, WIDTH + 10, 20, "Level 1", health_font, WHITE, win)
you_win = Message(WIDTH //2, HEIGHT//2, 40, "You  Win", health_font, BLUE2, win)

# SOUNDS **********************************************************************

click_fx = pygame.mixer.Sound('Sounds/click.mp3')
life_fx = pygame.mixer.Sound('Sounds/gate.mp3')
checkpoint_fx = pygame.mixer.Sound('Sounds/checkpoint.mp3')

pygame.mixer.music.load('Sounds/track1.wav')
pygame.mixer.music.play(loops=-1)
pygame.mixer.music.set_volume(0.4)

# LOADING IMAGES **************************************************************

ball_image = pygame.image.load('Assets/ball.png')
splash_img = pygame.transform.scale(pygame.image.load('Assets/splash_logo.png'),
             (2*WIDTH, HEIGHT))
bounce_img = pygame.image.load('Assets/menu_logo.png')
game_lost_img = pygame.image.load('Assets/lose.png')
game_lost_img = pygame.transform.scale(game_lost_img, (WIDTH//2, 80))
level_locked_img = pygame.image.load('Assets/level_locked.png')
level_locked_img = pygame.transform.scale(level_locked_img, (40, 40))
level_unlocked_img = pygame.image.load('Assets/level_unlocked.png')
level_unlocked_img = pygame.transform.scale(level_unlocked_img, (40, 40))


play_img = pygame.image.load('Assets/play.png')
restart_img = pygame.image.load('Assets/restart.png')
menu_img = pygame.image.load('Assets/menu.png')
sound_on_img = pygame.image.load('Assets/SoundOnBtn.png')
sound_off_img = pygame.image.load('Assets/SoundOffBtn.png')
game_won_img = pygame.image.load('Assets/game won.png')


# BUTTONS *********************************************************************

play_btn = Button(play_img, False, 45, 130)
sound_btn = Button(sound_on_img, False, 45, 170)
restart_btn = Button(restart_img, False, 45, 130)
menu_btn = Button(menu_img, False, 45, 170)

# LEVEL TEXT & BUTTONS ********************************************************

level_btns = []
for level in range(MAX_LEVEL):
    text = level_text.render(f'{level+1}', (255, 255, 255))
    r = level // 3
    c = level % 3
    btn = LevelButton(level_locked_img, (40, 40), 20 + c * 55, 50 + r * 55, text)
    level_btns.append(btn)

# GROUPS **********************************************************************

spikes_group = pygame.sprite.Group()
inflator_group = pygame.sprite.Group()
deflator_group = pygame.sprite.Group()
enemy_group = pygame.sprite.Group()
exit_group = pygame.sprite.Group()
checkpoint_group = pygame.sprite.Group()
health_group = pygame.sprite.Group()

objects_groups = [spikes_group, inflator_group, deflator_group, enemy_group, exit_group, 
                    checkpoint_group, health_group]
collision_groups = [inflator_group, deflator_group]

# RESET ***********************************************************************

def reset_level_data(level):
    for group in objects_groups:
        group.empty()

    # LOAD LEVEL WORLD

    world_data, level_length = load_level(level)
    w = World(objects_groups)
    w.generate_world(world_data, win)

    return world_data, level_length, w

def reset_player_data(level):
    if level == 1:
        x, y = 64, 50
    if level == 2:
        x, y = 65, 50
    if level == 3:
        x, y = 64, 50
    if level == 4:
        x, y = 63, 50
    if level == 5:
        x, y = 64, 50
    if level == 6:
        x, y = 48, 50
    if level == 7:
        x, y = 78, 80
    if level == 8:
        x, y = 112,100

    p = Ball(x, y)
    moving_left = False
    moving_right = False

    return p, moving_left, moving_right

# VARIABLES *******************************************************************

moving_left = False
moving_right = False

SCROLL_THRES = 80
screen_scroll = 0
level_scroll = 0
level = 1
next_level = False
reset_level = False

checkpoint = None
health = 3
splash_count = 0
sound_on = True

logo_page = True
home_page = False
level_page = False
game_page = False
restart_page = False
win_page = False

running = True
while running:
    win.fill(BLUE)
    pygame.draw.rect(win, (255, 255,255), (0, 0, WIDTH, HEIGHT), 1, border_radius=5)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE or \
                event.key == pygame.K_q:
                running = False

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                moving_left = True
            if event.key == pygame.K_RIGHT:
                moving_right = True
            if event.key == pygame.K_UP:
                if not p.jump:
                    p.jump = True

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT:
                moving_left = False
            if event.key == pygame.K_RIGHT:
                moving_right = False

    if logo_page:
        win.blit(splash_img, (-100,0))
        splash_count += 1
        if splash_count % 50 == 0:
            logo_page = False
            home_page = True

    if home_page:
        win.blit(bounce_img, (10,10))

        if play_btn.draw(win):
            click_fx.play()
            home_page = False
            level_page = True

        if sound_btn.draw(win):
            click_fx.play()
            sound_on = not sound_on

            if sound_on:
                sound_btn.update_image(sound_on_img)
                pygame.mixer.music.play(loops=-1)
            else:
                sound_btn.update_image(sound_off_img)
                pygame.mixer.music.stop()

    if level_page:
        select_level_text.update(shadow=False)
        for index, btn in enumerate(level_btns):
            if index < level:
                if not btn.unlocked:
                    btn.unlocked = True
                    btn.update_image(level_unlocked_img)
            if btn.draw(win):
                if index < level:
                    click_fx.play()
                    level_page = False
                    game_page = True
                    level = index + 1
                    screen_scroll = 0
                    level_scroll = 0
                    health = 3
                    world_data, level_length, w = reset_level_data(level)
                    p, moving_left, moving_right = reset_player_data(level)

    if restart_page:
        win.blit(game_lost_img, (45,20))
        if restart_btn.draw(win):
            click_fx.play()
            world_data, level_length, w = reset_level_data(level)
            p, moving_left, moving_right = reset_player_data(level)
            level_scroll = 0
            screen_scroll = 0
            health = 3
            checkpoint = None
            restart_page = False
            game_page = True

        if menu_btn.draw(win):
            click_fx.play()
            home_page = True
            restart_page = False

    if win_page:
        win.blit(game_won_img, (45, 20))
        you_win.update()
        if menu_btn.draw(win):
            click_fx.play()
            home_page = True
            win_page = False
            restart_page = False


    if game_page:
        w.update(screen_scroll)
        w.draw(win)

        spikes_group.update(screen_scroll)
        spikes_group.draw(win)
        health_group.update(screen_scroll)
        health_group.draw(win)
        inflator_group.update(screen_scroll)
        inflator_group.draw(win)
        deflator_group.update(screen_scroll)
        deflator_group.draw(win)
        exit_group.update(screen_scroll)
        exit_group.draw(win)
        checkpoint_group.update(screen_scroll)
        checkpoint_group.draw(win)
        enemy_group.update(screen_scroll)
        enemy_group.draw(win)

        screen_scroll = 0
        p.update(moving_left, moving_right, w, collision_groups)
        p.draw(win)

        if ((p.rect.right >= WIDTH - SCROLL_THRES) and level_scroll < (level_length * 16) - WIDTH) \
                or ((p.rect.left <= SCROLL_THRES) and level_scroll > 0):
                dx = p.dx
                p.rect.x -= dx
                screen_scroll = -dx
                level_scroll += dx

        if len(exit_group) > 0:
            exit = exit_group.sprites()[0]
            if not exit.open:
                if abs(p.rect.x - exit.rect.x) <= 80 and len(health_group) == 0:
                    exit.open = True

            if p.rect.colliderect(exit.rect) and exit.index == 11:
                checkpoint = None
                checkpoint_fx.play()
                level += 1
                if level < MAX_LEVEL:
                    checkpoint = False
                    reset_level = True
                    next_level = True
                else:
                    checkpoint = None
                    win_page = True

        cp = pygame.sprite.spritecollide(p, checkpoint_group, False)
        if cp:
            checkpoint = cp[0]
            if not checkpoint.catched:
                checkpoint_fx.play()
                checkpoint.catched = True
                checkpoint_pos = p.rect.center
                checkpoint_screen_scroll = screen_scroll
                checkpoint_level_scroll = level_scroll

        if pygame.sprite.spritecollide(p, spikes_group, False):
            reset_level = True

        if pygame.sprite.spritecollide(p, health_group, True):
            health += 1
            life_fx.play()

        if pygame.sprite.spritecollide(p, enemy_group, False):
            reset_level = True

        if reset_level:
            if health > 0:
                if next_level:
                    world_data, level_length, w = reset_level_data(level)
                    p, moving_left, moving_right = reset_player_data(level)
                    level_scroll = 0
                    health = 3
                    checkpoint = None
                    next_level = False

                elif checkpoint:
                    checkpoint_dx = level_scroll - checkpoint_level_scroll
                    w.update(checkpoint_dx)
                    for group in objects_groups:
                        group.update(checkpoint_dx)
                    p.rect.center = checkpoint_pos
                    level_scroll = checkpoint_level_scroll

                else:
                    w.update(level_scroll)
                    for group in objects_groups:
                        group.update(level_scroll)
                    p, moving_left, moving_right = reset_player_data(level)
                    level_scroll = 0

                screen_scroll = 0
                reset_level = False
                health -= 1
            else:
                restart_page = True
                game_page = False
                reset_level = False

        # Drawing info bar
        pygame.draw.rect(win, (25, 25, 25), (0, HEIGHT-20, WIDTH, 20))
        pygame.draw.rect(win, (255, 255,255), (0, 0, WIDTH, WIDTH), 2, border_radius=5)

        win.blit(ball_image, (5, WIDTH + 2))
        health_text.update(f'x{health}', shadow=False)
        current_level_text.update(f'Level {level}', shadow=False)

    clock.tick(FPS)
    pygame.display.update()

pygame.quit()

6、汽车避障
在这里插入图片描述

源码分享:

import pygame
import random
from objects import Road, Player, Nitro, Tree, Button, \
                    Obstacle, Coins, Fuel

pygame.init()
SCREEN = WIDTH, HEIGHT = 288, 512

info = pygame.display.Info()
width = info.current_w
height = info.current_h

if width >= height:
    win = pygame.display.set_mode(SCREEN, pygame.NOFRAME)
else:
    win = pygame.display.set_mode(SCREEN, pygame.NOFRAME | pygame.SCALED | pygame.FULLSCREEN)

clock = pygame.time.Clock()
FPS = 30

lane_pos = [50, 95, 142, 190]

# COLORS **********************************************************************

WHITE = (255, 255, 255)
BLUE = (30, 144,255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLACK = (0, 0, 20)

# FONTS ***********************************************************************

font = pygame.font.SysFont('cursive', 32)

select_car = font.render('Select Car', True, WHITE)

# IMAGES **********************************************************************

bg = pygame.image.load('Assets/bg.png')

home_img = pygame.image.load('Assets/home.png')
play_img = pygame.image.load('Assets/buttons/play.png')
end_img = pygame.image.load('Assets/end.jpg')
end_img = pygame.transform.scale(end_img, (WIDTH, HEIGHT))
game_over_img = pygame.image.load('Assets/game_over.png')
game_over_img = pygame.transform.scale(game_over_img, (220, 220))
coin_img = pygame.image.load('Assets/coins/1.png')
dodge_img = pygame.image.load('Assets/car_dodge.png')

left_arrow = pygame.image.load('Assets/buttons/arrow.png')
right_arrow = pygame.transform.flip(left_arrow, True, False)

home_btn_img = pygame.image.load('Assets/buttons/home.png')
replay_img = pygame.image.load('Assets/buttons/replay.png')
sound_off_img = pygame.image.load("Assets/buttons/soundOff.png")
sound_on_img = pygame.image.load("Assets/buttons/soundOn.png")

cars = []
car_type = 0
for i in range(1, 9):
    img = pygame.image.load(f'Assets/cars/{i}.png')
    img = pygame.transform.scale(img, (59, 101))
    cars.append(img)

nitro_frames = []
nitro_counter = 0
for i in range(6):
    img = pygame.image.load(f'Assets/nitro/{i}.gif')
    img = pygame.transform.flip(img, False, True)
    img = pygame.transform.scale(img, (18, 36))
    nitro_frames.append(img)

# FUNCTIONS *******************************************************************
def center(image):
    return (WIDTH // 2) - image.get_width() // 2

# BUTTONS *********************************************************************
play_btn = Button(play_img, (100, 34), center(play_img)+10, HEIGHT-80)
la_btn = Button(left_arrow, (32, 42), 40, 180)
ra_btn = Button(right_arrow, (32, 42), WIDTH-60, 180)

home_btn = Button(home_btn_img, (24, 24), WIDTH // 4 - 18, HEIGHT - 80)
replay_btn = Button(replay_img, (36,36), WIDTH // 2  - 18, HEIGHT - 86)
sound_btn = Button(sound_on_img, (24, 24), WIDTH - WIDTH // 4 - 18, HEIGHT - 80)

# SOUNDS **********************************************************************

click_fx = pygame.mixer.Sound('Sounds/click.mp3')
fuel_fx = pygame.mixer.Sound('Sounds/fuel.wav')
start_fx = pygame.mixer.Sound('Sounds/start.mp3')
restart_fx = pygame.mixer.Sound('Sounds/restart.mp3')
coin_fx = pygame.mixer.Sound('Sounds/coin.mp3')

pygame.mixer.music.load('Sounds/mixkit-tech-house-vibes-130.mp3')
pygame.mixer.music.play(loops=-1)
pygame.mixer.music.set_volume(0.6)

# OBJECTS *********************************************************************
road = Road()
nitro = Nitro(WIDTH-80, HEIGHT-80)
p = Player(100, HEIGHT-120, car_type)

tree_group = pygame.sprite.Group()
coin_group = pygame.sprite.Group()
fuel_group = pygame.sprite.Group()
obstacle_group = pygame.sprite.Group()

# VARIABLES *******************************************************************
home_page = True
car_page = False
game_page = False
over_page = False

move_left = False
move_right = False
nitro_on = False
sound_on = True

counter = 0
counter_inc = 1
# speed = 3
speed = 10
dodged = 0
coins = 0
cfuel = 100

endx, enddx = 0, 0.5
gameovery = -50

running = True
while running:
    win.fill(BLACK)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE or event.key == pygame.K_q:
                running = False

            if event.key == pygame.K_LEFT:
                move_left = True

            if event.key == pygame.K_RIGHT:
                move_right = True

            if event.key == pygame.K_n:
                nitro_on = True

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT:
                move_left = False

            if event.key == pygame.K_RIGHT:
                move_right = False

            if event.key == pygame.K_n:
                nitro_on = False
                speed = 3
                counter_inc = 1

        if event.type == pygame.MOUSEBUTTONDOWN:
            x, y = event.pos

            if nitro.rect.collidepoint((x, y)):
                nitro_on = True
            else:
                if x <= WIDTH // 2:
                    move_left = True
                else:
                    move_right = True

        if event.type == pygame.MOUSEBUTTONUP:
            move_left = False
            move_right = False
            nitro_on = False
            speed = 3
            counter_inc = 1

    if home_page:
        win.blit(home_img, (0,0))
        counter += 1
        if counter % 60 == 0:
            home_page = False
            car_page = True

    if car_page:
        win.blit(select_car, (center(select_car), 80))

        win.blit(cars[car_type], (WIDTH//2-30, 150))
        if la_btn.draw(win):
            car_type -= 1
            click_fx.play()
            if car_type < 0:
                car_type = len(cars) - 1

        if ra_btn.draw(win):
            car_type += 1
            click_fx.play()
            if car_type >= len(cars):
                car_type = 0

        if play_btn.draw(win):
            car_page = False
            game_page = True

            start_fx.play()

            p = Player(100, HEIGHT-120, car_type)
            counter = 0

    if over_page:
        win.blit(end_img, (endx, 0))
        endx += enddx
        if endx >= 10 or endx<=-10:
            enddx *= -1

        win.blit(game_over_img, (center(game_over_img), gameovery))
        if gameovery < 16:
            gameovery += 1

        num_coin_img = font.render(f'{coins}', True, WHITE)
        num_dodge_img = font.render(f'{dodged}', True, WHITE)
        distance_img = font.render(f'Distance : {counter/1000:.2f} km', True, WHITE)

        win.blit(coin_img, (80, 240))
        win.blit(dodge_img, (50, 280))
        win.blit(num_coin_img, (180, 250))
        win.blit(num_dodge_img, (180, 300))
        win.blit(distance_img, (center(distance_img), (350)))

        if home_btn.draw(win):
            over_page = False
            home_page = True

            coins = 0
            dodged = 0
            counter = 0
            nitro.gas = 0
            cfuel = 100

            endx, enddx = 0, 0.5
            gameovery = -50

        if replay_btn.draw(win):
            over_page = False
            game_page = True

            coins = 0
            dodged = 0
            counter = 0
            nitro.gas = 0
            cfuel = 100

            endx, enddx = 0, 0.5
            gameovery = -50

            restart_fx.play()

        if sound_btn.draw(win):
            sound_on = not sound_on

            if sound_on:
                sound_btn.update_image(sound_on_img)
                pygame.mixer.music.play(loops=-1)
            else:
                sound_btn.update_image(sound_off_img)
                pygame.mixer.music.stop()

    if game_page:
        win.blit(bg, (0,0))
        road.update(speed)
        road.draw(win)

        counter += counter_inc
        if counter % 60 == 0:
            tree = Tree(random.choice([-5, WIDTH-35]), -20)
            tree_group.add(tree)

        if counter % 270 == 0:
            type = random.choices([1, 2], weights=[6, 4], k=1)[0]
            x = random.choice(lane_pos)+10
            if type == 1:
                count = random.randint(1, 3)
                for i in range(count):
                    coin = Coins(x,-100 - (25 * i))
                    coin_group.add(coin)
            elif type == 2:
                fuel = Fuel(x, -100)
                fuel_group.add(fuel)
        elif counter % 90 == 0:
            obs = random.choices([1, 2, 3], weights=[6,2,2], k=1)[0]
            obstacle = Obstacle(obs)
            obstacle_group.add(obstacle)

        if nitro_on and nitro.gas > 0:
            x, y = p.rect.centerx - 8, p.rect.bottom - 10
            win.blit(nitro_frames[nitro_counter], (x, y))
            nitro_counter = (nitro_counter + 1) % len(nitro_frames)

            speed = 10
            if counter_inc == 1:
                counter = 0
                counter_inc = 5

        if nitro.gas <= 0:
            speed = 3
            counter_inc = 1

        nitro.update(nitro_on)
        nitro.draw(win)
        obstacle_group.update(speed)
        obstacle_group.draw(win)
        tree_group.update(speed)
        tree_group.draw(win)
        coin_group.update(speed)
        coin_group.draw(win)
        fuel_group.update(speed)
        fuel_group.draw(win)

        p.update(move_left, move_right)
        p.draw(win)

        if cfuel > 0:
            pygame.draw.rect(win, GREEN, (20, 20, cfuel, 15), border_radius=5)
        pygame.draw.rect(win, WHITE, (20, 20, 100, 15), 2, border_radius=5)
        cfuel -= 0.05

        # COLLISION DETECTION & KILLS
        for obstacle in obstacle_group:
            if obstacle.rect.y >= HEIGHT:
                if obstacle.type == 1:
                    dodged += 1
                obstacle.kill() 

            if pygame.sprite.collide_mask(p, obstacle):
                pygame.draw.rect(win, RED, p.rect, 1)
                speed = 0

                game_page = False
                over_page = True

                tree_group.empty()
                coin_group.empty()
                fuel_group.empty()
                obstacle_group.empty()

        if pygame.sprite.spritecollide(p, coin_group, True):
            coins += 1
            coin_fx.play()

        if pygame.sprite.spritecollide(p, fuel_group, True):
            cfuel += 25
            fuel_fx.play()
            if cfuel >= 100:
                cfuel = 100

    pygame.draw.rect(win, BLUE, (0, 0, WIDTH, HEIGHT), 3)
    clock.tick(FPS)
    pygame.display.update()

pygame.quit()

7、洞窟物语

在这里插入图片描述

源码分享:

import pygame
import pickle

from objects import World, load_level, Button, Player, Portal, game_data

pygame.init()
SCREEN = WIDTH, HEIGHT = 288, 512
win = pygame.display.set_mode(SCREEN, pygame.SCALED | pygame.FULLSCREEN)
clock = pygame.time.Clock()
FPS = 45

tile_size = 16

# Images

bg = pygame.image.load("Assets/bg.png")

cave_story = pygame.transform.rotate(pygame.image.load("Assets/cave_story.png"), 90)
cave_story = pygame.transform.scale(cave_story, (150,300))

game_won_img = pygame.transform.rotate(pygame.image.load("Assets/win.png"), -90)
game_won_img = pygame.transform.scale(game_won_img, (150,300))

# Sounds
pygame.mixer.music.load('Sounds/goodbyte_sad-rpg-town.mp3')
pygame.mixer.music.play(loops=-1)

replay_fx =  pygame.mixer.Sound('Sounds/replay.wav')

# Buttons

move_btn = pygame.image.load("Assets/movement.jpeg")
move_btn = pygame.transform.rotate(move_btn, -90)
move_btn = pygame.transform.scale(move_btn, (42, HEIGHT))

play_img = pygame.transform.rotate(pygame.image.load("Assets/play.png"), -90)
play_btn = Button(play_img, (60, 150), 30, 170)

quit_img = pygame.transform.rotate(pygame.image.load("Assets/quit.png"), -90)
quit_btn = Button(quit_img, (60, 150), 140, 170)

replay_img = pygame.transform.rotate(pygame.image.load("Assets/replay.png"), -90)
replay_btn = Button(replay_img, (40, 40), 100, 190)

sound_off_img = pygame.transform.rotate(pygame.image.load("Assets/sound_off.png"), -90)
sound_on_img = pygame.transform.rotate(pygame.image.load("Assets/sound_on.png"), -90)
sound_btn = Button(sound_on_img, (40, 40), 100, 260)

# Variables

current_level = 1
MAX_LEVEL = 3
show_keys = True
pressed_keys = [False, False, False, False]

dir_dict = {
    'Up' : pygame.Rect(5, 27, 35, 50),
    'Down' : pygame.Rect(5, 160, 35, 50),
    'Left' :  pygame.Rect(5, 320, 35, 50),
    'Right' : pygame.Rect(5, 450, 35, 50)
}

# groups 
diamond_group = pygame.sprite.Group()
spike_group = pygame.sprite.Group()
plant_group = pygame.sprite.Group()
board_group = pygame.sprite.Group()
chain_group = pygame.sprite.Group()
groups = [diamond_group, spike_group, plant_group, board_group, chain_group]

data = load_level(current_level)
(player_x, player_y), (portal_x, portal_y) = game_data(current_level)

world = World(win, data, groups)
player = Player(win, (player_x,player_y), world, groups)
portal = Portal(portal_x, portal_y, win)

game_started = False
game_over = False
game_won = False
replay_menu = False
sound_on = True

bgx = 0
bgcounter = 0
bgdx = 1

running = True
while running:
    win.blit(bg, (bgx, 0))
    for group in groups:
        group.draw(win)
    world.draw()

    if not game_started:
        win.blit(cave_story, (100,100))
        if play_btn.draw(win):
            game_started = True
    elif game_won:
        win.blit(game_won_img, (100,100))
    else:
        if show_keys:
            win.blit(move_btn, (0,0))
            bgcounter += 1
            if bgcounter >= 15:
                bgcounter = 0
                bgx += bgdx
                if bgx < 0 or bgx >5 :
                    bgdx *= -1

    #   for rect in dir_dict:
    #       pygame.draw.rect(win, (255, 0, 0), dir_dict[rect])

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

            if event.type == pygame.MOUSEBUTTONDOWN:
                pos = event.pos
                if show_keys:
                    if dir_dict["Up"].collidepoint(pos):
                        pressed_keys[0] = True
                    if dir_dict["Down"].collidepoint(pos):
                        pressed_keys[1] = True
                    if dir_dict["Left"].collidepoint(pos):
                        pressed_keys[2] = True
                    if dir_dict["Right"].collidepoint(pos):
                        pressed_keys[3] = True

            if event.type == pygame.MOUSEBUTTONUP:
                pressed_keys = [False, False, False, False]

        portal.update()

        if not game_over:
            game_over = player.update(pressed_keys, game_over)
            if game_over:
                show_keys = False
                replay_menu = True

        if player.rect.colliderect(portal) and player.rect.top > portal.rect.top and player.rect.bottom < portal.rect.bottom:
            if current_level < MAX_LEVEL:
                current_level += 1
                for group in groups:
                    group.empty()

                data = load_level(current_level)
                (player_x, player_y), (portal_x, portal_y) = game_data(current_level)

                world = World(win, data, groups)
                player = Player(win, (player_x,player_y), world, groups)
                portal = Portal(portal_x, portal_y, win)
            else:
                show_keys = False
                game_won = True

        if replay_menu:
            if quit_btn.draw(win):
                running = False

            if sound_btn.draw(win):
                sound_on = not sound_on

                if sound_on:
                    sound_btn.update_image(sound_on_img)
                    pygame.mixer.music.play(loops=-1)
                else:
                    sound_btn.update_image(sound_off_img)
                    pygame.mixer.music.stop()

            if replay_btn.draw(win):
                show_keys = True
                replay_menu = False
                game_over = False
                replay_fx.play()

                for group in groups:
                    group.empty()

                data = load_level(current_level)
                (player_x, player_y), (portal_x, portal_y) = game_data(current_level)

                world = World(win, data, groups)
                player = Player(win, (player_x,player_y), world, groups)
                portal = Portal(portal_x, portal_y, win)

    clock.tick(FPS)
    pygame.display.update()

pygame.quit()

8、联系

在这里插入图片描述

源码分享:

# Connected

# Author : Prajjwal Pathak (pyguru)
# Date : Thursday, 8 August, 2021

import random
import pygame

from objects import Balls, Coins, Tiles, Particle, Message, Button

pygame.init()
SCREEN = WIDTH, HEIGHT = 288, 512
CENTER = WIDTH //2, HEIGHT // 2

info = pygame.display.Info()
width = info.current_w
height = info.current_h

if width >= height:
    win = pygame.display.set_mode(SCREEN, pygame.NOFRAME)
else:
    win = pygame.display.set_mode(SCREEN, pygame.NOFRAME | pygame.SCALED | pygame.FULLSCREEN)
pygame.display.set_caption('Connected')

clock = pygame.time.Clock()
FPS = 90

# COLORS **********************************************************************

RED = (255,0,0)
GREEN = (0,177,64)
BLUE = (30, 144,255)
ORANGE = (252,76,2)
YELLOW = (254,221,0)
PURPLE = (155,38,182)
AQUA = (0,103,127)
WHITE = (255,255,255)
BLACK = (0,0,0)
GRAY = (25, 25, 25)

color_list = [PURPLE, GREEN, BLUE, ORANGE, YELLOW, RED]
color_index = 0
color = color_list[color_index]

# SOUNDS **********************************************************************

flip_fx = pygame.mixer.Sound('Sounds/flip.mp3')
score_fx = pygame.mixer.Sound('Sounds/point.mp3')
dead_fx = pygame.mixer.Sound('Sounds/dead.mp3')
score_page_fx = pygame.mixer.Sound('Sounds/score_page.mp3')

pygame.mixer.music.load('Sounds/bgm.mp3')
pygame.mixer.music.play(loops=-1)
pygame.mixer.music.set_volume(0.5)


# FONTS ***********************************************************************

title_font = "Fonts/Aladin-Regular.ttf"
score_font = "Fonts/DroneflyRegular-K78LA.ttf"
game_over_font = "Fonts/ghostclan.ttf"
final_score_font = "Fonts/DalelandsUncialBold-82zA.ttf"
new_high_font = "Fonts/BubblegumSans-Regular.ttf"


connected = Message(WIDTH//2, 120, 55, "ConnecteD", title_font, WHITE, win)
score_msg = Message(WIDTH//2, 100, 60, "0", score_font, (150, 150, 150), win)
game_msg = Message(80, 150, 40, "GAME", game_over_font, BLACK, win)
over_msg = Message(210, 150, 40, "OVER!", game_over_font, WHITE, win)
final_score = Message(WIDTH//2, HEIGHT//2, 90, "0", final_score_font, RED, win)
new_high_msg = Message(WIDTH//2, HEIGHT//2+60, 20, "New High", None, GREEN, win)

# Button images

home_img = pygame.image.load('Assets/homeBtn.png')
replay_img = pygame.image.load('Assets/replay.png')
sound_off_img = pygame.image.load("Assets/soundOffBtn.png")
sound_on_img = pygame.image.load("Assets/soundOnBtn.png")
easy_img = pygame.image.load("Assets/easy.jpg")
hard_img = pygame.image.load("Assets/hard.jpg")

# Buttons

easy_btn = Button(easy_img, (70, 24), WIDTH//4-10, HEIGHT-100)
hard_btn = Button(hard_img, (70, 24), WIDTH//2 + 10, HEIGHT-100)
home_btn = Button(home_img, (24, 24), WIDTH // 4 - 18, HEIGHT//2 + 120)
replay_btn = Button(replay_img, (36,36), WIDTH // 2  - 18, HEIGHT//2 + 115)
sound_btn = Button(sound_on_img, (24, 24), WIDTH - WIDTH // 4 - 18, HEIGHT//2 + 120)

# Groups **********************************************************************

RADIUS = 70
ball_group = pygame.sprite.Group()
coin_group = pygame.sprite.Group()
tile_group = pygame.sprite.Group()
particle_group = pygame.sprite.Group()

ball = Balls((CENTER[0], CENTER[1]+RADIUS), RADIUS, 90, win)
ball_group.add(ball)
ball = Balls((CENTER[0], CENTER[1]-RADIUS), RADIUS, 270, win)
ball_group.add(ball)

# TIME ************************************************************************

start_time = pygame.time.get_ticks()
current_time = 0
coin_delta = 850
tile_delta = 2000

# VARIABLES *******************************************************************

clicked = False
new_coin = True
num_clicks = 0
score = 0

player_alive = True
score = 0
highscore = 0
sound_on = True
easy_level = True

home_page = True
game_page = False
score_page = False

running = True
while running:
    win.fill(GRAY)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE or \
                event.key == pygame.K_q:
                running = False

        if event.type == pygame.MOUSEBUTTONDOWN and game_page:
            if not clicked:
                clicked = True
                for ball in ball_group:
                    ball.dtheta *= -1
                    flip_fx.play()

                num_clicks += 1
                if num_clicks % 5 == 0:
                    color_index += 1
                    if color_index > len(color_list) - 1:
                        color_index = 0

                    color = color_list[color_index]

        if event.type == pygame.MOUSEBUTTONDOWN and game_page:
            clicked = False

    if home_page:
        connected.update()

        pygame.draw.circle(win, BLACK, CENTER, 80, 20)
        ball_group.update(color)

        if easy_btn.draw(win):
            ball_group.empty()
            ball = Balls((CENTER[0], CENTER[1]+RADIUS), RADIUS, 90, win)
            ball_group.add(ball)

            home_page = False
            game_page = True
            easy_level = True

        if hard_btn.draw(win):
            ball_group.empty()
            ball = Balls((CENTER[0], CENTER[1]+RADIUS), RADIUS, 90, win)
            ball_group.add(ball)
            ball = Balls((CENTER[0], CENTER[1]-RADIUS), RADIUS, 270, win)
            ball_group.add(ball)

            home_page = False
            game_page = True
            easy_level = False

    if score_page:
        game_msg.update()
        over_msg.update()

        if score:
            final_score.update(score, color)
        else:
            final_score.update("0", color)
        if score and (score >= highscore):
            new_high_msg.update(shadow=False)

        if home_btn.draw(win):
            home_page = True
            score_page = False
            game_page = False
            player_alive = True
            score = 0
            score_msg = Message(WIDTH//2, 100, 60, "0", score_font, (150, 150, 150), win)

        if replay_btn.draw(win):
            home_page = False
            score_page = False
            game_page = True
            score = 0
            score_msg = Message(WIDTH//2, 100, 60, "0", score_font, (150, 150, 150), win)

            if easy_level:
                ball = Balls((CENTER[0], CENTER[1]+RADIUS), RADIUS, 90, win)
                ball_group.add(ball)
            else:
                ball = Balls((CENTER[0], CENTER[1]+RADIUS), RADIUS, 90, win)
                ball_group.add(ball)
                ball = Balls((CENTER[0], CENTER[1]-RADIUS), RADIUS, 270, win)
                ball_group.add(ball)

            player_alive = True


        if sound_btn.draw(win):
            sound_on = not sound_on

            if sound_on:
                sound_btn.update_image(sound_on_img)
                pygame.mixer.music.play(loops=-1)
            else:
                sound_btn.update_image(sound_off_img)
                pygame.mixer.music.stop()

    if game_page:
        pygame.draw.circle(win, BLACK, CENTER, 80, 20)
        ball_group.update(color)
        coin_group.update(color)
        tile_group.update()
        score_msg.update(score)
        particle_group.update()

        if player_alive:
            for ball in ball_group:
                if pygame.sprite.spritecollide(ball, coin_group, True):
                    score_fx.play()
                    score += 1
                    if highscore <= score:
                            highscore = score

                    x, y = ball.rect.center
                    for i in range(10):
                        particle = Particle(x, y, color, win)
                        particle_group.add(particle)

                if pygame.sprite.spritecollide(ball, tile_group, True):
                    x, y = ball.rect.center
                    for i in range(30):
                        particle = Particle(x, y, color, win)
                        particle_group.add(particle)

                    player_alive = False
                    dead_fx.play()

            current_time = pygame.time.get_ticks()
            delta = current_time- start_time
            if  coin_delta < delta < coin_delta + 100 and new_coin:
                y = random.randint(CENTER[1]-RADIUS, CENTER[1]+RADIUS)
                coin = Coins(y, win)
                coin_group.add(coin)
                new_coin = False

            if current_time- start_time >= tile_delta:
                y = random.choice([CENTER[1]-80, CENTER[1], CENTER[1]+80])
                type_ = random.randint(1,3)
                t = Tiles(y, type_, win)
                tile_group.add(t)

                start_time = current_time
                new_coin = True

        if not player_alive and len(particle_group) == 0:
            score_page = True
            game_page = False

            score_page_fx.play()

            ball_group.empty()
            tile_group.empty()
            coin_group.empty()

    pygame.draw.rect(win, BLUE, (0, 0, WIDTH, HEIGHT), 5, border_radius=10)
    clock.tick(FPS)
    pygame.display.update()

pygame.quit()

9、恐龙避障

在这里插入图片描述

10、超级玛丽

在这里插入图片描述

标签:边玩,10,group,img,win,源码,pygame,False,page
From: https://blog.csdn.net/m0_62283350/article/details/140098395

相关文章

  • 用python代码实现超级玛丽游戏(详细动画展示+源码分享)
    效果展示:温馨提示:篇幅有限,完整代码已打包文件夹,获取方式在:1.画面和角色的导入创建屏幕、从图片中导入Mario#屏幕创建和初始化参数self.screen=pygame.display.set_mode((WIDTH,HEIGHT))self.rect=self.screen.get_rect()pygame.display.set_caption(TITLE)......
  • 【打卡】002 p2 CIFAR10彩色图片识别
    打卡~555我的环境:●语言环境:Python●编译器:jupyternotebook●深度学习环境:Pytorch>-**......
  • 餐厅在线点餐小程序源码系统可外卖配送 带完整的安装代码包以及搭建部署教程
    系统概述在当今数字化时代,餐厅在线点餐小程序已成为餐饮行业的重要工具。它不仅为消费者提供了便捷的点餐体验,也为餐厅提高了运营效率和服务质量。小编给大家分享一款餐厅在线点餐小程序源码系统,该系统不仅支持在线点餐,还具备外卖配送功能,同时提供完整的安装代码包以及搭建部......
  • 最新AIGC系统源码-ChatGPT商业版系统源码,自定义ChatGPT指令Promp提示词,AI绘画系统,AI换
    目录一、前言系统文档二、系统演示核心AI能力系统快速体验三、系统功能模块3.1AI全模型支持/插件系统AI模型提问文档分析​识图理解能力3.2GPts应用3.2.1GPTs应用3.2.2GPTs工作台3.2.3自定义创建Promp指令预设应用3.3AI专业绘画3.3.1文生图/图生图(垫图)......
  • 1974Springboot医院远程诊断管理系统idea开发mysql数据库web结构java编程计算机网页源
    一、源码特点 springboot医院远程诊断管理系统是一套完善的信息系统,结合springboot框架和bootstrap完成本系统,对理解JSPjava编程开发语言有帮助系统采用springboot框架(MVC模式开发),系统具有完整的源代码和数据库,系统主要采用B/S模式开发。springboot医院远程诊断系统......
  • 适合任何行业在线DIY预约报名小程序源码系统 带完整的安装代码包以及搭建教程
    系统概述在当今数字化时代,便捷高效的预约报名系统成为了许多行业的迫切需求。“适合任何行业在线DIY预约报名小程序源码系统”便是一款为满足这一需求而设计开发的创新解决方案。这款源码系统是基于先进的技术架构,旨在为各类企业和组织提供一个强大、灵活且易于使用的在线......
  • LeetCode 1013. Partition Array Into Three Parts With Equal Sum
    原题链接在这里:https://leetcode.com/problems/partition-array-into-three-parts-with-equal-sum/description/题目:Givenanarrayofintegers arr,return true ifwecanpartitionthearrayintothree non-empty partswithequalsums.Formally,wecanpartition......
  • protobufjs解析proto消息出错RangeError: index out of range: 2499 + 10 > 2499解决办
    使用websocket通讯传输protobuf消息的时候,decode的时候出错了:RangeError:indexoutofrange:2499+10>2499Error:invalidwiretype4atoffset1986出现这种错误的时候,99%是因为proto里面的消息类型和服务端发送的消息类型不一致导致的。解决这个问题的办法有......
  • 10
    在本次的软件工程项目中,我们的团队旨在开发一款基于人脸识别的人脸检测APP,以帮助用户记录每日心情,记下当刻美好。最初的目的是为老年人群体提供便利,让他们可以通过简单的操作,轻松记录生活中的点滴。然而在项目执行过程中,出现了了一系列的问题,导致项目偏离了最初的设计构想,进度滞后......
  • Win10需要使用新应用以打开此windowsdefender链接怎么解决?
    1、以管理员身份打开“WindowsPowerShell”。 2、以管理员身份在Powershell中依次运行如下命令即可解决。1.$BasePath=Get-Content.appx.list(报错不要管)2.$BasePath|%{$Path=$($_).Trim()Add-AppxPackage-Register-DisableDevelopmentMode“$PathAppXManifest.xml......