保姆级教你用Python制作超级玛丽游戏(文末赠书)

名字:阿玥的小东东

学习:Python、C/C++

主页链接:阿玥的小东东的博客_CSDN博客-python&&c++高级知识,过年必备,C/C++知识讲解领域博主

目录


Python是一门易学易用的编程语言,适用于各种不同的编程场景,包括游戏开发。Python不仅具有强大的数据处理和计算能力,还具有一整套游戏编程工具包,可以帮助开发者快速实现各种类型的游戏。本文将探讨如何使用Python编程语言制作游戏,阿玥了提供几个Python游戏开发的示例。

  1. Pygame游戏编程框架

Pygame是一个专门为Python编程语言设计的游戏开发框架,它提供了一整套游戏开发工具包,包括图形、声音和输入控制等。Pygame的优点在于它非常易学易用,并且具有广泛的社区支持和大量可用的代码资源。下面是一个使用Pygame编写的简单游戏的代码示例:

import pygame
from pygame.locals import *

pygame.init()
screen = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    screen.fill((255, 255, 255))
    pygame.draw.circle(screen, (255, 0, 0), (320, 240), 100)
    pygame.display.update()
    clock.tick(60)

贪吃蛇游戏

这个程序使用Pygame框架创建了一个窗口,并在屏幕中央绘制了一个红色圆形。这个游戏循环在每帧之间运行,并等待用户关闭窗口。

  1. 使用Pygame编写贪吃蛇游戏

下面是一个使用Pygame编写的贪吃蛇游戏的代码示例:

import pygame
import random
from pygame.locals import *

pygame.init()
screen = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()

class Snake:
    def __init__(self):
        self.body = [(4, 5), (5, 5), (6, 5)]
        self.direction = "right"

    def move(self):
        x, y = self.body[0]
        if self.direction == "up":
            y -= 1
        elif self.direction == "down":
            y += 1
        elif self.direction == "left":
            x -= 1
        elif self.direction == "right":
            x += 1
        self.body.pop()
        self.body.insert(0, (x, y))

    def grow(self):
        x, y = self.body[0]
        if self.direction == "up":
            y -= 1
        elif self.direction == "down":
            y += 1
        elif self.direction == "left":
            x -= 1
        elif self.direction == "right":
            x += 1
        self.body.insert(0, (x, y))

    def draw(self):
        for x, y in self.body:
            pygame.draw.rect(screen, (0, 255, 0), (x * 20, y * 20, 20, 20), 0)

    def check_collision(self):
        x, y = self.body[0]
        if x < 0 or x > 31 or y < 0 or y > 23:
            return True
        for i, j in self.body[1:]:
            if x == i and y == j:
                return True
        return False

class Food:
    def __init__(self):
        self.x = random.randint(0, 31)
        self.y = random.randint(0, 23)

    def draw(self):
        pygame.draw.rect(screen, (255, 0, 0), (self.x * 20, self.y * 20, 20, 20), 0)

    def check_collision(self, snake):
        if self.x == snake.body[0][0] and self.y == snake.body[0][1]:
            snake.grow()
            self.x = random.randint(0, 31)
            self.y = random.randint(0, 23)

snake = Snake()
food = Food()

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == KEYDOWN:
            if event.key == K_UP and snake.direction != "down":
                snake.direction = "up"
            elif event.key == K_DOWN and snake.direction != "up":
                snake.direction = "down"
            elif event.key == K_LEFT and snake.direction != "right":
                snake.direction = "left"
            elif event.key == K_RIGHT and snake.direction != "left":
                snake.direction = "right"

    screen.fill((0, 0, 0))
    snake.move()
    snake.draw()
    food.draw()
    food.check_collision(snake)
    if snake.check_collision():
        pygame.quit()
        sys.exit()
    pygame.display.update()
    clock.tick(10)

这个程序使用Pygame框架创建了一个窗口,并绘制了一条贪吃蛇和一个食物。在这个游戏中,玩家必须通过控制蛇来吃掉食物,每吃掉一个食物,蛇就会变长一节。

  1. 使用Pygame编写弹珠游戏

