pygame制作游戏第一天

pygame制作第一天

 截个图

首先还是黑屏哈。后面找时间慢慢做地图跟其他角色,还有攻击方式等。

这里先做了一个“炫酷”的雨云召唤技能。

人物可以移动,g键召唤持续10秒的跟随目标的雨云。角色会被雨滴攻击。

思路很重要,不然数据传递就乱了。

雨滴是单个的,与其他元素无关(除了要传入攻击目标)。

云里面生成雨滴对象的集合,雨滴的x范围在与的[x,x+cloud.width]内

云需要跟随目标(这里暂定是玩家自己)需要定义其x,y的速度,以及方向。

人物我做了个基类charactor,玩家player继承基类。未雨绸缪哈

charactor.py

class Charactor(object):
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y

    def attack(self):
        pass

    def update(self, keys):
        pass

    def draw_damage(self, damage, window):
        pass

    def draw(self, delta, window):
        pass

player.py

import pygame

from cloud import Cloud

from settings import *
from charactor import Charactor


class Player(Charactor):
    def __init__(self):
        super().__init__()
        self.hp = 100
        self.x_speed = person_x_speed
        self.y_speed = person_y_speed
        self.facing = {
            'right': True,
            "left": False,
            'up': False,
            'down': False
        }
        self.pre_facing = 'right'
        self.peron_down_walk_images = peron_down_walk_images
        self.peron_up_walk_images = peron_up_walk_images
        self.peron_right_walk_images = peron_right_walk_images
        self.peron_left_walk_images = peron_left_walk_images
        self.image_index = 0
        self.image = peron_down_walk_images[self.image_index]
        self.width = peron_down_walk_images[self.image_index].get_width()
        self.height = peron_down_walk_images[self.image_index].get_height()

        self.hit_by_raindrop = 0

        self.font = pygame.font.Font(None, 36)
        self.get_damage = 0  # 受到伤害
        self.get_damage_text = None  # 受到伤害文本
        self.time_counter = 0  # 计时器
        self.skills = {
            'g': {'status': False,
                  'cloud': Cloud(self.x, self.y - 200),
                  'exist_time': 10,
                  }

        }

    def update(self, keys):
        if keys[pygame.K_a]:
            self.x -= self.x_speed
            self.facing['right'], self.facing['left'], self.facing['up'], self.facing[
                'down'] = False, True, False, False
        if keys[pygame.K_d]:
            self.x += self.x_speed
            self.facing['right'], self.facing['left'], self.facing['up'], self.facing[
                'down'] = True, False, False, False
        if keys[pygame.K_w]:
            self.y -= self.y_speed
            self.facing['right'], self.facing['left'], self.facing['up'], self.facing[
                'down'] = False, False, True, False
        if keys[pygame.K_s]:
            self.y += self.y_speed
            self.facing['right'], self.facing['left'], self.facing['up'], self.facing[
                'down'] = False, False, False, True
        if keys[pygame.K_g]:
            if not self.skills['g']['status']:
                self.skills['g']['status'] = True

    def skill_cloud(self, delta, window):
        if self.time_counter >= self.skills['g']['exist_time']:
            self.skills['g']['status'] = False
            self.time_counter = 0
        if self.skills['g']['status']:
            self.skills['g']['cloud'].rained_objects = [self]
            self.skills['g']['cloud'].update(delta, self)
            self.skills['g']['cloud'].draw(window)
        else:
            self.skills['g']['cloud'] = Cloud(self.x, self.y - 200)

    def damaged(self, damage):
        font = pygame.font.Font(None, 24)
        text1 = font.render(f"-{damage}", True, (255, 0, 0))
        self.get_damage = damage
        self.get_damage_text = text1

    def draw(self, delta, window):
        self.time_counter += delta
        self.skill_cloud(delta, window)
        for k, v in self.facing.items():
            if v and self.pre_facing != k:
                self.pre_facing = k
                self.image_index = 0
            if v and self.pre_facing == k:
                self.image_index = self.image_index + int(delta * FPS) if self.image_index < 6 else 0
            self.image = peron_down_walk_images[self.image_index]
            self.width = peron_down_walk_images[self.image_index].get_width()
            self.height = peron_down_walk_images[self.image_index].get_height()
        if self.facing['right']:
            images = self.peron_right_walk_images
        elif self.facing['left']:
            images = self.peron_left_walk_images
        elif self.facing['up']:
            images = self.peron_up_walk_images
        else:
            images = self.peron_down_walk_images
        window.blit(images[self.image_index], (self.x, self.y))
        pygame.draw.rect(window, (0, 0, 255), (0, 0, 40, 30))
        text1 = self.font.render(str(self.hp), True, (255, 0, 0))
        window.blit(text1, (screen_width - 100, 5))
        if self.get_damage:
            window.blit(self.get_damage_text, (self.x, self.y - 30))
            self.get_damage = 0

rain.py

import random
import pygame

from settings import *


