文章目录
前言
在学习Python的过程中,不妨给自己增添一点乐趣,博主分享了几个小游戏的代码,欢迎大家边学边玩~
1.愤怒的墙
代码如下(示例):
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()
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 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()
4.汽车避障
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()
5.洞窟物语
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()
总结
祝大家边学边玩,游玩愉快~
关于Python技术储备
学好 Python 不论是就业还是做副业赚钱都不错,但要学会 Python 还是要有一个学习规划。最后大家分享一份全套的 Python 学习资料,给那些想学习 Python 的小伙伴们一点帮助!
👉CSDN大礼包:《Python入门资料&实战源码&安装工具】免费领取(安全链接,放心点击)
一、Python所有方向的学习路线
Python所有方向的技术点做的整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。
二、Python基础学习视频
② 路线对应学习视频
还有很多适合0基础入门的学习视频,有了这些视频,轻轻松松上手Python~在这里插入图片描述
③练习题
每节视频课后,都有对应的练习题哦,可以检验学习成果哈哈!
因篇幅有限,仅展示部分资料
三、精品Python学习书籍
当我学到一定基础,有自己的理解能力的时候,会去阅读一些前辈整理的书籍或者手写的笔记资料,这些笔记详细记载了他们对一些技术点的理解,这些理解是比较独到,可以学到不一样的思路。
四、Python工具包+项目源码合集
①Python工具包
学习Python常用的开发软件都在这里了!每个都有详细的安装教程,保证你可以安装成功哦!
②Python实战案例
光学理论是没用的,要学会跟着一起敲代码,动手实操,才能将自己的所学运用到实际当中去,这时候可以搞点实战案例来学习。100+实战案例源码等你来拿!
③Python小游戏源码
如果觉得上面的实战案例有点枯燥,可以试试自己用Python编写小游戏,让你的学习过程中增添一点趣味!
五、面试资料
我们学习Python必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有阿里大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。
六、Python兼职渠道
而且学会Python以后,还可以在各大兼职平台接单赚钱,各种兼职渠道+兼职注意事项+如何和客户沟通,我都整理成文档了。
这份完整版的Python全套学习资料已经上传CSDN,朋友们如果需要可以微信扫描下方CSDN官方认证二维码免费领取【保证100%免费
】
![](https://i-blog.csdnimg.cn/blog_migrate/90882741f32fe6c367eda46f6cb8c5a5.png)