赞
踩
经常听到有朋友说,学习编程是一件非常枯燥无味的事情。其实,大家有没有认真想过,可能是我们的学习方法不对?
比方说,你有没有想过,可以通过打游戏来学编程?今天我想跟大家分享几个Python小游戏,教你如何通过边打游戏边学编程!
源码分享:
-
- import sys
- import cfg
- import pygame
- from modules import *
-
-
- '''定义按钮'''
- def Button(screen, position, text, button_size=(200, 50)):
- left, top = position
- bwidth, bheight = button_size
- pygame.draw.line(screen, (150, 150, 150), (left, top), (left+bwidth, top), 5)
- pygame.draw.line(screen, (150, 150, 150), (left, top-2), (left, top+bheight), 5)
- pygame.draw.line(screen, (50, 50, 50), (left, top+bheight), (left+bwidth, top+bheight), 5)
- pygame.draw.line(screen, (50, 50, 50), (left+bwidth, top+bheight), (left+bwidth, top), 5)
- pygame.draw.rect(screen, (100, 100, 100), (left, top, bwidth, bheight))
- font = pygame.font.Font(cfg.FONTPATH, 30)
- text_render = font.render(text, 1, (255, 235, 205))
- return screen.blit(text_render, (left+50, top+10))
-
-
- '''
- Function:
- 开始界面
- Input:
- --screen: 游戏界面
- Return:
- --game_mode: 1(单人模式)/2(双人模式)
- '''
- def startInterface(screen):
- clock = pygame.time.Clock()
- while True:
- screen.fill((41, 36, 33))
- button_1 = Button(screen, (150, 175), '1 Player')
- button_2 = Button(screen, (150, 275), '2 Player')
- for event in pygame.event.get():
- if event.type == pygame.QUIT:
- pygame.quit()
- sys.exit()
- if event.type == pygame.MOUSEBUTTONDOWN:
- if button_1.collidepoint(pygame.mouse.get_pos()):
- return 1
- elif button_2.collidepoint(pygame.mouse.get_pos()):
- return 2
- clock.tick(10)
- pygame.display.update()
-
-
- '''结束界面'''
- def endInterface(screen, score_left, score_right):
- clock = pygame.time.Clock()
- font1 = pygame.font.Font(cfg.FONTPATH, 30)
- font2 = pygame.font.Font(cfg.FONTPATH, 20)
- msg = 'Player on left won!' if score_left > score_right else 'Player on right won!'
- texts = [font1.render(msg, True, cfg.WHITE),
- font2.render('Press ESCAPE to quit.', True, cfg.WHITE),
- font2.render('Press ENTER to continue or play again.', True, cfg.WHITE)]
- positions = [[120, 200], [155, 270], [80, 300]]
- while True:
- screen.fill((41, 36, 33))
- for event in pygame.event.get():
- if event.type == pygame.QUIT:
- pygame.quit()
- sys.exit()
- if event.type == pygame.KEYDOWN:
- if event.key == pygame.K_RETURN:
- return
- elif event.key == pygame.K_ESCAPE:
- sys.exit()
- pygame.quit()
- for text, pos in zip(texts, positions):
- screen.blit(text, pos)
- clock.tick(10)
- pygame.display.update()
-
-
- '''运行游戏Demo'''
- def runDemo(screen):
- # 加载游戏素材
- hit_sound = pygame.mixer.Sound(cfg.HITSOUNDPATH)
- goal_sound = pygame.mixer.Sound(cfg.GOALSOUNDPATH)
- pygame.mixer.music.load(cfg.BGMPATH)
- pygame.mixer.music.play(-1, 0.0)
- font = pygame.font.Font(cfg.FONTPATH, 50)
- # 开始界面
- game_mode = startInterface(screen)
- # 游戏主循环
- # --左边球拍(ws控制, 仅双人模式

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。