下面是一个使用Pygame编写的弹珠游戏的代码示例:

弹珠游戏

import pygame
from pygame.locals import *

pygame.init()
screen = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()

class Ball:
    def __init__(self, x, y, vx, vy, radius):
        self.x = x
        self.y = y
        self.vx = vx
        self.vy = vy
        self.radius = radius

    def move(self):
        self.x += self.vx
        self.y += self.vy

    def draw(self):
        pygame.draw.circle(screen, (255, 255, 255), (self.x, self.y), self.radius)

class Paddle:
    def __init__(self, x, y, width, height, speed):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.speed = speed

    def move(self, direction):
        if direction == "left":
            self.x -= self.speed
        elif direction == "right":
            self.x += self.speed

        if self.x < 0:
            self.x = 0
        elif self.x + self.width > 640:
            self.x = 640 - self.width

    def draw(self):
        pygame.draw.rect(screen, (255, 255, 255), (self.x, self.y, self.width, self.height), 0)

ball = Ball(320, 240, 5, -5, 10)
paddle = Paddle(250, 460, 100, 20, 10)

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == KEYDOWN:
            if event.key == K_LEFT:
                paddle.move("left")
            elif event.key == K_RIGHT:
                paddle.move("right")

    screen.fill((0, 0, 0))
    ball.move()
    ball.draw()
    paddle.draw()
    if ball.y < ball.radius:
        ball.vy = -ball.vy
    elif ball.x < ball.radius or ball.x > 640 - ball.radius:
        ball.vx = -ball.vx
    elif ball.y > 480 - ball.radius:
        pygame.quit()
        sys.exit()
    if ball.y >= paddle.y - ball.radius and ball.x >= paddle.x and ball.x <= paddle.x + paddle.width:
        ball.vy = -ball.vy
    pygame.display.update()
    clock.tick(60)

这个程序使用Pygame框架创建了一个窗口,并在屏幕中央绘制了一个弹珠和一个滑板。在这个游戏中,玩家必须使用滑板将弹珠弹回,直到弹珠跌落到底部或碰到四周的边界。

超级玛丽(爷青回~)

超级玛丽游戏是一款非常经典的游戏,下面我们将使用Python语言来实现一个类似的简化版的超级玛丽游戏。

  1. 游戏背景

我们将使用Pygame工具包来实现游戏背景,首先我们需要导入Pygame和sys模块:

import pygame
import sys

然后,需要初始化Pygame:

pygame.init()

接着,我们创建一个窗口,并设置窗口大小为800×600像素:

screen = pygame.display.set_mode((800, 600))

为了方便维护,我们将游戏中要使用到的颜色值定义成常量:

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GRAY = (128, 128, 128)

然后,我们可以在窗口中绘制游戏背景:

screen.fill(BLACK)
pygame.draw.rect(screen, GRAY, (100, 100, 600, 400), 0)
pygame.display.update()

这段代码绘制了一个灰色的矩形框作为游戏背景。

  1. 玛丽角色

接下来,我们需要定义玩家角色——超级玛丽。我们使用一个小人头像来代表超级玛丽。

首先,我们需要导入pygame.image模块:

import pygame.image

然后,我们可以通过以下代码加载和绘制超级玛丽的头像:

mario = pygame.image.load("mario_head.png")
screen.blit(mario, (400, 500))
pygame.display.update()

这段代码加载了一个名为“mario_head.png”的图像文件,并将其绘制到了屏幕中央底部。

  1. 定义玛丽的移动

接下来,我们需要定义超级玛丽的移动方法。为了简化游戏逻辑,我们将只实现左右移动和跳跃两种动作。

首先,我们需要定义超级玛丽的位置和速度:

mario_pos = [400, 500]
mario_vel = [0, 0]

