玩游戏也能学编程!30个Python 小游戏,初学者也能快乐敲代码啦(含源码)

文摘   2024-10-29 10:30   山西  

Python 作为一种简洁易懂且功能强大的编程语言,吸引着越来越多的初学者。当学习与游戏相结合,可以快速让同学们get到学习编程的乐趣~

下面小黄鸭给大家分享30个Python小游戏及源码,希望能更好的帮助大家上手掌握!由于篇幅限制在此就发布了3个,剩下的源码已经给大家打包好了在文末,需要的可以自取嗷!

一、植物大战僵尸游戏:

1. 游戏逻辑

玩家:选择并放置植物来防御。

僵尸:从屏幕的一边出现,并向另一边移动。

目标:阻止僵尸到达屏幕的另一边。

2. 使用库

pygame:用于创建图形界面和处理用户输入。

random:用于随机生成僵尸的位置和速度。

3. 简化实现

植物:只有一种,可以射击僵尸。

僵尸:只有一种,速度随机。

界面:简单的命令行界面。

4. 代码示例

import pygame  import random  import sys  import time    # 初始化pygame  pygame.init()    # 设置颜色  WHITE = (255, 255, 255)  GREEN = (0, 255, 0)  RED = (255, 0, 0)    # 设置屏幕大小  SCREEN_WIDTH, SCREEN_HEIGHT = 800, 600  screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))    # 植物和僵尸的类  class Plant:      def __init__(self, x, y):          self.x = x          self.y = y          self.bullets = []        def shoot(self):          bullet = pygame.Rect(self.x + 20, self.y, 5, 10)          self.bullets.append(bullet)        def move_bullets(self):          for bullet in self.bullets:              bullet.y -= 5        def draw(self):          pygame.draw.rect(screen, GREEN, pygame.Rect(self.x, self.y, 50, 50))          for bullet in self.bullets:              pygame.draw.rect(screen, RED, bullet)    class Zombie:      def __init__(self):          self.x = random.randint(SCREEN_WIDTH, SCREEN_WIDTH + 50)          self.y = random.randint(0, SCREEN_HEIGHT)          self.speed = random.randint(1, 5)        def move(self):          self.x -= self.speed        def draw(self):          pygame.draw.rect(screen, RED, pygame.Rect(self.x, self.y, 50, 50))    # 游戏主循环  def game_loop():      plant = Plant(SCREEN_WIDTH - 60, SCREEN_HEIGHT // 2)      zombies = [Zombie() for _ in range(5)]        running = True      while running:          for event in pygame.event.get():              if event.type == pygame.QUIT:                  running = False              elif event.type == pygame.KEYDOWN:                  if event.key == pygame.K_SPACE:                      plant.shoot()            screen.fill(WHITE)            plant.move_bullets()          plant.draw()            for zombie in zombies:              zombie.move()              zombie.draw()                # 检查子弹是否击中僵尸              for bullet in plant.bullets:                  if zombie.x < bullet.x < zombie.x + 50 and zombie.y < bullet.y < zombie.y + 50:                      plant.bullets.remove(bullet)                      zombies.remove(zombie)                      break            # 检查僵尸是否到达屏幕左边          zombies = [zombie for zombie in zombies if zombie.x > 0]            pygame.display.flip()          time.sleep(0.1)        pygame.quit()      sys.exit()    # 运行游戏  game_loop()


 二、飞机大战

让我们用python来做一个飞机大战小游戏,要放置玩家和敌机还有子弹,设置玩家控制方向:WASD,攻击:J。

运行视频:


代码:

 

