前端搭建打字通游戏(内附源码)

Posted 几何心凉

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了前端搭建打字通游戏(内附源码)相关的知识,希望对你有一定的参考价值。

The sand accumulates to form a pagoda


✨ 写在前面

上周我们实通过前端基础实现了名言生成器,当然很多伙伴再评论区提出了想法,后续我们会考虑实现的,今天还是继续按照我们原定的节奏来带领大家完成一个打字通的小游戏,功能也比较简单简单,也是想借助这样一个简单的功能,然后来帮助大家了解我们javascript在前端中的作用, 在前面的文章当中我们也提及到我们在本系列的专栏是循序渐进从简单到复杂的过程,后续会带领大家用前端实现猜数字、翻卡片、扫雷、贪吃蛇等有趣的小游戏,纯前端语言实现,都会陆续带给大家。欢迎大家订阅我们这份前端小游戏的专栏。


✨ 打字通功能介绍

我们中间白色区域就是我们文本域,用户可以在里面输入内容,我们点击开始按钮后我们下面的倒计时就会启动,这里我们是以60秒倒计时,与此同时上面的你准备好了吗?将变成我们的文案内容,我们需要照着文案内容再文本域中进行输入,倒计时结束后我们的我们上面将变成最终的得分,然后用户可以重新点击开始,又是同样的倒计时,当然我们可以自己规定规则,大家可以自己修改变成更棒的小游戏!下面我们就按照前面的思路先来实现一下吧!


✨ 页面搭建

创建文件

首先呢我们创建我们的html文件,这里我就直接命名为 打字通.html 了,大家可以随意命名, 文件创建生成后我们通过编辑器打开,这里我用的是VScode, 然后初始化我们的代码结构,那在这里告诉大家一个快捷键,就是我们敲上我们英文的一个 ! 我们敲击回车直接就会给我们生成基础版本的前端代码结构。

搭建DOM结构

我们现在就可以再body中对着我们的效果图开始搭建我们的DOM结构了,首先的话,我们可以看到我们肯定是有一个大的盒子,我们就先来定义这个盒子我们设置类名就为bigBox,然后我们上面的你准备好了吗?我们也放一个盒子我们设置类名为container,盒子的下面是一个文本域,这个文本域我们前端可以使用 textarea 标签,标签中有一些属性,在下面我们可以看到我们用到了几个属性,首先placeholder的作用是提示文字,我们可以看没有输入内容的时候看到开始输入…字样,我们style是设置样式这里我是通过resize:none来禁止我们文本域的拖拽,大家可以先不设置这个属性然后感受一下我们文本域的右下角是有一个三角是可以对文本域进行拖拽的,这里呢我们禁止拖拽,为了保护我们后续的布局,这是我们的文本域,再往下面就是我们的按钮跟倒计时的内容,这里我们的首先添加一个盒子类名叫做operate,然后盒子里面我们添加一个按钮跟一个类名叫做timer的div,就是下面这些代码,我们可以保存代码然后看一下页面。

<div class="bigBox">
  <div class="container">
    你准备好了吗?
  </div>
  <textarea name="" placeholder="开始输入..."
   id="" style="resize:none" cols="30" 
   rows="10"></textarea>
  <div class="operate">

    <button>开始</button>
    <div id="timer">60</div>
  </div>
</div>


✨ 样式代码

大盒子样式

上面的框架我们已经搭建出来了,其实在我们的开发过程中我们是肯定搭建一个DOM元素然后就开始编写样式的,但是这里为了方便给大家展示我们只能先搭建完所有的元素统一来配置样式,首先呢我们还是一样在我们的head中添加style标签,在里面编写我们的样式代码,老规矩先为我们的body设置上margin: 0; padding: 0;font-family: Arial, sans-serif;,内外边距都为0还有我们的字体;在我们的bigBox设置宽度50%,背景颜色,外边距上下为40px,然后水平居中,设置盒子模型为标准盒子,内边距为20px,边框圆角30px,然后盒子阴影,这个每个值什么意思我们再上篇文章中为大家讲解了,大家可以看一下;最后我们看一下效果

body 
  font-family: Arial, sans-serif;
  margin: 0;
  padding: 0;

.bigBox 
  width: 50%;
  background-color: #ac8c3e;
  margin: 40px auto;
  box-sizing: border-box;
  padding: 20px;
  border-radius: 30px;
  box-shadow: 0px 0px 30px 9px #939393;

盒子内部布局

为我们类名为container的盒子也就是上面的你准备好了吗?盒子设置居中,然后通过text-align: center;设置文字居中,内边距为20px,大家可以保存看一下效果;这里就不一一展示效果了,然后我们为中间的文本域,设置宽度100%,高度200px,外边距上下位20px左右为0,然后我们设置他的边框为none,不展示边框,下面就是文本域下面的区域,我们用了一个类名叫做operate的盒子来包裹按钮跟倒计时,我们为这个盒子设置宽度为20%,然后水平居中,字体居中,继续设置里面的botton按钮,字体大小24px,内边距上下为10px,左右为20px,背景颜色为 #007bff 字体颜色白色,边框设置为none不展示,圆角为5px,在通过cursor: pointer;鼠标悬浮为手状;最后在设置我们id为timer的倒计时,字体大小为48px,然后外边距上下左右都是20px;保存代码我们看一下效果;

.container 
  margin: 0 auto;
  text-align: center;
  padding: 20px;


textarea 
  width: 100%;
  height: 200px;
  margin: 20px 0;
  font-size: 20px;
  border: none;


.operate 
  width: 20%;
  margin: 0 auto;
  text-align: center;

    
button 
  font-size: 24px;
  padding: 10px 20px;
  background-color: #007bff;
  color: #fff;
  border: none;
  border-radius: 5px;
  cursor: pointer;


#timer 
  font-size: 48px;
  margin: 20px;


✨ 功能实现

那么代码写到这里呢,其实我们页面已经搭建完整了,但是我们的页面现在处于纯静态页面,也就是说仅仅用于展示, 现在还没有任何的效果,我们想要实现动态的一些交互效果就需要用到我们的JS来完成,下面呢我们就从几个方面来实现我们整体的效果;

获取所需元素和内容

首先呢我们知道点击开始之后,上面的你准备好了吗就要换成我们的范文,首先我们先声明变量来放我们的范文,我们声明变量text值就是我们的范文内容,这给大家找了一段英文的;我们还要通过document.querySelector先获取我们的元素后面会使用;然后我们先为我们的文本域设置内容为空;

  const text =
    "Believe in yourself and all that you are. Know that there is something inside you that is greater than any obstacle. This quote by Christian D. Larson reminds us that we all have the power within us to overcome any obstacle we may face. When we have confidence in ourselves and our abilities, we can achieve great things. So, let's trust ourselves, believe in our dreams, and work hard to make them a reality.";

  const container = document.querySelector(".container");
  const input = document.querySelector("textarea");
  const button = document.querySelector("button");
  const timer = document.getElementById("timer");
  input.value = "";

为按钮注册事件

通过addEventListener为按钮注册时间,我们在函数中首先把倒计时设置为60秒,然后清空我们输入框和范文的内容,然后我们调用startGame函数。

