为孩子准备的 第一个python编程学习案例-pygame小游戏

部署运行你感兴趣的模型镜像


  • 想指导孩子进行python编程启蒙,自己研究了一下如何从零搭建python开发环境、安装配置基本库并运行一个游戏示例.

python安装

安装最新版本的python, 3.13.1版本

https://www.python.org/ftp/python/3.13.1/python-3.13.1-amd64.exe

安装之后 ,打开 CMD:

PS D:\AppGallery>
PS D:\AppGallery> python.exe
Python 3.13.1 (tags/v3.13.1:0671451, Dec  3 2024, 19:06:28) [MSC v.1942 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> help
>>> Welcome to Python 3.13's help utility! If this is your first time using
Python, you should definitely check out the tutorial at
https://docs.python.org/3.13/tutorial/.

Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules.  To get a list of available
modules, keywords, symbols, or topics, enter "modules", "keywords",
"symbols", or "topics".

Each module also comes with a one-line summary of what it does; to list
the modules whose name or summary contain a given string such as "spam",
enter "modules spam".

To quit this help utility and return to the interpreter,
enter "q", "quit" or "exit".

安装 pygame,如果缺少其他库,通常也可以使用pip进行安装。

pip instll pygame

IDE安装thonny

Thonny最常被推荐作为初学者的Python集成开发环境。它适用于Windows、macOS和Linux。它的功能包括代码调试、功能语法高亮和识别相似名称。Thonny还有一个“助手”,可以帮助你查看错误,并且你正在运行的应用程序可以在多个窗口中打开。

安装完python后,自带pip,这里无须再专门下载thonny安装包,而是直接使用pip安装 thonny

pip install thonny

image-20241225214846266

打开 thonny

PS D:\AppGallery> thonny.exe
PS D:\AppGallery>

image-20241225215345186

开发第一个小游戏-避坑指南

网上找了很多示例,遇到各种坑:

  1. 代码不全 , 比如 豆包提供的猜数游戏

  2. cfg模块缺失: cfg是博主自定义的一些变量集合,缺失导致游戏无法正常运行

    15个Python小游戏,上班摸鱼我能玩一天【内附源码】 - 小明谈Python - 博客园

        import cfg
    ModuleNotFoundError: No module named 'cfg'
    
  3. 代码格式不对,一般是缩进问题:

    IndentationError: expected an indented block after function definition on line 3
    
  4. 缩进问题,有时也会报错为变量未定义,需要自己复制 粘贴代码时注意检查缩进格式

  File "D:\code\7. python\catchgame.py", line 39, in Player
    if keys[pygame.K_LEFT]:
NameError: name 'keys' is not defined

最终运行通过的小游戏

如果提示缺少其他库,通常也可以使用pip进行安装。复制代码时注意缩进和格式 。

import pygame
import random

# Initialize pygame
pygame.init() 
# Set the width and height of the screen (width, height)
screen = pygame.display.set_mode((800, 600))

# Set the title of the window
pygame.display.set_caption("Catch Game")

# Set the clock
clock = pygame.time.Clock()

# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)


# Player class
class Player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.Surface([50, 50])
        self.image.fill(RED)
        self.rect = self.image.get_rect()
        self.rect.x = 375
        self.rect.y = 500
        self.speed = 5
    def update(self):
        # Get the current key state
        keys = pygame.key.get_pressed()

    # Move the player
    if keys[pygame.K_LEFT]:
        self.rect.x -= self.speed
    elif keys[pygame.K_RIGHT]:
        self.rect.x += self.speed

# Object class
class Object(pygame.sprite.Sprite):
   def __init__(self):
      super().__init__()
      self.image = pygame.Surface([25, 25])
      self.image.fill(BLUE)
      self.rect = self.image.get_rect()
      self.rect.x = random.randrange(0, 750)
      self.rect.y = random.randrange(-100, -40)
      self.speed = random.randint(2, 8)

   def update(self):
      # Move the object down the screen
      self.rect.y += self.speed

      # If the object goes off the bottom of the screen, reset it
      if self.rect.top > 600:
         self.rect.x = random.randrange(0, 750)
         self.rect.y = random.randrange(-100, -40)
         self.speed = random.randint(2, 8)

# Create groups for all sprites and objects
all_sprites = pygame.sprite.Group()
objects = pygame.sprite.Group()

# Create the player
player = Player()
all_sprites.add(player)

# Create the objects
for i in range(10):
   obj = Object()
   all_sprites.add(obj)
   objects.add(obj)

# Set the score
score = 0

# Set the font
font_name = pygame.font.match_font("arial")

# Function to draw text on the screen
def draw_text(surf, text, size, x, y):
   font = pygame.font.Font(font_name, size)
   text_surface = font.render(text, True, WHITE)
   text_rect = text_surface.get_rect()
   text_rect.midtop = (x, y)
   surf.blit(text_surface, text_rect)

# Game loop
running = True
while running:
   # Set the frame rate
   clock.tick(60)

   # Process events
   for event in pygame.event.get():
      if event.type == pygame.QUIT:
         running = False

   # Update all sprites
   all_sprites.update()

   # Check for collisions between the player and objects
   hits = pygame.sprite.spritecollide(player, objects, True)
   for hit in hits:
      score += 1
      obj = Object()
      all_sprites.add(obj)
      objects.add(obj)

   # Draw everything on the screen
   screen.fill(BLACK)
   all_sprites.draw(screen)
   draw_text(screen, "Score: {}".format(score), 18, 50, 10)

   # Update the screen
   pygame.display.update()

参考

Building a Simple Game in Python using the PyGame Module

The End.

您可能感兴趣的与本文相关的镜像

Python3.11

Python3.11

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

月光技术杂谈

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值