import randomimport tkinter root = tkinter.Tk()root.title('飞机大战')root.geometry('800x650+400+100')canvas = tkinter.Canvas(root, width=550, height=520, bg='white')canvas.pack()lb = tkinter.Label(root, width=20, height=1, bg='white')lb.place(x=290, y=540)count = 0message = "消灭敌机数量:"lb['text'] = message + str(count)lb2 = tkinter.Label(root, width=20, height=1, bg='white')lb2.place(x=290, y=570)lb2['text'] = '---'  # 玩家class PlayerPlane:    # 机翼的坐标    wings_x1, wings_y1 = 240, 470    wings_x2, wings_y2 = 290, 470    # 尾翼的坐标    tail_x1, tail_y1 = 250, 500    tail_x2, tail_y2 = 280, 500    # 机身的坐标    fuselage_x1, fuselage_y1 = 265, 500    fuselage_x2, fuselage_y2 = 265, 440    # 子弹的坐标    bullet_x1, bullet_y1 = fuselage_x2, fuselage_y2    bullet_x2, bullet_y2 = bullet_x1, bullet_y1 - 120     def __init__(self):        # 机翼        self.wings = canvas.create_line(self.wings_x1, self.wings_y1, self.wings_x2, self.wings_y2)        # 尾翼        self.tail = canvas.create_line(self.tail_x1, self.tail_y1, self.tail_x2, self.tail_y2)        # 机身        self.fuselage = canvas.create_line(self.fuselage_x1, self.fuselage_y1, self.fuselage_x2, self.fuselage_y2)        # 子弹        self.bullet = None        # 移动距离        self.move_distance = 5     # 攻击    def attack(self, event):        # 子弹的坐标        self.bullet_x1, self.bullet_y1 = self.fuselage_x2, self.fuselage_y2        self.bullet_x2, self.bullet_y2 = self.bullet_x1, self.bullet_y1 - 120        # 子弹        self.bullet = canvas.create_line(self.bullet_x1, self.bullet_y1, self.bullet_x2, self.bullet_y2, fill='red',                                         dash=(1, 1))        # 80毫秒之后子弹消失        canvas.after(80, self.delete_bullet)     # 删除子弹    def delete_bullet(self):        canvas.delete(self.bullet)     # 左移    def move_left(self, event):        if self.wings_x1 == 0:            return        canvas.move(self.wings, -self.move_distance, 0)        self.wings_x1 -= self.move_distance        self.wings_x2 -= self.move_distance         canvas.move(self.tail, -self.move_distance, 0)        self.tail_x1 -= self.move_distance        self.tail_x2 -= self.move_distance         canvas.move(self.fuselage, -self.move_distance, 0)        self.fuselage_x1 -= self.move_distance        self.fuselage_x2 -= self.move_distance     # 右移    def move_right(self, event):        if self.wings_x2 == 550:            return        canvas.move(self.wings, self.move_distance, 0)        self.wings_x1 += self.move_distance        self.wings_x2 += self.move_distance         canvas.move(self.tail, self.move_distance, 0)        self.tail_x1 += self.move_distance        self.tail_x2 += self.move_distance         canvas.move(self.fuselage, self.move_distance, 0)        self.fuselage_x1 += self.move_distance        self.fuselage_x2 += self.move_distance     # 上移    def move_up(self, event):        if self.fuselage_y2 == 0:            return        canvas.move(self.wings, 0, -self.move_distance)        self.wings_y1 -= self.move_distance        self.wings_y2 -= self.move_distance         canvas.move(self.tail, 0, -self.move_distance)        self.tail_y1 -= self.move_distance        self.tail_y2 -= self.move_distance         canvas.move(self.fuselage, 0, -self.move_distance)        self.fuselage_y1 -= self.move_distance        self.fuselage_y2 -= self.move_distance     # 下移    def move_down(self, event):        if self.fuselage_y1 == 530:            return        canvas.move(self.wings, 0, self.move_distance)        self.wings_y1 += self.move_distance        self.wings_y2 += self.move_distance         canvas.move(self.tail, 0, self.move_distance)        self.tail_y1 += self.move_distance        self.tail_y2 += self.move_distance         canvas.move(self.fuselage, 0, self.move_distance)        self.fuselage_y1 += self.move_distance        self.fuselage_y2 += self.move_distance  # 敌机类class EnemyPlane:    wings_x1 = 0    wings_y1 = 30    wings_x2 = 40    wings_y2 = 30    tail_x1 = 10    tail_y1 = 0    tail_x2 = 30    tail_y2 = 0    fuselage_x1 = 20    fuselage_y1 = 0    fuselage_x2 = 20    fuselage_y2 = 60    # 子弹的坐标    bullet_x1, bullet_y1 = fuselage_x2, fuselage_y2    bullet_x2, bullet_y2 = bullet_x1, bullet_y1 + 120     def __init__(self):        self.bullet = None        # 移动距离        self.move_distance = 10     def create(self):        lt = [0, 40, 80, 120]        x_change = random.choice(lt)        self.wings_x1 += x_change        self.wings_x2 += x_change        self.tail_x1 += x_change        self.tail_x2 += x_change        self.fuselage_x1 += x_change        self.fuselage_x2 += x_change        # 机翼        self.wings = canvas.create_line(self.wings_x1, self.wings_y1, self.wings_x2, self.wings_y2)        # 尾翼        self.tail = canvas.create_line(self.tail_x1, self.tail_y1, self.tail_x2, self.tail_y2)        # 机身        self.fuselage = canvas.create_line(self.fuselage_x1, self.fuselage_y1, self.fuselage_x2, self.fuselage_y2)        self.move()     def attack(self):        # 子弹的坐标        self.bullet_x1, self.bullet_y1 = self.fuselage_x2, self.fuselage_y2        self.bullet_x2, self.bullet_y2 = self.bullet_x1, self.bullet_y1 + 120        # 子弹        self.bullet = canvas.create_line(self.bullet_x1, self.bullet_y1, self.bullet_x2, self.bullet_y2, fill='red',                                         dash=(1, 1))        # 80毫秒之后子弹消失        canvas.after(100, self.delete_bullet)     # 删除子弹    def delete_bullet(self):        canvas.delete(self.bullet)     def delete(self):        canvas.delete(self.wings)        canvas.delete(self.tail)        canvas.delete(self.fuselage)     def move(self):        global count        self.attack()         canvas.move(self.wings, 0, self.move_distance)        self.wings_y1 += self.move_distance        self.wings_y2 += self.move_distance         canvas.move(self.tail, 0, self.move_distance)        self.tail_y1 += self.move_distance        self.tail_y2 += self.move_distance         canvas.move(self.fuselage, 0, self.move_distance)        self.fuselage_y1 += self.move_distance        self.fuselage_y2 += self.move_distance        time_id2 = root.after(2000, self.move)         if self.fuselage_y2 == 530:            root.after_cancel(time_id2)            self.delete()         # 检测是否受到攻击        if (self.wings_x1 <= p.bullet_x2 <= self.wings_x2 and self.wings_y2 >= p.bullet_y2) or (                p.bullet_x2 == self.fuselage_x2 and p.bullet_y2 <= self.fuselage_y2):            root.after_cancel(time_id2)            self.delete()            count += 1            lb['text'] = message + str(count)            if count == n:                lb2['text'] = '敌机已全部消灭!' # 创建玩家飞机p = PlayerPlane()#  存放敌机lt = []# 敌机数量n = 3for i in range(n):    lt.append(EnemyPlane())i = 0 def cre():    global i, n, count    time_id = root.after(6000, cre)    if i < n:        lt[i].create()        i += 1    else:        root.after_cancel(time_id)# 创建敌机cre() # 绑定事件canvas.bind('<KeyPress-j>', p.attack)canvas.bind('<KeyPress-a>', p.move_left)canvas.bind('<KeyPress-d>', p.move_right)canvas.bind('<KeyPress-w>', p.move_up)canvas.bind('<KeyPress-s>', p.move_down)# 设置按钮获取焦点canvas.focus_set() root.mainloop()


三、忍者奔跑

创建一个简单的“忍者奔跑”小游戏可以使用Python的pygame库。以下是一个基本的项目结构,包括游戏循环和一些基本的功能,如角色移动、背景滚动和基本碰撞检测。
首先,确保你已经安装了pygame库。如果没有安装,可以使用pip来安装:         

pip install pygame

      代码:

import pygameimport random# 初始化pygamepygame.init()# 设置屏幕大小screen_width = 800screen_height = 600screen = pygame.display.set_mode((screen_width, screen_height))# 设置标题pygame.display.set_caption('忍者奔跑')# 定义颜色WHITE = (255, 255, 255)GREEN = (0, 255, 0)# 定义忍者属性ninja_image = pygame.image.load('ninja.png').convert_alpha()  # 假设你有一个忍者图像ninja_width = ninja_image.get_width()ninja_height = ninja_image.get_height()ninja_x = screen_width // 2ninja_y = screen_height - ninja_height - 10ninja_speed = 5# 定义背景属性background_image = pygame.image.load('background.png').convert()  # 假设你有一个背景图像background_width = background_image.get_width()background_height = background_image.get_height()background_x = 0background_y = 0# 定义障碍物属性obstacle_image = pygame.image.load('obstacle.png').convert_alpha()  # 假设你有一个障碍物图像obstacle_width = obstacle_image.get_width()obstacle_height = obstacle_image.get_height()obstacles = []# 游戏主循环running = 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_LEFT:                ninja_x -= ninja_speed            if event.key == pygame.K_RIGHT:                ninja_x += ninja_speed    # 忍者移动    ninja_x = max(0, min(ninja_x, screen_width - ninja_width))    # 背景滚动    background_x -= 1    if background_x + background_width < 0:        background_x = screen_width    # 创建障碍物    if random.randint(1, 30) == 1:        obstacles.append([random.randint(0, screen_width - obstacle_width), 0])    for obstacle in obstacles:        obstacle[1] -= 5        if obstacle[1] + obstacle_height < 0:            obstacles.remove(obstacle)    # 碰撞检测    for obstacle in obstacles:        if (ninja_x < obstacle[0] + obstacle_width and            ninja_x + ninja_width > obstacle[0] and            ninja_y < obstacle[1] + obstacle_height and            ninja_y + ninja_height > obstacle[1]):            running = False    # 绘制    screen.fill(WHITE)    screen.blit(background_image, (background_x, background_y))    screen.blit(ninja_image, (ninja_x, ninja_y))    for obstacle in obstacles:        screen.blit(obstacle_image, (obstacle[0], obstacle[1]))    # 更新屏幕    pygame.display.flip()    # 控制游戏帧率    pygame.time.Clock().tick(60)# 退出游戏

        


    1. 剩下的Python小游戏游戏

    1. 如何获取资料:


    2. 后台回复:游戏项目 获取







    小黄鸭编程
    分享Python、Java、前端、大数据、人工智能等程序员必备资料,在这里可以获得最全的编程资料。
     最新文章