// 添加按钮点击事件监听器
button.addEventListener("click", () => 
  // 设置倒计时时间
  timer.textContent = "60";

  // 清空输入框和输出文本区域
  input.value = "";
  container.textContent = "";

  // 启动游戏
  startGame();
);

启动游戏

上面的代码我们是通过点击按钮然后来用到我们下面的startGame函数,我们在这个函数的前面的首先要声明一个变量countdown用来承接定时器的销毁,在函数中首先呢我们要将按钮禁用,倒计时期间不能重复点击,然后我们将范文展示再我们的container元素中,然后我们运用定时器setInterval,第一参数是一个函数,第二个参数是隔多少秒,下面的意思就是每秒执行一次函数,在函数中我们首先获取到倒计时现在的数值,第一次这里肯定为60,然后这里我们申明常量remainingTime来接受当前秒数-1,我们还有一个判断就是如果当前描述是0那么我们就执行endGame函数,然后我们对描述进行赋值就完成了我们的倒计时效果;下面呢我们继续写endGame函数。

  let countdown;

  function startGame () 
    // 游戏开始后,禁用按钮
    button.disabled = true;

    // 显示文本
    container.textContent = text;



    // 启动倒计时
    countdown = setInterval(() => 
      const remainingTime = parseInt(timer.textContent) - 1;
      if (remainingTime === 0) 
        // 时间用完,游戏结束
        endGame();
      

      timer.textContent = remainingTime;
    , 1000);
  

暂停游戏

endGame函数中我们首先就是停止倒计时,也就是销毁定时器,我们刚才说到了我们申明了一个变量用来承接定时器,这里的销魂我们就可以通过变量来;然后我们要计算得分,计算得分的函数呢我们下面讲解,首先这里你要知道计算得分的函数是调用后返回分数即可,然后我们将分数显示再范文区域,并且取消按钮的禁用;

function endGame () 
  // 停止倒计时
  clearInterval(countdown);

  // 计算得分
  const score = calculateScore();
  const scoreMessage = `你的得分是 $score 分!`;
  container.textContent = scoreMessage;

  // 显示按钮和计时器
  // button.style.display = "block";
  // timer.style.display = "block";
  button.disabled = false;

分数的计算

在上面我们结束游戏的函数中调用了计算分数的calculateScore 函数,在这个函数中我们需要按照规则生成分数并且返回,看下面首先我们将文本域、范文内容通过.trim()移除两端的空格,并且赋值给变量,然后我们通过split将所有内容按照空格进行拆分,然后我们进行循环每个单词进行一一对应如果相等则分数++,最后将分数return出去,调用的地方就可以直接拿到了。

function calculateScore () 
  const userText = input.value.trim();
  const correctText = text.trim();
  const userWords = userText.split(" ");
  const correctWords = correctText.split(" ");
  let score = 0;

  for (let i = 0; i < userWords.length; i++) 
    console.log(userWords[i], correctWords[i])
    if (userWords[i] === correctWords[i]) 
      score++;
    
  

  return score;

上面这些就是我们实现的整体思路跟代码,当然这里你完全可以按照自己的私聊来编写逻辑,上面也只是完成小小的功能,大家可以结合自己的想法编写,然后在这里呢有个小小的点,就是我是为了大家能够跟得上逻辑然后按照用户行为的先后顺序来介绍的,当然这样写也没有问题,但是还是建议大家函数要写在调用的前面,比如我们的启动游戏的函数是再按钮点击的时候调用的,那我们可以把启动游戏的函数代码写在点击事件的前面会更好以写;下面的完整代码也给到大家了哦!还有一点就是为了用户体验我们可以禁止用户复制,直接把范文复制到文本域好像不太好,我们可以再css代码的body中添以下代码;

body 
  font-family: Arial, sans-serif;
  margin: 0;
  padding: 0;
  -moz-user-select: none;
  /*火狐*/
  -webkit-user-select: none;
  /*webkit浏览器*/
  -ms-user-select: none;
  /*IE10*/
  -khtml-user-select: none;
  /*早期浏览器*/
  -o-user-select: none;
  user-select: none;

完整代码

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    body 
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 0;
      -moz-user-select: none;
      /*火狐*/
      -webkit-user-select: none;
      /*webkit浏览器*/
      -ms-user-select: none;
      /*IE10*/
      -khtml-user-select: none;
      /*早期浏览器*/
      -o-user-select: none;
      user-select: none;
    

    .bigBox 
      width: 50%;
      background-color: #ac8c3e;
      margin: 40px auto;
      box-sizing: border-box;
      padding: 20px;
      border-radius: 30px;
      box-shadow: 0px 0px 30px 9px #939393;
    

    .container 
      margin: 0 auto;
      text-align: center;
      padding: 20px;
    

    textarea 
      width: 100%;
      height: 200px;
      margin: 20px 0;
      font-size: 20px;
      border: none;
    

    .operate 
      width: 20%;
      margin: 0 auto;
      text-align: center;
    

    button 
      font-size: 24px;
      padding: 10px 20px;
      background-color: #007bff;
      color: #fff;
      border: none;
      border-radius: 5px;
      cursor: pointer;
    

    #timer 
      font-size: 48px;
      margin: 20px;
    
  </style>
</head>

<body>

  <div class="bigBox">
    <div class="container">
      你准备好了吗?
    </div>
    <textarea name="" placeholder="开始输入..." id="" style="resize:none" cols="30" rows="10"></textarea>
    <div class="operate">
      <button>开始</button>
      <div id="timer">60</div>
    </div>
  </div>


  <script>
    const text =
      "Believe in yourself and all that you are. Know that there is something inside you that is greater than any obstacle. This quote by Christian D. Larson reminds us that we all have the power within us to overcome any obstacle we may face. When we have confidence in ourselves and our abilities, we can achieve great things. So, let's trust ourselves, believe in our dreams, and work hard to make them a reality.";

    const container = document.querySelector(".container");
    const input = document.querySelector("textarea");
    const button = document.querySelector("button");
    const timer = document.getElementById("timer");
    input.value = "";



    let countdown;

    function startGame () 
      // 游戏开始后,禁用按钮
      button.disabled = true;

      // 显示文本
      container.textContent = text;


      // 启动倒计时
      countdown = setInterval(() => 
        const remainingTime = parseInt(timer.textContent) - 1;
        if (remainingTime === 0) 
          // 时间用完,游戏结束
          endGame();
        

        timer.textContent = remainingTime;
      , 1000);
    

    function endGame () 
      // 停止倒计时
      clearInterval(countdown);

      // 计算得分
      const score = calculateScore();
      const scoreMessage = `你的得分是 $score 分!`;
      container.textContent = scoreMessage;

      button.disabled = false;
    

    function calculateScore () 
      const userText = input.value.trim();
      const correctText = text.trim();
      const userWords = userText.split(" ");
      const correctWords = correctText.split(" ");
      let score = 0;

      for (let i = 0; i < userWords.length; i++) 
        console.log(userWords[i], correctWords[i])
        if (userWords[i] === correctWords[i]) 
          score++;
        
      

      return score;
    

    // 添加按钮点击事件监听器
    button.addEventListener("click", () => 
      // 设置倒计时时间
      timer.textContent = "60";

      // 清空输入框和输出文本区域
      input.value = "";
      container.textContent = "";

      // 启动游戏
      startGame();
    );

  </script>
