一些简单好玩的Python编程游戏,Python好玩的代码

  一些简单好玩的Python编程游戏,Python好玩的代码

  今天小编跟大家分享13个有趣又好玩的计算机编程语言小游戏示例代码,教你如何通过边打游戏边学编程!感兴趣的小伙伴快跟随小编一起学习起来

  

目录
1、吃金币2、打乒乓3、滑雪4、并夕夕版飞机大战5、打地鼠6、小恐龙7、消消乐8、俄罗斯方块9、贪吃蛇10、24点小游戏11、平衡木12、外星人入侵13、井字棋888经常听到有朋友说,学习编程是一件非常枯燥无味的事情。其实,大家有没有认真想过,可能是我们的学习方法不对?

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

  今天我想跟大家分享几个计算机编程语言小游戏,教你如何通过边打游戏边学编程!

  

1、吃金币

  源码分享:

  导入操作系统

  导入稳频发电机(发生器)(constant frequency generator的缩写)

  导入系统

  导入简介及安装

  随机导入

  从模块导入*

  游戏初始化

  def initGame():

  # 初始化pygame,设置展示窗口

  pygame.init()

  屏幕=py游戏。展示。设置模式(CFG .屏幕尺寸)

  pygame.display.set_caption(抓硬币——九歌)

  # 加载必要的游戏素材

  game_images={}

  对于关键字,以稳频发电机(发生器)(constant frequency generator的缩写)表示的值IMAGE_PATHS.items():

  if isinstance(value,list):

  图像=[]

  对于值:中的项目图像。追加(py游戏。形象。负载(项目))

  game_images[key]=图像

  else:

  game _ images[key]=py game。形象。负载(值)

  game_sounds={}

  对于关键字,以稳频发电机(发生器)(constant frequency generator的缩写)表示的值. AUDIO _ path。物品():

  如果key==bgm:继续

  游戏_声音[键]=py游戏。搅拌机。声音(值)

  # 返回初始化数据

  返回屏幕,游戏图像,游戏声音

  主函数

  定义主():

  # 初始化

  screen,game_images,game_sounds=initGame()

  # 播放背景音乐

  pygame.mixer.music.load(cfg .音频路径[bgm])

  pygame.mixer.music.play(-1,0.0)

  # 字体加载

  font=pygame.font.Font(cfg .FONT_PATH,40)

  # 定义英雄

  hero=Hero(game_images[hero],position=(375,520))

  # 定义食物组

  food _ sprites _ group=py游戏。雪碧。群组()

  generate _ food _ freq=随机。randint(10,20)

  生成_食物_计数=0

  # 当前分数/历史最高分

  分数=0

  最高分=0如果不是操作系统路径存在(cfg .最高分数记录文件路径)else int(open(CFG .最高分记录文件路径)。read())

  # 游戏主循环

  clock=pygame.time.Clock()

  而True:

  # - 填充背景

  screen.fill(0)

  屏幕。blit(game _ images[ background ],(0,0))

  # - 倒计时信息

  倒计时_tex

  t = Count down: + str((90000 - pygame.time.get_ticks()) // 60000) + ":" + str((90000 - pygame.time.get_ticks()) // 1000 % 60).zfill(2)

   countdown_text = font.render(countdown_text, True, (0, 0, 0))

   countdown_rect = countdown_text.get_rect()

   countdown_rect.topright = [cfg.SCREENSIZE[0]-30, 5]

   screen.blit(countdown_text, countdown_rect)

   # --按键检测

   for event in pygame.event.get():

   if event.type == pygame.QUIT:

   pygame.quit()

   sys.exit()

   key_pressed = pygame.key.get_pressed()

   if key_pressed[pygame.K_a] or key_pressed[pygame.K_LEFT]:

   hero.move(cfg.SCREENSIZE, left)

   if key_pressed[pygame.K_d] or key_pressed[pygame.K_RIGHT]:

   hero.move(cfg.SCREENSIZE, right)

   # --随机生成食物

   generate_food_count += 1

   if generate_food_count > generate_food_freq:

   generate_food_freq = random.randint(10, 20)

   generate_food_count = 0

   food = Food(game_images, random.choice([gold,] * 10 + [apple]), cfg.SCREENSIZE)

   food_sprites_group.add(food)

   # --更新食物

   for food in food_sprites_group:

   if food.update(): food_sprites_group.remove(food)

   # --碰撞检测

   for food in food_sprites_group:

   if pygame.sprite.collide_mask(food, hero):

   game_sounds[get].play()

   food_sprites_group.remove(food)

   score += food.score

   if score > highest_score: highest_score = score

   # --画hero

   hero.draw(screen)

   # --画食物

   food_sprites_group.draw(screen)

   # --显示得分

   score_text = fScore: {score}, Highest: {highest_score}

   score_text = font.render(score_text, True, (0, 0, 0))

   score_rect = score_text.get_rect()

   score_rect.topleft = [5, 5]

   screen.blit(score_text, score_rect)

   # --判断游戏是否结束

   if pygame.time.get_ticks() >= 90000:

   break

   # --更新屏幕

   pygame.display.flip()

   clock.tick(cfg.FPS)

   # 游戏结束, 记录最高分并显示游戏结束画面

   fp = open(cfg.HIGHEST_SCORE_RECORD_FILEPATH, w)

   fp.write(str(highest_score))

   fp.close()

   return showEndGameInterface(screen, cfg, score, highest_score)

  run

  if __name__ == __main__:

   while main():

   pass

  

  

2、打乒乓

  

  源码分享:

  

 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控制, 仅双人模式时可控制)

   score_left = 0

   racket_left = Racket(cfg.RACKETPICPATH, LEFT, cfg)

   # --右边球拍(↑↓控制)

   score_right = 0

   racket_right = Racket(cfg.RACKETPICPATH, RIGHT, cfg)

   # --球

   ball = Ball(cfg.BALLPICPATH, cfg)

   clock = pygame.time.Clock()

   while True:

   for event in pygame.event.get():

   if event.type == pygame.QUIT:

   pygame.quit()

   sys.exit(-1)

   screen.fill((41, 36, 33))

   # 玩家操作

   pressed_keys = pygame.key.get_pressed()

   if pressed_keys[pygame.K_UP]:

   racket_right.move(UP)

   elif pressed_keys[pygame.K_DOWN]:

   racket_right.move(DOWN)

   if game_mode == 2:

   if pressed_keys[pygame.K_w]:

   racket_left.move(UP)

   elif pressed_keys[pygame.K_s]:

   racket_left.move(DOWN)

   else:

   racket_left.automove(ball)

   # 球运动

   scores = ball.move(ball, racket_left, racket_right, hit_sound, goal_sound)

   score_left += scores[0]

   score_right += scores[1]

   # 显示

   # --分隔线

   pygame.draw.rect(screen, cfg.WHITE, (247, 0, 6, 500))

   # --球

   ball.draw(screen)

   # --拍

   racket_left.draw(screen)

   racket_right.draw(screen)

   # --得分

   screen.blit(font.render(str(score_left), False, cfg.WHITE), (150, 10))

   screen.blit(font.render(str(score_right), False, cfg.WHITE), (300, 10))

   if score_left == 11 or score_right == 11:

   return score_left, score_right

   clock.tick(100)

   pygame.display.update()

  主函数

  def main():

   # 初始化

   pygame.init()

   pygame.mixer.init()

   screen = pygame.display.set_mode((cfg.WIDTH, cfg.HEIGHT))

   pygame.display.set_caption(pingpong —— 九歌)

   # 开始游戏

   while True:

   score_left, score_right = runDemo(screen)

   endInterface(screen, score_left, score_right)

  run

  if __name__ == __main__:

   main()

  

  

3、滑雪

  

  源码分享:

  

 import sys

  import cfg

  import pygame

  import random

  滑雪者类

  class SkierClass(pygame.sprite.Sprite):

   def __init__(self):

   pygame.sprite.Sprite.__init__(self)

   # 滑雪者的朝向(-2到2)

   self.direction = 0

   self.imagepaths = cfg.SKIER_IMAGE_PATHS[:-1]

   self.image = pygame.image.load(self.imagepaths[self.direction])

   self.rect = self.image.get_rect()

   self.rect.center = [320, 100]

   self.speed = [self.direction, 6-abs(self.direction)*2]

   改变滑雪者的朝向. 负数为向左,正数为向。

郑重声明:本文由网友发布,不代表盛行IT的观点,版权归原作者所有,仅为传播更多信息之目的,如有侵权请联系,我们将第一时间修改或删除,多谢。

留言与评论(共有 条评论)
   
验证码: