pygame图像透明度混乱

如何解决pygame图像透明度混乱

我在此处阅读了与此问题相关的前20条帖子,在Google上阅读了很多示例,尝试使用.convert().convert_alpha(),尝试都不使用,.png,.gif, Google上排名前5位的不同图片。请有人帮我弄清楚如何以透明背景显示作品。 这是所有代码:

import pygame
pygame.init()
print("1")
screen_size = (600,600)
blue = (100,225,225)
screen = pygame.display.set_mode(screen_size)
pygame.display.set_caption("Chess")


class SpriteSheet:

    def __init__(self,filename):
        """Load the sheet."""
        try:
            self.sheet = pygame.image.load(filename).convert.alpha()
        except pygame.error as e:
            print(f"Unable to load spritesheet image: {filename}")
            raise SystemExit(e)


    def image_at(self,rectangle,colorkey = None):
        """Load a specific image from a specific rectangle."""
        # Loads image from x,y,x+offset,y+offset.
        rect = pygame.Rect(rectangle)
        image = pygame.Surface(rect.size)
        image.blit(self.sheet,(0,0),rect)
        if colorkey is not None:
            if colorkey == -1:
                colorkey = image.get_at((0,0))
            image.set_colorkey(colorkey,pygame.RLEACCEL)
        return image

    def images_at(self,rects,colorkey = None):
        """Load a whole bunch of images and return them as a list."""
        return [self.image_at(rect,colorkey) for rect in rects]

    def load_strip(self,rect,image_count,colorkey = None):
        """Load a whole strip of images,and return them as a list."""
        tups = [(rect[0]+rect[2]*x,rect[1],rect[2],rect[3])
                for x in range(image_count)]
        return self.images_at(tups,colorkey)
print("2")

class Game:
    def __init__(self):
        self.playing = False
        self.move = 0
        self.player_turn = 1
        self.quit = False

    def quit(self):
        self.quit = True

print("3")
class Piece:
    def __init__(self):
        self.sprite = None
        self.spacial = [0,0]
        self.temporal = [0,0]
        self.position = [self.spacial,self.temporal]
        self.color = ""
        self.type = ""

print("4")
chess_image = SpriteSheet('ChessPiecesArray.png')
colors = ["White","Black"]
types = ["K","Q","B","N","R","P"]
rect_piece = (0,133,133)

print("5")


class ChessSet:
    def __init__(self):
        self.set = []

    def create_set(self):
        for i in range(2):
            for j in range(6):
                this_piece = Piece()
                this_piece.color = colors[i]
                this_piece.type = types[j]
                rect_set = (133*j,133*i,133*(j+1),133*(i+1))
                this_piece.sprite = SpriteSheet.image_at(chess_image,rect_set)
                self.set.append(this_piece)

print("6")
chess = Game()
set_one = ChessSet()
set_one.create_set()

print("7")
while not chess.quit:
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_q:
                chess.quit()
    screen.fill(blue)
    screen.blit(set_one.set[0].sprite,(10,10))

    pygame.display.flip()

以下是我花时间尝试的一些图片:

编辑:这是我的错误消息在我的代码与建议的更改的屏幕快照

Changed code

解决方法

如果将透明的 Surface 复制到另一个 Surface ,则目标 Surface 必须分别为每个像素alpha提供透明度。

创建新曲面时可以启用其他功能。设置SRCALPHA标志以创建具有包括每个像素alpha的图像格式的表面。像素的初始值为(0,0,0,0):

my_surface = pygame.Surface((width,height),pygame.SRCALPHA)

使用以下图片

并修改类image_at的方法SpriteSheet。使用pygame.SRCALPHA

class SpriteSheet:
    # [...]

    def image_at(self,rectangle,colorkey = None):
        """Load a specific image from a specific rectangle."""
        # Loads image from x,y,x+offset,y+offset.
        rect = pygame.Rect(rectangle)
        
        image = pygame.Surface(rect.size,pygame.SRCALPHA) # <----
        
        image.blit(self.sheet,(0,0),rect)
        if colorkey is not None:
            if colorkey == -1:
                colorkey = image.get_at((0,0))
            image.set_colorkey(colorkey,pygame.RLEACCEL)
        return image

或使用convert_alpha()

class SpriteSheet:
    # [...]

    def image_at(self,y+offset.
        rect = pygame.Rect(rectangle)
        
        image = pygame.Surface(rect.size).convert_alpha() # <----
        image.fill((0,0))                          # <---
        
        image.blit(self.sheet,pygame.RLEACCEL)
        return image

另请参阅:


请注意,棋子也可以通过Unicode文本绘制。
参见Displaying unicode symbols using pygame

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-