</body>

</html>

本期推荐

原创不易,还希望各位大佬支持一下 \\textcolorblue原创不易,还希望各位大佬支持一下 原创不易,还希望各位大佬支持一下

👍 点赞,你的认可是我创作的动力! \\textcolorgreen点赞,你的认可是我创作的动力! 点赞,你的认可是我创作的动力!

⭐️ 收藏,你的青睐是我努力的方向! \\textcolorgreen收藏,你的青睐是我努力的方向! 收藏,你的青睐是我努力的方向!

✏️ 评论,你的意见是我进步的财富! \\textcolorgreen评论,你的意见是我进步的财富! 评论,你的意见是我进步的财富!

30个Python小游戏,上班摸鱼我能玩一天内附源码

大家好,我是辣条。

今天给大家带来30个py小游戏,一定要收藏!

目录

有手就行

1、吃金币

2、打乒乓

3、滑雪

4、并夕夕版飞机大战

5、打地鼠

简简单单

6、小恐龙

7、消消乐

8、俄罗斯方块

9、贪吃蛇

普普通通

10、24点小游戏

11、平衡木

12、外星人入侵

13、贪心鸟

14、井字棋888‘’

有点困难

15、炸弹人

16、保卫森林

17、五子棋

18、吃豆豆

19、坦克大战

20、超级玛丽

21、水果忍者

极度困难

22、飞机大战

23、2048

24、推箱子

25、塔防

26、植物大战僵尸

27、扫雷

终极挑战 

28、拼图

 29、走迷宫

30、最强游戏


有手就行

1、吃金币

【有手就行系列不介绍玩法了+附源码】

源码分享:
 

import os
import cfg
import sys
import pygame
import random
from modules import *


'''游戏初始化'''
def initGame():
    # 初始化pygame, 设置展示窗口
    pygame.init()
    screen = pygame.display.set_mode(cfg.SCREENSIZE)
    pygame.display.set_caption('catch coins —— 九歌')
    # 加载必要的游戏素材
    game_images = {}
    for key, value in cfg.IMAGE_PATHS.items():
        if isinstance(value, list):
            images = []
            for item in value: images.append(pygame.image.load(item))
            game_images[key] = images
        else:
            game_images[key] = pygame.image.load(value)
    game_sounds = {}
    for key, value in cfg.AUDIO_PATHS.items():
        if key == 'bgm': continue
        game_sounds[key] = pygame.mixer.Sound(value)
    # 返回初始化数据
    return screen, game_images, game_sounds


'''主函数'''
def main():
    # 初始化
    screen, game_images, game_sounds = initGame()
    # 播放背景音乐
    pygame.mixer.music.load(cfg.AUDIO_PATHS['bgm'])
    pygame.mixer.music.play(-1, 0.0)
    # 字体加载
    font = pygame.font.Font(cfg.FONT_PATH, 40)
    # 定义hero
    hero = Hero(game_images['hero'], position=(375, 520))
    # 定义食物组
    food_sprites_group = pygame.sprite.Group()
    generate_food_freq = random.randint(10, 20)
    generate_food_count = 0
    # 当前分数/历史最高分
    score = 0
    highest_score = 0 if not os.path.exists(cfg.HIGHEST_SCORE_RECORD_FILEPATH) else int(open(cfg.HIGHEST_SCORE_RECORD_FILEPATH).read())
    # 游戏主循环
    clock = pygame.time.Clock()
    while True:
        # --填充背景
        screen.fill(0)
        screen.blit(game_images['background'], (0, 0))
        # --倒计时信息
        countdown_text = '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 = f'Score: {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]
    '''改变滑雪者的朝向. 负数为向左,正数为向右,0为向前'''
    def turn(self, num):
        self.direction += num
        self.direction = max(-2, self.direction)
        self.direction = min(2, self.direction)
        center = self.rect.center
        self.image = pygame.image.load(self.imagepaths[self.direction])
        self.rect = self.image.get_rect()
        self.rect.center = center
        self.speed = [self.direction, 6-abs(self.direction)*2]
        return self.speed
    '''移动滑雪者'''
    def move(self):
        self.rect.centerx += self.speed[0]
        self.rect.centerx = max(20, self.rect.centerx)
        self.rect.centerx = min(620, self.rect.centerx)
    '''设置为摔倒状态'''
    def setFall(self):
        self.image = pygame.image.load(cfg.SKIER_IMAGE_PATHS[-1])
    '''设置为站立状态'''
    def setForward(self):
        self.direction = 0
        self.image = pygame.image.load(self.imagepaths[self.direction])


'''
Function:
    障碍物类
Input:
    img_path: 障碍物图片路径
    location: 障碍物位置
    attribute: 障碍物类别属性
'''
class ObstacleClass(pygame.sprite.Sprite):
    def __init__(self, img_path, location, attribute):
        pygame.sprite.Sprite.__init__(self)
        self.img_path = img_path
        self.image = pygame.image.load(self.img_path)
        self.location = location
        self.rect = self.image.get_rect()
        self.rect.center = self.location
        self.attribute = attribute
        self.passed = False
    '''移动'''
    def move(self, num):
        self.rect.centery = self.location[1] - num


'''创建障碍物'''
def createObstacles(s, e, num=10):
    obstacles = pygame.sprite.Group()
    locations = []
    for i in range(num):
        row = random.randint(s, e)
        col = random.randint(0, 9)
        location  = [col*64+20, row*64+20]
        if location not in locations:
            locations.append(location)
            attribute = random.choice(list(cfg.OBSTACLE_PATHS.keys()))
            img_path = cfg.OBSTACLE_PATHS[attribute]
            obstacle = ObstacleClass(img_path, location, attribute)
            obstacles.add(obstacle)
    return obstacles


'''合并障碍物'''
def AddObstacles(obstacles0, obstacles1):
    obstacles = pygame.sprite.Group()
    for obstacle in obstacles0:
        obstacles.add(obstacle)
    for obstacle in obstacles1:
        obstacles.add(obstacle)
    return obstacles


