Python小游戏(附源码)

1:飞机大战小游戏

ec250b99515f06a9d79a2d73bc55b663.png

 上源码

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.quite

2、行星大战射击游戏


05f7ff382e65b49cc4ad4272f6cddb5a.png

 废话不多说,上代码

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()

3、赛车竞赛游戏

a71072665a7234f7e6fd5b7a8203bcf5.png

 废话不多说,上代码。

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()

# 今天给大家介绍一款Python制作的汽车避障小游戏
# 主要通过Pygame实现的,运行代码,选择车型,进入游戏
# 可以控制左右移动,点击右下角可以进行加速
# 金 币可以增加积分,撞到障碍物则游戏介绍

                   

 

4. 电子时钟

d86f6f3043fa16f1dda52f07127b7001.png

 

 

import tkinter as tk
import time
import datetime
 
# 按照日期返回星期数
def get_week_day(date):
    # 用一个字典建立对应关系
    week_dict = {
        0: '星期一',
        1: '星期二',
        2: '星期三',
        3: '星期四',
        4: '星期五',
        5: '星期六',
        6: '星期日'
    }
    day = date.weekday()
    return week_dict.get(day)
 
# 每一秒修改一下clock的显示
def show_time():
    # 获取当前日期和星期
    now = datetime.datetime.now()
    week_day = get_week_day(now)
    str_date = now.strftime('%Y年%m月%d日') + ' ' + week_day
    # 获取当前时间
    str_time = now.strftime('%H:%M:%S %p')
    date_str.set(str_date)
    time_str.set(str_time)
    # 每隔一秒调用一次show_time函数
    clock_label.after(1000, show_time)
 
if __name__ == '__main__':
    # 创建主窗口
    win = tk.Tk()
    # 设置主窗口的标题
    win.title('电子时钟')
    # 设置主窗口的尺寸
    win.geometry('400x150')
    # 创建StringVar对象
    time_str = tk.StringVar()
    date_str = tk.StringVar()
    # 创建标签
    date_label = tk.Label(win, font=('黑体', 18), fg='blue', textvariable=date_str)
    clock_label = tk.Label(win, font=('黑体', 48), fg='red', textvariable=time_str)
    # 布局标签
    date_label.pack(anchor='center')
    clock_label.pack(anchor='center')
    # 显示时间
    show_time()
    # 运行主循环
 win.mainloop()

学会了吗?快去试试吧,再见

 

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值