大家好,我是小F~
经常听到有朋侪说,学习编程是一件非常枯燥无味的事情。实在,大家有没有认真想过,可能是我们的学习方法不对?
比方说,你有没有想过,可以通过打游戏来学编程?
今天我想跟大家分享30个Python小游戏,教你如何通过边打游戏边学编程!
相干文件及代码都已上传,公众号复兴【游戏】即可获取。
接下来就一起来看看吧~
1、飞机大战
源码分享:
[code]import randomimport pygamefrom objects import Background, Player, Enemy, Bullet, Explosion, Fuel, \ Powerup, Button, Message, BlinkingTextpygame.init()SCREEN = WIDTH, HEIGHT = 288, 512info = pygame.display.Info()width = info.current_wheight = info.current_hif 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 = 1plane_destroy_count = 0plane_frequency = 5000start_time = pygame.time.get_ticks()moving_left = Falsemoving_right = Falsehome_page = Truegame_page = Falsescore_page = Falsescore = 0sound_on = Truerunning = Truewhile 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_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 = 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 x: move_right = False move_left = True move_fx.play() if move_left and prev_x = 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 = 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 = 0color = 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 imageshome_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")# Buttonshome_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 = 120rad_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 = Falsenum_clicks = 0player_alive = Truesound_on = Truescore = 0highscore = 0home_page = Truegame_page = Falsescore_page = Falserunning = Truewhile 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 portal.rect.top and player.rect.bottom 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 |