'''显示游戏开始界面'''
def ShowStartInterface(screen, screensize):
    screen.fill((255, 255, 255))
    tfont = pygame.font.Font(cfg.FONTPATH, screensize[0]//5)
    cfont = pygame.font.Font(cfg.FONTPATH, screensize[0]//20)
    title = tfont.render(u'滑雪游戏', True, (255, 0, 0))
    content = cfont.render(u'按任意键开始游戏', True, (0, 0, 255))
    trect = title.get_rect()
    trect.midtop = (screensize[0]/2, screensize[1]/5)
    crect = content.get_rect()
    crect.midtop = (screensize[0]/2, screensize[1]/2)
    screen.blit(title, trect)
    screen.blit(content, crect)
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                return
        pygame.display.update()


'''显示分数'''
def showScore(screen, score, pos=(10, 10)):
    font = pygame.font.Font(cfg.FONTPATH, 30)
    score_text = font.render("Score: %s" % score, True, (0, 0, 0))
    screen.blit(score_text, pos)


'''更新当前帧的游戏画面'''
def updateFrame(screen, obstacles, skier, score):
    screen.fill((255, 255, 255))
    obstacles.draw(screen)
    screen.blit(skier.image, skier.rect)
    showScore(screen, score)
    pygame.display.update()


'''主程序'''
def main():
    # 游戏初始化
    pygame.init()
    pygame.mixer.init()
    pygame.mixer.music.load(cfg.BGMPATH)
    pygame.mixer.music.set_volume(0.4)
    pygame.mixer.music.play(-1)
    # 设置屏幕
    screen = pygame.display.set_mode(cfg.SCREENSIZE)
    pygame.display.set_caption('滑雪游戏 —— 九歌')
    # 游戏开始界面
    ShowStartInterface(screen, cfg.SCREENSIZE)
    # 实例化游戏精灵
    # --滑雪者
    skier = SkierClass()
    # --创建障碍物
    obstacles0 = createObstacles(20, 29)
    obstacles1 = createObstacles(10, 19)
    obstaclesflag = 0
    obstacles = AddObstacles(obstacles0, obstacles1)
    # 游戏clock
    clock = pygame.time.Clock()
    # 记录滑雪的距离
    distance = 0
    # 记录当前的分数
    score = 0
    # 记录当前的速度
    speed = [0, 6]
    # 游戏主循环
    while True:
        # --事件捕获
        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_LEFT or event.key == pygame.K_a:
                    speed = skier.turn(-1)
                elif event.key == pygame.K_RIGHT or event.key == pygame.K_d:
                    speed = skier.turn(1)
        # --更新当前游戏帧的数据
        skier.move()
        distance += speed[1]
        if distance >= 640 and obstaclesflag == 0:
            obstaclesflag = 1
            obstacles0 = createObstacles(20, 29)
            obstacles = AddObstacles(obstacles0, obstacles1)
        if distance >= 1280 and obstaclesflag == 1:
            obstaclesflag = 0
            distance -= 1280
            for obstacle in obstacles0:
                obstacle.location[1] = obstacle.location[1] - 1280
            obstacles1 = createObstacles(10, 19)
            obstacles = AddObstacles(obstacles0, obstacles1)
        for obstacle in obstacles:
            obstacle.move(distance)
        # --碰撞检测
        hitted_obstacles = pygame.sprite.spritecollide(skier, obstacles, False)
        if hitted_obstacles:
            if hitted_obstacles[0].attribute == "tree" and not hitted_obstacles[0].passed:
                score -= 50
                skier.setFall()
                updateFrame(screen, obstacles, skier, score)
                pygame.time.delay(1000)
                skier.setForward()
                speed = [0, 6]
                hitted_obstacles[0].passed = True
            elif hitted_obstacles[0].attribute == "flag" and not hitted_obstacles[0].passed:
                score += 10
                obstacles.remove(hitted_obstacles[0])
        # --更新屏幕
        updateFrame(screen, obstacles, skier, score)
        clock.tick(cfg.FPS)


'''run'''
if __name__ == '__main__':
    main();

4、并夕夕版飞机大战

源码分享:


import sys
import cfg
import pygame
from modules import *


'''游戏界面'''
def GamingInterface(num_player, screen):
    # 初始化
    pygame.mixer.music.load(cfg.SOUNDPATHS['Cool Space Music'])
    pygame.mixer.music.set_volume(0.4)
    pygame.mixer.music.play(-1)
    explosion_sound = pygame.mixer.Sound(cfg.SOUNDPATHS['boom'])
    fire_sound = pygame.mixer.Sound(cfg.SOUNDPATHS['shot'])
    font = pygame.font.Font(cfg.FONTPATH, 20)
    # 游戏背景图
    bg_imgs = [cfg.IMAGEPATHS['bg_big'], cfg.IMAGEPATHS['seamless_space'], cfg.IMAGEPATHS['space3']]
    bg_move_dis = 0
    bg_1 = pygame.image.load(bg_imgs[0]).convert()
    bg_2 = pygame.image.load(bg_imgs[1]).convert()
    bg_3 = pygame.image.load(bg_imgs[2]).convert()
    # 玩家, 子弹和小行星精灵组
    player_group = pygame.sprite.Group()
    bullet_group = pygame.sprite.Group()
    asteroid_group = pygame.sprite.Group()
    # 产生小行星的时间间隔
    asteroid_ticks = 90
    for i in range(num_player):
        player_group.add(Ship(i+1, cfg))
    clock = pygame.time.Clock()
    # 分数
    score_1, score_2 = 0, 0
    # 游戏主循环
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
        # --玩家一: ↑↓←→控制, j射击; 玩家二: wsad控制, 空格射击
        pressed_keys = pygame.key.get_pressed()
        for idx, player in enumerate(player_group):
            direction = None
            if idx == 0:
                if pressed_keys[pygame.K_UP]:
                    direction = 'up'
                elif pressed_keys[pygame.K_DOWN]:
                    direction = 'down'
                elif pressed_keys[pygame.K_LEFT]:
                    direction = 'left'
                elif pressed_keys[pygame.K_RIGHT]:
                    direction = 'right'
                if direction:
                    player.move(direction)
                if pressed_keys[pygame.K_j]:
                    if player.cooling_time == 0:
                        fire_sound.play()
                        bullet_group.add(player.shot())
                        player.cooling_time = 20
            elif idx == 1:
                if pressed_keys[pygame.K_w]:
                    direction = 'up'
                elif pressed_keys[pygame.K_s]:
                    direction = 'down'
                elif pressed_keys[pygame.K_a]:
                    direction = 'left'
                elif pressed_keys[pygame.K_d]:
                    direction = 'right'
                if direction:
                    player.move(direction)
                if pressed_keys[pygame.K_SPACE]:
                    if player.cooling_time == 0:
                        fire_sound.play()
                        bullet_group.add(player.shot())
                        player.cooling_time = 20
            if player.cooling_time > 0:
                player.cooling_time -= 1
        if (score_1 + score_2) < 500:
            background = bg_1
        elif (score_1 + score_2) < 1500:
            background = bg_2
        else:
            background = bg_3
        # --向下移动背景图实现飞船向上移动的效果
        screen.blit(background, (0, -background.get_rect().height + bg_move_dis))
        screen.blit(background, (0, bg_move_dis))
        bg_move_dis = (bg_move_dis + 2) % background.get_rect().height
        # --生成小行星
        if asteroid_ticks == 0:
            asteroid_ticks = 90
            asteroid_group.add(Asteroid(cfg))
        else:
            asteroid_ticks -= 1
        # --画飞船
        for player in player_group:
            if pygame.sprite.spritecollide(player, asteroid_group, True, None):
                player.explode_step = 1
                explosion_sound.play()
            elif player.explode_step > 0:
                if player.explode_step > 3:
                    player_group.remove(player)
                    if len(player_group) == 0:
                        return
                else:
                    player.explode(screen)
            else:
                player.draw(screen)
        # --画子弹
        for bullet in bullet_group:
            bullet.move()
            if pygame.sprite.spritecollide(bullet, asteroid_group, True, None):
                bullet_group.remove(bullet)
                if bullet.player_idx == 1:
                    score_1 += 1
                else:
                    score_2 += 1
            else:
                bullet.draw(screen)
        # --画小行星
        for asteroid in asteroid_group:
            asteroid.move()
            asteroid.rotate()
            asteroid.draw(screen)
        # --显示分数
        score_1_text = '玩家一得分: %s' % score_1
        score_2_text = '玩家二得分: %s' % score_2
        text_1 = font.render(score_1_text, True, (0, 0, 255))
        text_2 = font.render(score_2_text, True, (255, 0, 0))
        screen.blit(text_1, (2, 5))
        screen.blit(text_2, (2, 35))
        # --屏幕刷新
        pygame.display.update()
        clock.tick(60)


'''主函数'''
def main():
    pygame.init()
    pygame.font.init()
    pygame.mixer.init()
    screen = pygame.display.set_mode(cfg.SCREENSIZE)
    pygame.display.set_caption('飞机大战 —— 九歌')
    num_player = StartInterface(screen, cfg)
    if num_player == 1:
        while True:
            GamingInterface(num_player=1, screen=screen)
            EndInterface(screen, cfg)
    else:
        while True:
            GamingInterface(num_player=2, screen=screen)
            EndInterface(screen, cfg)


'''run'''
if __name__ == '__main__':
    main()

5、打地鼠

源码分享:


import cfg
import sys
import pygame
import random
from modules import *


'''游戏初始化'''
def initGame():
    pygame.init()
    pygame.mixer.init()
    screen = pygame.display.set_mode(cfg.SCREENSIZE)
    pygame.display.set_caption('打地鼠 —— 九歌')
    return screen


'''主函数'''
def main():
    # 初始化
    screen = initGame()
    # 加载背景音乐和其他音效
    pygame.mixer.music.load(cfg.BGM_PATH)
    pygame.mixer.music.play(-1)
    audios = {
        'count_down': pygame.mixer.Sound(cfg.COUNT_DOWN_SOUND_PATH),
        'hammering': pygame.mixer.Sound(cfg.HAMMERING_SOUND_PATH)
    }
    # 加载字体
    font = pygame.font.Font(cfg.FONT_PATH, 40)
    # 加载背景图片
    bg_img = pygame.image.load(cfg.GAME_BG_IMAGEPATH)
    # 开始界面
    startInterface(screen, cfg.GAME_BEGIN_IMAGEPATHS)
    # 地鼠改变位置的计时
    hole_pos = random.choice(cfg.HOLE_POSITIONS)
    change_hole_event = pygame.USEREVENT
    pygame.time.set_timer(change_hole_event, 800)
    # 地鼠
    mole = Mole(cfg.MOLE_IMAGEPATHS, hole_pos)
    # 锤子
    hammer = Hammer(cfg.HAMMER_IMAGEPATHS, (500, 250))
    # 时钟
    clock = pygame.time.Clock()
    # 分数
    your_score = 0
    flag = False
    # 初始时间
    init_time = pygame.time.get_ticks()
    # 游戏主循环
    while True:
        # --游戏时间为60s
        time_remain = round((61000 - (pygame.time.get_ticks() - init_time)) / 1000.)
        # --游戏时间减少, 地鼠变位置速度变快
        if time_remain == 40 and not flag:
            hole_pos = random.choice(cfg.HOLE_POSITIONS)
            mole.reset()
            mole.setPosition(hole_pos)
            pygame.time.set_timer(change_hole_event, 650)
            flag = True
        elif time_remain == 20 and flag:
            hole_pos = random.choice(cfg.HOLE_POSITIONS)
            mole.reset()
            mole.setPosition(hole_pos)
            pygame.time.set_timer(change_hole_event, 500)
            flag = False
        # --倒计时音效
        if time_remain == 10:
            audios['count_down'].play()
        # --游戏结束
        if time_remain < 0: break
        count_down_text = font.render('Time: '+str(time_remain), True, cfg.WHITE)
        # --按键检测
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.MOUSEMOTION:
                hammer.setPosition(pygame.mouse.get_pos())
            elif event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:
                    hammer.setHammering()
            elif event.type == change_hole_event:
                hole_pos = random.choice(cfg.HOLE_POSITIONS)
                mole.reset()
                mole.setPosition(hole_pos)
        # --碰撞检测
        if hammer.is_hammering and not mole.is_hammer:
            is_hammer = pygame.sprite.collide_mask(hammer, mole)
            if is_hammer:
                audios['hammering'].play()
                mole.setBeHammered()
                your_score += 10
        # --分数
        your_score_text = font.render('Score: '+str(your_score), True, cfg.BROWN)
        # --绑定必要的游戏元素到屏幕(注意顺序)
        screen.blit(bg_img, (0, 0))
        screen.blit(count_down_text, (875, 8))
        screen.blit(your_score_text, (800, 430))
        mole.draw(screen)
        hammer.draw(screen)
        # --更新
        pygame.display.flip()
        clock.tick(60)
    # 读取最佳分数(try块避免第一次游戏无.rec文件)
    try:
        best_score = int(open(cfg.RECORD_PATH).read())
    except:
        best_score = 0
    # 若当前分数大于最佳分数则更新最佳分数
    if your_score > best_score:
        f = open(cfg.RECORD_PATH, 'w')
        f.write(str(your_score))
        f.close()
    # 结束界面
    score_info = {'your_score': your_score, 'best_score': best_score}
    is_restart = endInterface(screen, cfg.GAME_END_IMAGEPATH, cfg.GAME_AGAIN_IMAGEPATHS, score_info, cfg.FONT_PATH, [cfg.WHITE, cfg.RED], cfg.SCREENSIZE)
    return is_restart


'''run'''
if __name__ == '__main__':
    while True:
        is_restart = main()
        if not is_restart:
            break

简简单单

【简单介绍一下玩法+附源码】

6、小恐龙

玩法:上下控制起跳躲避

源码分享:


import cfg
import sys
import random
import pygame
from modules import *


'''main'''
def main(highest_score):
    # 游戏初始化
    pygame.init()
    screen = pygame.display.set_mode(cfg.SCREENSIZE)
    pygame.display.set_caption('九歌')
    # 导入所有声音文件
    sounds = {}
    for key, value in cfg.AUDIO_PATHS.items():
        sounds[key] = pygame.mixer.Sound(value)
    # 游戏开始界面
    GameStartInterface(screen, sounds, cfg)
    # 定义一些游戏中必要的元素和变量
    score = 0
    score_board = Scoreboard(cfg.IMAGE_PATHS['numbers'], position=(534, 15), bg_color=cfg.BACKGROUND_COLOR)
    highest_score = highest_score
    highest_score_board = Scoreboard(cfg.IMAGE_PATHS['numbers'], position=(435, 15), bg_color=cfg.BACKGROUND_COLOR, is_highest=True)
    dino = Dinosaur(cfg.IMAGE_PATHS['dino'])
    ground = Ground(cfg.IMAGE_PATHS['ground'], position=(0, cfg.SCREENSIZE[1]))
    cloud_sprites_group = pygame.sprite.Group()
    cactus_sprites_group = pygame.sprite.Group()
    ptera_sprites_group = pygame.sprite.Group()
    add_obstacle_timer = 0
    score_timer = 0
    # 游戏主循环
    clock = pygame.time.Clock()
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE or event.key == pygame.K_UP:
                    dino.jump(sounds)
                elif event.key == pygame.K_DOWN:
                    dino.duck()
            elif event.type == pygame.KEYUP and event.key == pygame.K_DOWN:
                dino.unduck()
        screen.fill(cfg.BACKGROUND_COLOR)
        # --随机添加云
        if len(cloud_sprites_group) < 5 and random.randrange(0, 300) == 10:
            cloud_sprites_group.add(Cloud(cfg.IMAGE_PATHS['cloud'], position=(cfg.SCREENSIZE[0], random.randrange(30, 75))))
        # --随机添加仙人掌/飞龙
        add_obstacle_timer += 1
        if add_obstacle_timer > random.randrange(50, 150):
            add_obstacle_timer = 0
            random_value = random.randrange(0, 10)
            if random_value >= 5 and random_value <= 7:
                cactus_sprites_group.add(Cactus(cfg.IMAGE_PATHS['cacti']))
            else:
                position_ys = [cfg.SCREENSIZE[1]*0.82, cfg.SCREENSIZE[1]*0.75, cfg.SCREENSIZE[1]*0.60, cfg.SCREENSIZE[1]*0.20]
                ptera_sprites_group.add(Ptera(cfg.IMAGE_PATHS['ptera'], position=(600, random.choice(position_ys))))
        # --更新游戏元素
        dino.update()
        ground.update()
        cloud_sprites_group.update()
        cactus_sprites_group.update()
        ptera_sprites_group.update()
        score_timer += 1
        if score_timer > (cfg.FPS//12):
            score_timer = 0
            score += 1
            score = min(score, 99999)
            if score > highest_score:
                highest_score = score
            if score % 100 == 0:
                sounds['point'].play()
            if score % 1000 == 0:
                ground.speed -= 1
                for item in cloud_sprites_group:
                    item.speed -= 1
                for item in cactus_sprites_group:
                    item.speed -= 1
                for item in ptera_sprites_group:
                    item.speed -= 1
        # --碰撞检测
        for item in cactus_sprites_group:
            if pygame.sprite.collide_mask(dino, item):
                dino.die(sounds)
        for item in ptera_sprites_group:
            if pygame.sprite.collide_mask(dino, item):
                dino.die(sounds)
        # --将游戏元素画到屏幕上
        dino.draw(screen)
        ground.draw(screen)
        cloud_sprites_group.draw(screen)
        cactus_sprites_group.draw(screen)
        ptera_sprites_group.draw(screen)
        score_board.set(score)
        highest_score_board.set(highest_score)
        score_board.draw(screen)
        highest_score_board.draw(screen)
        # --更新屏幕
        pygame.display.update()
        clock.tick(cfg.FPS)
        # --游戏是否结束
        if dino.is_dead:
            break
    # 游戏结束界面
    return GameEndInterface(screen, cfg), highest_score


'''run'''
if __name__ == '__main__':
    highest_score = 0
    while True:
        flag, highest_score = main(highest_score)
        if not flag: break

7、消消乐

玩法:三个相连就能消除

源码分享:


import os
import sys
import cfg
import pygame
from modules import *


'''游戏主程序'''
def main():
    pygame.init()
    screen = pygame.display.set_mode(cfg.SCREENSIZE)
    pygame.display.set_caption('Gemgem —— 九歌')
    # 加载背景音乐
    pygame.mixer.init()
    pygame.mixer.music.load(os.path.join(cfg.ROOTDIR, "resources/audios/bg.mp3"))
    pygame.mixer.music.set_volume(0.6)
    pygame.mixer.music.play(-1)
    # 加载音效
    sounds = {}
    sounds['mismatch'] = pygame.mixer.Sound(os.path.join(cfg.ROOTDIR, 'resources/audios/badswap.wav'))
    sounds['match'] = []
    for i in range(6):
        sounds['match'].append(pygame.mixer.Sound(os.path.join(cfg.ROOTDIR, 'resources/audios/match%s.wav' % i)))
    # 加载字体
    font = pygame.font.Font(os.path.join(cfg.ROOTDIR, 'resources/font/font.TTF'), 25)
    # 图片加载
    gem_imgs = []
    for i in range(1, 8):
        gem_imgs.append(os.path.join(cfg.ROOTDIR, 'resources/images/gem%s.png' % i))
    # 主循环
    game = gemGame(screen, sounds, font, gem_imgs, cfg)
    while True:
        score = game.start()
        flag = False
        # 一轮游戏结束后玩家选择重玩或者退出
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT or (event.type == pygame.KEYUP and event.key == pygame.K_ESCAPE):
                    pygame.quit()
                    sys.exit()
                elif event.type == pygame.KEYUP and event.key == pygame.K_r:
                    flag = True
            if flag:
                break
            screen.fill((135, 206, 235))
            text0 = 'Final score: %s' % score
            text1 = 'Press <R> to restart the game.'
            text2 = 'Press <Esc> to quit the game.'
            y = 150
            for idx, text in enumerate([text0, text1, text2]):
                text_render = font.render(text, 1, (85, 65, 0))
                rect = text_render.get_rect()
                if idx == 0:
                    rect.left, rect.top = (212, y)
                elif idx == 1:
                    rect.left, rect.top = (122.5, y)
                else:
                    rect.left, rect.top = (126.5, y)
                y += 100
                screen.blit(text_render, rect)
            pygame.display.update()
        game.reset()


'''run'''
if __name__ == '__main__':
    main()

8、俄罗斯方块

玩法:童年经典,普通模式没啥意思,小时候我们都是玩加速的。

源码分享:


import os
import sys
import random
from modules import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *


'''定义俄罗斯方块游戏类'''
class TetrisGame(QMainWindow):
    def __init__(self, parent=None):
        super(TetrisGame, self).__init__(parent)
        # 是否暂停ing
        self.is_paused = False
        # 是否开始ing
        self.is_started = False
        self.initUI()
    '''界面初始化'''
    def initUI(self):
        # icon
        self.setWindowIcon(QIcon(os.path.join(os.getcwd(), 'resources/icon.jpg')))
        # 块大小
        self.grid_size = 22
        # 游戏帧率
        self.fps = 200
        self.timer = QBasicTimer()
        # 焦点
        self.setFocusPolicy(Qt.StrongFocus)
        # 水平布局
        layout_horizontal = QHBoxLayout()
        self.inner_board = InnerBoard()
        self.external_board = ExternalBoard(self, self.grid_size, self.inner_board)
        layout_horizontal.addWidget(self.external_board)
        self.side_panel = SidePanel(self, self.grid_size, self.inner_board)
        layout_horizontal.addWidget(self.side_panel)
        self.status_bar = self.statusBar()
        self.external_board.score_signal[str].connect(self.status_bar.showMessage)
        self.start()
        self.center()
        self.setWindowTitle('Tetris —— 九歌')
        self.show()
        self.setFixedSize(self.external_board.width() + self.side_panel.width(), self.side_panel.height() + self.status_bar.height())
    '''游戏界面移动到屏幕中间'''
    def center(self):
        screen = QDesktopWidget().screenGeometry()
        size = self.geometry()
        self.move((screen.width() - size.width()) // 2, (screen.height() - size.height()) // 2)
    '''更新界面'''
    def updateWindow(self):
        self.external_board.updateData()
        self.side_panel.updateData()
        self.update()
    '''开始'''
    def start(self):
        if self.is_started:
            return
        self.is_started = True
        self.inner_board.createNewTetris()
        self.timer.start(self.fps, self)
    '''暂停/不暂停'''
    def pause(self):
        if not self.is_started:
            return
        self.is_paused = not self.is_paused
        if self.is_paused:
            self.timer.stop()
            self.external_board.score_signal.emit('Paused')
        else:
            self.timer.start(self.fps, self)
        self.updateWindow()
    '''计时器事件'''
    def timerEvent(self, event):
        if event.timerId() == self.timer.timerId():
            removed_lines = self.inner_board.moveDown()
            self.external_board.score += removed_lines
            self.updateWindow()
        else:
            super(TetrisGame, self).timerEvent(event)
    '''按键事件'''
    def keyPressEvent(self, event):
        if not self.is_started or self.inner_board.current_tetris == tetrisShape().shape_empty:
            super(TetrisGame, self).keyPressEvent(event)
            return
        key = event.key()
        # P键暂停
        if key == Qt.Key_P:
            self.pause()
            return
        if self.is_paused:
            return
        # 向左
        elif key == Qt.Key_Left:
            self.inner_board.moveLeft()
        # 向右
        elif key == Qt.Key_Right:
            self.inner_board.moveRight()
        # 旋转
        elif key == Qt.Key_Up:
            self.inner_board.rotateAnticlockwise()
        # 快速坠落
        elif key == Qt.Key_Space:
            self.external_board.score += self.inner_board.dropDown()
        else:
            super(TetrisGame, self).keyPressEvent(event)
        self.updateWindow()


'''run'''
if __name__ == '__main__':
    app = QApplication([])
    tetris = TetrisGame()
    sys.exit(app.exec_())

9、贪吃蛇

玩法:童年经典,普通魔术也没啥意思,小时候玩的也是加速的。

源码分享:


import cfg
import sys
import pygame
from modules import *


'''主函数'''
def main(cfg):
    # 游戏初始化
    pygame.init()
    screen = pygame.display.set_mode(cfg.SCREENSIZE)
    pygame.display.set_caption('Greedy Snake —— 九歌')
    clock = pygame.time.Clock()
    # 播放背景音乐
    pygame.mixer.music.load(cfg.BGMPATH)
    pygame.mixer.music.play(-1)
    # 游戏主循环
    snake = Snake(cfg)
    apple = Apple(cfg, snake.coords)
    score = 0
    while True:
        screen.fill(cfg.BLACK)
        # --按键检测
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key in [pygame.K_UP, pygame.K_DOWN, pygame.K_LEFT, pygame.K_RIGHT]:
                    snake.setDirection({pygame.K_UP: 'up', pygame.K_DOWN: 'down', pygame.K_LEFT: 'left', pygame.K_RIGHT: 'right'}[event.key])
        # --更新贪吃蛇和食物
        if snake.update(apple):
            apple = Apple(cfg, snake.coords)
            score += 1
        # --判断游戏是否结束
        if snake.isgameover: break
        # --显示游戏里必要的元素
        drawGameGrid(cfg, screen)
        snake.draw(screen)
        apple.draw(screen)
        showScore(cfg, score, screen)
        # --屏幕更新
        pygame.display.update()
        clock.tick(cfg.FPS)
    return endInterface(screen, cfg)


'''run'''
if __name__ == '__main__':
    while True:
        if not main(cfg):
            break

普普通通

【玩法详细介绍+源码】

10、24点小游戏

玩法:通过加减乘除操作,小学生都没问题的。

源码分享:


import os
import sys
import pygame
from cfg import *
from modules import *
from fractions import Fraction


'''检查控件是否被点击'''
def checkClicked(group, mouse_pos, group_type='NUMBER'):
    selected = []
    # 数字卡片/运算符卡片
    if group_type == GROUPTYPES[0] or group_type == GROUPTYPES[1]:
        max_selected = 2 if group_type == GROUPTYPES[0] else 1
        num_selected = 0
        for each in group:
            num_selected += int(each.is_selected)
        for each in group:
            if each.rect.collidepoint(mouse_pos):
                if each.is_selected:
                    each.is_selected = not each.is_selected
                    num_selected -= 1
                    each.select_order = None
                else:
                    if num_selected < max_selected:
                        each.is_selected = not each.is_selected
                        num_selected += 1
                        each.select_order = str(num_selected)
            if each.is_selected:
                selected.append(each.attribute)
    # 按钮卡片
    elif group_type == GROUPTYPES[2]:
        for each in group:
            if each.rect.collidepoint(mouse_pos):
                each.is_selected = True
                selected.append(each.attribute)
    # 抛出异常
    else:
        raise ValueError('checkClicked.group_type unsupport %s, expect %s, %s or %s...' % (group_type, *GROUPTYPES))
    return selected


'''获取数字精灵组'''
def getNumberSpritesGroup(numbers):
    number_sprites_group = pygame.sprite.Group()
    for idx, number in enumerate(numbers):
        args = (*NUMBERCARD_POSITIONS[idx], str(number), NUMBERFONT, NUMBERFONT_COLORS, NUMBERCARD_COLORS, str(number))
        number_sprites_group.add(Card(*args))
    return number_sprites_group


'''获取运算符精灵组'''
def getOperatorSpritesGroup(operators):
    operator_sprites_group = pygame.sprite.Group()
    for idx, operator in enumerate(operators):
        args = (*OPERATORCARD_POSITIONS[idx], str(operator), OPERATORFONT, OPREATORFONT_COLORS, OPERATORCARD_COLORS, str(operator))
        operator_sprites_group.add(Card(*args))
    return operator_sprites_group


'''获取按钮精灵组'''
def getButtonSpritesGroup(buttons):
    button_sprites_group = pygame.sprite.Group()
    for idx, button in enumerate(buttons):
        args = (*BUTTONCARD_POSITIONS[idx], str(button), BUTTONFONT, BUTTONFONT_COLORS, BUTTONCARD_COLORS, str(button))
        button_sprites_group.add(Button(*args))
    return button_sprites_group


'''计算'''
def calculate(number1, number2, operator):
    operator_map = {'+': '+', '-': '-', '×': '*', '÷': '/'}
    try:
        result = str(eval(number1+operator_map[operator]+number2))
        return result if '.' not in result else str(Fraction(number1+operator_map[operator]+number2))
    except:
        return None


'''在屏幕上显示信息'''
def showInfo(text, screen):
    rect = pygame.Rect(200, 180, 400, 200)
    pygame.draw.rect(screen, PAPAYAWHIP, rect)
    font = pygame.font.Font(FONTPATH, 40)
    text_render = font.render(text, True, BLACK)
    font_size = font.size(text)
    screen.blit(text_render, (rect.x+(rect.width-font_size[0])/2, rect.y+(rect.height-font_size[1])/2))


'''主函数'''
def main():
    # 初始化, 导入必要的游戏素材
    pygame.init()
    pygame.mixer.init()
    screen = pygame.display.set_mode(SCREENSIZE)
    pygame.display.set_caption('24 point —— 九歌')
    win_sound = pygame.mixer.Sound(AUDIOWINPATH)
    lose_sound = pygame.mixer.Sound(AUDIOLOSEPATH)
    warn_sound = pygame.mixer.Sound(AUDIOWARNPATH)
    pygame.mixer.music.load(BGMPATH)
    pygame.mixer.music.play(-1, 0.0)
    # 24点游戏生成器
    game24_gen = game24Generator()
    game24_gen.generate()
    # 精灵组
    # --数字
    number_sprites_group = getNumberSpritesGroup(game24_gen.numbers_now)
    # --运算符
    operator_sprites_group = getOperatorSpritesGroup(OPREATORS)
    # --按钮
    button_sprites_group = getButtonSpritesGroup(BUTTONS)
    # 游戏主循环
    clock = pygame.time.Clock()
    selected_numbers = []
    selected_operators = []
    selected_buttons = []
    is_win = False
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit(-1)
            elif event.type == pygame.MOUSEBUTTONUP:
                mouse_pos = pygame.mouse.get_pos()
                selected_numbers = checkClicked(number_sprites_group, mouse_pos, 'NUMBER')
                selected_operators = checkClicked(operator_sprites_group, mouse_pos, 'OPREATOR')
                selected_buttons = checkClicked(button_sprites_group, mouse_pos, 'BUTTON')
        screen.fill(AZURE)
        # 更新数字
        if len(selected_numbers) == 2 and len(selected_operators) == 1:
            noselected_numbers = []
            for each in number_sprites_group:
                if each.is_selected:
                    if each.select_order == '1':
                        selected_number1 = each.attribute
                    elif each.select_order == '2':
                        selected_number2 = each.attribute
                    else:
                        raise ValueError('Unknow select_order %s, expect 1 or 2...' % each.select_order)
                else:
                    noselected_numbers.append(each.attribute)
                each.is_selected = False
            for each in operator_sprites_group:
                each.is_selected = False
            result = calculate(selected_number1, selected_number2, *selected_operators)
            if result is not None:
                game24_gen.numbers_now = noselected_numbers + [result]
                is_win = game24_gen.check()
                if is_win:
                    win_sound.play()
                if not is_win and len(game24_gen.numbers_now) == 1:
                    lose_sound.play()
            else:
                warn_sound.play()
            selected_numbers = []
            selected_operators = []
            number_sprites_group = getNumberSpritesGroup(game24_gen.numbers_now)
        # 精灵都画到screen上
        for each in number_sprites_group:
            each.draw(screen, pygame.mouse.get_pos())
        for each in operator_sprites_group:
            each.draw(screen, pygame.mouse.get_pos())
        for each in button_sprites_group:
            if selected_buttons and selected_buttons[0] in ['RESET', 'NEXT']:
                is_win = False
            if selected_buttons and each.attribute == selected_buttons[0]:
                each.is_selected = False
                number_sprites_group = each.do(game24_gen, getNumberSpritesGroup, number_sprites_group, button_sprites_group)
                selected_buttons = []
            each.draw(screen, pygame.mouse.get_pos())
        # 游戏胜利
        if is_win:
            showInfo('Congratulations', screen)
        # 游戏失败
        if not is_win and len(game24_gen.numbers_now) == 1:
            showInfo('Game Over', screen)
        pygame.display.flip()
        clock.tick(30)


'''run'''
if __name__ == '__main__':
    main()

11、平衡木

玩法:也是小时候的经典游戏,控制左右就行,到后面才有一点点难度。

源码分享:


import cfg
from modules import breakoutClone


'''主函数'''
def main():
    game = breakoutClone(cfg)
    game.run()


'''run'''
if __name__ == '__main__':
    main()

还有配置文件

12、外星人入侵

玩法:这让我想起了魂斗罗那第几关的boss,有点类似,不过魂斗罗那个难度肯定高点。

源码分享:


import os
import sys
import cfg
import random
import pygame
from modules import *


'''开始游戏'''
def startGame(screen):
    clock = pygame.time.Clock()
    # 加载字体
    font = pygame.font.SysFont('arial', 18)
    if not os.path.isfile('score'):
        f = open('score', 'w')
        f.write('0')
        f.close()
    with open('score', 'r') as f:
        highest_score = int(f.read().strip())
    # 敌方
    enemies_group = pygame.sprite.Group()
    for i in range(55):
        if i < 11:
            enemy = enemySprite('small', i, cfg.WHITE, cfg.WHITE)
        elif i < 33:
            enemy = enemySprite('medium', i, cfg.WHITE, cfg.WHITE)
        else:
            enemy = enemySprite('large', i, cfg.WHITE, cfg.WHITE)
        enemy.rect.x = 85 + (i % 11) * 50
        enemy.rect.y = 120 + (i // 11) * 45
        enemies_group.add(enemy)
    boomed_enemies_group = pygame.sprite.Group()
    en_bullets_group = pygame.sprite.Group()
    ufo = ufoSprite(color=cfg.RED)
    # 我方
    myaircraft = aircraftSprite(color=cfg.GREEN, bullet_color=cfg.WHITE)
    my_bullets_group = pygame.sprite.Group()
    # 用于控制敌方位置更新
    # --移动一行
    enemy_move_count = 24
    enemy_move_interval = 24
    enemy_move_flag = False
    # --改变移动方向(改变方向的同时集体下降一次)
    enemy_change_direction_count = 0
    enemy_change_direction_interval = 60
    enemy_need_down = False
    enemy_move_right = True
    enemy_need_move_row = 6
    enemy_max_row = 5
    # 用于控制敌方发射子弹
    enemy_shot_interval = 100
    enemy_shot_count = 0
    enemy_shot_flag = False
    # 游戏进行中
    running = True
    is_win = False
    # 主循环
    while running:
        screen.fill(cfg.BLACK)
        for event in pygame.event.get():
            # --点右上角的X或者按Esc键退出游戏
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    sys.exit()
            # --射击
            if event.type == pygame.MOUSEBUTTONDOWN:
                my_bullet = myaircraft.shot()
                if my_bullet:
                    my_bullets_group.add(my_bullet)
        # --我方子弹与敌方/UFO碰撞检测
        for enemy in enemies_group:
            i

以上是关于前端搭建打字通游戏(内附源码)的主要内容,如果未能解决你的问题,请参考以下文章

java小项目之:植物大战僵尸,这个僵尸有点冷!内附素材源码

python小游戏之超级玛丽进阶版(1~4关)。好玩到爆炸~内附github源码,及其详细备注

Unity手机游戏开发:从搭建到发布上线全流程实战

前端小游戏——植物大战僵尸

30个Python小游戏,上班摸鱼我能玩一天内附源码

30个Python小游戏,上班摸鱼我能玩一天内附源码