class Rain(pygame.sprite.Sprite):
    def __init__(self, x, y, rained_objects):
        super().__init__()
        self.width = random.randint(0, 3)
        self.length = random.randint(8, 15)
        self.image = pygame.Surface([self.width, self.length])
        self.image.fill((244, 244, 255))
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.rained_objects = rained_objects
        self.drop_speed = random.randint(rain_drop_speed[0], rain_drop_speed[1]) # 下落速度随机范围
        self.gravity = drop_gravity  # 加速度

    def check_collision(self, item):
        return True if (item.x < self.rect.x < item.x + item.width
                        and item.y < self.rect.y < item.y + item.height) else False

    def update(self):
        self.drop_speed = self.drop_speed * (1 + self.gravity)
        self.rect.y += int(self.drop_speed)
        if self.rect.y > screen_height:
            self.kill()
        damage = int(10 * ((self.width * self.length) / 10))
        for item in self.rained_objects:
            if self.check_collision(item):
                item.hit_by_raindrop += 1
                item.hp -= damage
                item.damaged(damage)
                self.kill()

cloud.py

import random

import pygame

from settings import *
from rain import Rain


class Cloud:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.image = pygame.image.load(cloud_image_path).convert_alpha()
        self.width = self.image.get_width()
        self.height = self.image.get_height()
        self.x_speed = cloud_x_speed
        self.y_speed = cloud_y_speed
        self.move_right = True
        self.move_down = True
        self.delta = 0
        self.raining = True
        self.raindrops = pygame.sprite.Group()
        self.rain_counts = rain_counts
        self.rained_objects = []
        self.raining_time = 0
        self.total_raining_time = 10
        self.target_distance = 100

    def update(self, delta, target):
        self.raining_time += delta
        self.x = self.x + self.x_speed if self.move_right else self.x - self.x_speed
        self.y = self.y + self.y_speed if self.move_down else self.y - self.y_speed
        if self.x + self.width <= target.x: self.move_right = True
        if self.x >= target.x + target.width: self.move_right = False
        if self.y + self.height < target.y - self.target_distance:
            self.move_down, self.y_speed = True, cloud_y_speed
        elif self.y + self.height > target.y - self.target_distance:
            self.move_down, self.y_speed = False, cloud_y_speed
        else:
            self.y_speed = 0

    def rain(self, window):
        rain_range = [i for i in range(self.x, self.x + self.width)]
        if len(self.raindrops) <= self.rain_counts and self.raining:
            x = random.choice(rain_range)
            y = self.y + self.height
            new_raindrop = Rain(x, y, self.rained_objects)
            self.raindrops.add(new_raindrop)
        self.raindrops.update()
        self.raindrops.draw(window)

    def draw(self, window):
        window.blit(self.image, (self.x, self.y))
        self.rain(window)
        if self.raining_time >= self.total_raining_time:
            self.raining = False

settings.py

import random
import pygame

screen_width = 1280
screen_height = 720
FPS = 60
cloud_image_path = "data/cloud.png"
cloud_x_speed = 2
cloud_y_speed = 1
person_x_speed = 5
person_y_speed = 3
rain_counts = 5
rain_drop_speed = [3, 8]
rain_drop_interval = 0.1
drop_gravity = 0.005

peron_down_walk_images = []
for i in range(0, 7):
    img = pygame.image.load("data/catgame/walk/down_walk_%d.png" % i)
    peron_down_walk_images.append(img)
peron_up_walk_images = []
for i in range(0, 7):
    img = pygame.image.load("data/catgame/walk/up_walk_%d.png" % i)
    peron_up_walk_images.append(img)
peron_left_walk_images = []
for i in range(0, 7):
    img = pygame.image.load("data/catgame/walk/left_walk_%d.png" % i)
    peron_left_walk_images.append(img)
peron_right_walk_images = []
for i in range(0, 7):
    img = pygame.image.load("data/catgame/walk/right_walk_%d.png" % i)
    peron_right_walk_images.append(img)