然后,我们需要在主循环中监听键盘事件,并根据按下的键来决定超级玛丽的移动:

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                mario_vel[0] = -5  # 向左移动
            elif event.key == pygame.K_RIGHT:
                mario_vel[0] = 5   # 向右移动
            elif event.key == pygame.K_UP:
                mario_vel[1] = -10 # 跳跃

    mario_pos[0] += mario_vel[0]
    mario_pos[1] += mario_vel[1]

    screen.fill(BLACK)
    pygame.draw.rect(screen, GRAY, (100, 100, 600, 400), 0)
    screen.blit(mario, mario_pos)
    pygame.display.update()

    mario_vel[1] += 1  # 重力加速度

这段代码在接收到左右移动和跳跃的键盘事件后,更新了超级玛丽的位置和速度,并将其绘制到了游戏背景中。

  1. 定义碰撞检测

最后,我们需要实现超级玛丽与游戏背景的碰撞检测。当超级玛丽碰到游戏背景时,需要停止其运动。

我们可以定义一个名为“is_collision”的函数来检测碰撞:

def is_collision(pos, vel, rect):
    if pos[0] < rect[0]:
        pos[0] = rect[0]
    elif pos[0] > rect[0] + rect[2]:
        pos[0] = rect[0] + rect[2]
    if pos[1] < rect[1]:
        pos[1] = rect[1]
        vel[1] = 0
    elif pos[1] > rect[1] + rect[3]:
        pos[1] = rect[1] + rect[3]
        vel[1] = 0
    return pos, vel

这个函数用于检测超级玛丽是否与游戏背景矩形碰撞,如果发生碰撞,将会返回新的位置和速度。

接着,我们需要在主循环中调用这个函数:

while True:
    # 监听键盘事件,更新玛丽的位置和速度
    ...

    # 检测碰撞,更新玛丽的位置和速度
    mario_pos, mario_vel = is_collision(mario_pos, mario_vel, (100, 100, 600, 400))

    # 绘制游戏背景和玛丽
    ...

这样,当超级玛丽碰撞到游戏背景矩形时,就会停止运动了。

完整代码如下:

import pygame
import sys

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GRAY = (128, 128, 128)

pygame.init()
screen = pygame.display.set_mode((800, 600))

mario = pygame.image.load("mario_head.png")
mario_pos = [400, 500]
mario_vel = [0, 0]

def is_collision(pos, vel, rect):
    if pos[0] < rect[0]:
        pos[0] = rect[0]
    elif pos[0] > rect[0] + rect[2]:
        pos[0] = rect[0] + rect[2]
    if pos[1] < rect[1]:
        pos[1] = rect[1]
        vel[1] = 0
    elif pos[1] > rect[1] + rect[3]:
        pos[1] = rect[1] + rect[3]
        vel[1] = 0
    return pos, vel

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                mario_vel[0] = -5
            elif event.key == pygame.K_RIGHT:
                mario_vel[0] = 5
            elif event.key == pygame.K_UP:
                mario_vel[1] = -10

    mario_pos[0] += mario_vel[0]
    mario_pos[1] += mario_vel[1]

    mario_pos, mario_vel = is_collision(mario_pos, mario_vel, (100, 100, 600, 400))

    screen.fill(BLACK)
    pygame.draw.rect(screen, GRAY, (100, 100, 600, 400), 0)
    screen.blit(mario, mario_pos)
    pygame.display.update()

    mario_vel[1] += 1

这段代码可以实现一个简单的超级玛丽游戏,玩家可以通过左右移动和跳跃来控制超级玛丽的运动,当超级玛丽碰到游戏背景时,将会停止运动。

总结

Python是一门非常适合游戏开发的编程语言,其强大的数据处理和计算能力以及丰富的游戏编程工具包为开发者提供了广阔的发展空间。阿玥提供了几个使用Python编写的简单游戏示例,大佬们看看就好,也可以自己动手敲打敲打

本期推荐

本期推荐

参与方式:点赞+收藏+评论:人生苦短,我用Python!

截止6.18日晚上20:00

保姆级教你用Python制作超级玛丽游戏(文末赠书)

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
心中带点小风骚的头像心中带点小风骚普通用户
上一篇 2023年6月19日
下一篇 2023年6月19日

相关推荐