ground_path = "data/ground1.png"
ground_rows = 4
ground_columns = 8

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Python利用pygame制作游戏是一种非常流行的方法。pygame是一个基于Python的游戏开发库,它提供了许多游戏开发所需的功能,如图形、声音、输入、碰撞检测等。使用pygame,开发者可以轻松地创建2D游戏。 要使用pygame制作游戏,首先需要安装pygame库。安装完成后,可以使用pygame提供的函数和类来创建游戏窗口、加载图像、播放声音、处理用户输入等。开发者可以根据自己的需求来设计游戏的逻辑和玩法。 在制作游戏时,需要注意游戏的性能和用户体验。为了提高游戏的性能,可以使用一些优化技巧,如使用双缓冲技术、避免频繁的图像绘制等。为了提高用户体验,可以添加一些特效、音效和动画效果,使游戏更加生动有趣。 总之,Python利用pygame制作游戏是一项非常有趣和有挑战性的工作。通过不断的学习和实践,开发者可以创造出各种各样的精彩游戏。 ### 回答2: Python是一种非常流行的编程语言,适用于各种应用。Python的一个优点是可以轻而易举地制作游戏,其中一个流行的Python游戏引擎是pygamepygame提供了一组功能强大的游戏开发工具,是许多Python游戏开发者的首选。 在Python中制作一个pygame游戏需要以下步骤: 1.安装pygame 要使用pygame,必须先安装它。可以通过pip命令轻松地安装pygame,如下所示: pip install pygame 2.创建游戏窗口 在pygame中,游戏窗口是承载游戏场景和对象的容器。可以使用pygame.display.set_mode()方法来创建一个游戏窗口: import pygame pygame.init() # Set up the display WIN_WIDTH = 800 WIN_HEIGHT = 600 screen = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT)) 3.创建游戏对象 在游戏中,对象是游戏动态的基本单元。游戏对象可以是玩家,敌人,迷宫,道具等等。要创建一个游戏对象,需要给它一个图像和位置: import pygame pygame.init() # Load the image ball_image = pygame.image.load("ball.png") # Set the position ball_x = 400 ball_y = 300 # Create the ball object ball = {"image": ball_image, "x": ball_x, "y": ball_y} 4.运行游戏循环 游戏循环是一个无限循环,用于更新游戏状态并渲染游戏。在pygame中,可以使用pygame.display.update()来更新游戏窗口,使用pygame.event.get()来获取所有游戏事件。 import pygame pygame.init() # Set up the display WIN_WIDTH = 800 WIN_HEIGHT = 600 screen = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT)) # Set up the ball ball_image = pygame.image.load("ball.png") ball_x = 400 ball_y = 300 ball = {"image": ball_image, "x": ball_x, "y": ball_y} # Set up the game loop done = False while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True # Update game objects ball_x += 1 ball["x"] = ball_x # Draw game objects screen.blit(ball["image"], (ball["x"], ball["y"])) pygame.display.update() 5.添加游戏逻辑 游戏逻辑是指游戏中的规则和交互,例如碰撞检测,得分系统和游戏状态等。可以将游戏逻辑添加到游戏循环中: import pygame pygame.init() # Set up the display WIN_WIDTH = 800 WIN_HEIGHT = 600 screen = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT)) # Set up the ball ball_image = pygame.image.load("ball.png") ball_x = 400 ball_y = 300 ball_speed = 5 ball = {"image": ball_image, "x": ball_x, "y": ball_y, "speed": ball_speed} # Set up the game loop done = False while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True # Update game objects ball_x += ball_speed if ball_x >= WIN_WIDTH: ball_speed = -ball_speed elif ball_x <= 0: ball_speed = -ball_speed ball["x"] = ball_x # Check for collisions # ... # Draw game objects screen.blit(ball["image"], (ball["x"], ball["y"])) pygame.display.update() 总的来说,python利用pygame制作游戏是简单易上手的。通过简单的Python代码,您可以创建各种各样的游戏,并让它们拥有各种各样的功能和特性。制作一个游戏可以提高代码编写水平,设计思路等多个方面,Pygame可谓是非常值得推荐的一款游戏开发框架。 ### 回答3: Python是一种流行的编程语言,具有简单易学和优雅的语法,还具有广泛的应用领域。Pygame则是Python中用于制作游戏的库,提供了丰富的API和模块,使得开发者可以轻松地创建各种游戏场景,并实现丰富的交互体验。 使用Pygame制作游戏,首先需要安装Pygame库,并配置好相应的开发环境。接着,可以通过使用Pygame提供的各种模块来实现游戏的各种功能,比如绘制游戏场景、添加动画效果、处理用户输入、播放音效等。具体来说,制作游戏的步骤包括以下几个方面: 1.准备素材。游戏中需要使用到各种素材,比如游戏背景、角色形象、道具、音效等,这些素材可以通过拍摄、绘制、采集等方式获得。制作游戏的时候,需要使用到一些图像和声音处理工具,如PIL、Audacity等。 2.绘制游戏场景。使用Pygame库提供的Surface类来创建游戏场景。Surface类是一个矩形区域,可以在其上绘制图像和文字。可以通过使用Pygame提供的各种绘图函数来对Surface对象进行绘制。 3.添加动画效果。可以使用Pygame中的Sprite类来创建游戏中的角色和道具。Sprite类可以用来表示游戏中的各个元素,并有自己的位置、速度等属性。使用Pygame提供的库可以实现动画,添加声音等交互效果。 4.处理用户输入。在游戏中,用户操作键盘、鼠标等方式进行交互,可以使用Pygame的事件处理模块来实现用户输入的检测和响应。 5.设计游戏规则。游戏规则会影响游戏的难度和趣味性。可以使用Python的面向对象编程思想来设计游戏规则,将各种游戏元素进行拆分,实现可扩展、可复用的代码结构。 总之,使用Pygame制作游戏是一项有趣的任务,可以锻炼自己的编程能力和创造力。在制作游戏的过程中,还可以了解游戏设计的相关知识、美工等技巧,对日后的工作或学习起到有益的作用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值