首页 > 编程问答 >pygame中对象列表的颜色渐变

pygame中对象列表的颜色渐变

时间:2024-07-26 15:03:48浏览次数:6  
标签:python colors pygame

我正在尝试在 pygame 中重新创建游戏蛇作为介绍,但是我正在努力解决如何在蛇移动时为蛇的每个方块创建渐变。我的其余代码都是有效的。

我编写了以下代码:

import colorsys

class Snake:
  def __init__(self):
    self.body = [Vector2(5,no_cell/2), Vector2(4,no_cell/2), Vector2(3,no_cell/2)]
    self.direction = Vector2(1,0)
    self.new_block = False
    self.start_hue = 0.0  
    self.end_hue = 0.7    
    self.num_steps = 20  

  def generate_gradient(self, start_hue, end_hue, num_steps):
    hues = []
    for i in range(num_steps):
      hue = start_hue + (end_hue - start_hue) * (i / (num_steps - 1))
      hues.append(hue % 1.0)  
    colours = [colorsys.hsv_to_rgb(hue, 1.0, 1.0) for hue in hues]

    return colours

  def draw_snake(self):
    colours = self.generate_gradient(self.start_hue, self.end_hue, 
  self.num_steps)
    for rgb in colours:   
     for block in self.body:
       x_pos = int(block.x * cell_size)
       y_pos = int(block.y * cell_size)
       block_rect = pygame.Rect(x_pos + grid_border, y_pos + 
  heading_border + grid_border, cell_size, cell_size)
       rgb = tuple(int(value * 255) for value in rgb)
       pygame.draw.rect(screen, rgb, block_rect)

当我运行此代码时,出现以下错误: “pygame.draw.rect(屏幕,rgb,block_rect) ValueError:无效的颜色参数”


遇到的错误是因为在 pygame.draw.rect() 中传递了一个无效的 rgb 值。这可能是由于以下代码行导致的:

rgb = tuple(int(value * 255) for value in rgb)

这里的问题是正在迭代 rgb 元组本身,并将每个值 (r、g、b) 乘以 255,然后尝试将其转换为整数。这将导致超出 0 到 255 范围的值,而 Pygame 不允许这样做。

以下是如何修复代码以正确应用渐变的方法:

import pygame
import colorsys
from pygame.math import Vector2

class Snake:
    def __init__(self):
        self.body = [Vector2(5, no_cell / 2), Vector2(4, no_cell / 2), Vector2(3, no_cell / 2)]
        self.direction = Vector2(1, 0)
        self.new_block = False
        self.start_hue = 0.0
        self.end_hue = 0.7
        self.num_steps = len(self.body)  # 渐变步骤数应与蛇身段数一致

    def generate_gradient(self, start_hue, end_hue, num_steps):
        hues = [start_hue + (end_hue - start_hue) * (i / (num_steps - 1)) for i in range(num_steps)]
        colours = [colorsys.hsv_to_rgb(hue, 1.0, 1.0) for hue in hues]
        return colours

    def draw_snake(self):
        colours = self.generate_gradient(self.start_hue, self.end_hue, self.num_steps)
        for i, block in enumerate(self.body):
            x_pos = int(block.x * cell_size)
            y_pos = int(block.y * cell_size)
            block_rect = pygame.Rect(x_pos + grid_border, y_pos + heading_border + grid_border, cell_size, cell_size)
            rgb = tuple(int(value * 255) for value in colours[i])  # 获取当前段的颜色
            pygame.draw.rect(screen, rgb, block_rect)

更改:

  1. 渐变步骤数: 我们将 self.num_steps 设置为 len(self.body) ,以便每个蛇身段都获得唯一的颜色。
  2. 颜色应用: draw_snake 中,我们使用 enumerate 迭代蛇身段及其索引。然后,我们使用索引 i colours 列表中获取相应的颜色。
  3. 颜色转换: 我们只在绘制每个段时才将当前段的颜色 colours[i] 转换为 RGB 元组。

通过这些更改,代码现在应该能够正常工作,并为蛇身创建平滑的渐变效果。

标签:python,colors,pygame
From: 78326655

相关文章

  • 无法编译 Arduino ESP32 代码:.../python3: exec 格式错误
    昨天我使用MacOSArduinoIDE或VSCode编译Arduino草图没有任何问题。但今天什么也编译不了。我尝试在ArduinoIDE或带有Arduino扩展的VSCode中编译的任何草图都会出现此错误:fork/exec/Library/Frameworks/Python.framework/Versions/3.11/bin/python3:exec......
  • 用Python解析邮件日志
    我的任务有点困难。我有一个邮件日志,如:Oct315:30:18mail1postfix/lmtp[5369]:DB10242054:to=<XXXXX>,orig_to=<XXXXXX>,relay=ip[ip]:port,delay=1.4,delays=0.04/0/0.01/1.4,dsn=2.0.0,status=sent(2502.0.0fromMTA(smtp:[iP]:port):2502.0.0Ok:queueda......
  • Python,Pyinstaller打包含taichi模块的程序
    Python版本3.9、taichi版本1.7.1,pyinstaller版本6.9.0问题描述:正常Pyinstaller打包后报错[Taichi]version1.7.1,llvm15.0.1,commit0f143b2f,win,python3.9.19[Taichi]Startingonarch=x64Traceback(mostrecentcalllast):File"taichi\lang\_wrap_inspec......
  • Python,运行Yolo项目,报错AttributeError: ‘ImageDraw‘ object has no attribute ‘te
    Python3.9问题描述:其他电脑已经运行成功的Python,YOLO代码到我电脑上运行报错Traceback(mostrecentcalllast): File"C:\Users\Administrator\Desktop\20240725\识别项目\predict.py",line122,in<module>  frame=np.array(yolo.detect_image(frame)) Fil......
  • Python从零开始制做文字游戏(荒岛求生)
    文章目录前言开发游戏《荒岛求生》游戏大纲背景内容通关条件游戏过程探索荒岛购买物资休息总结代码开发定义变量当前代码引入背景故事当前代码循环问题解决:函数当前代码制作延时当前代码制作a函数(探索荒岛阶段)展示数......
  • 使用 Python 进行数据分析:入门指南
    使用Python进行数据分析:入门指南1.简介本指南将介绍如何使用Python进行数据分析,涵盖从数据加载到可视化分析的各个方面。2.必要的库NumPy:用于数值计算和数组操作。Pandas:用于数据处理和分析,提供DataFrame结构。Matplotlib:用于数据可视化,创建各种图表。Seab......
  • IT实战课堂计算机毕业设计源码精品基于Python的高校教育教材采购出入库进销存储信息管
    项目功能简介:《[含文档+PPT+源码等]精品基于Python的高校教育教材信息管理系统设计与实现》该项目含有源码、文档、PPT、配套开发软件、软件安装教程、项目发布教程、包运行成功以及课程答疑与微信售后交流群、送查重系统不限次数免费查重等福利!软件开发环境及开发工具:开......
  • 为什么我的 Python 脚本失败并出现 TypeError?
    我正在编写一个Python脚本,该脚本应该计算数字列表的总和。但是,当我运行代码时遇到TypeError这是一个最小的例子:numbers=[1,2,3,'4']total=sum(numbers)print(total)Theerrormessageis:TypeError:unsupportedoperandtype(s)for+:'int'and'str......
  • 如何通过socks代理传递所有Python的流量?
    有如何通过http代理传递所有Python的流量?但是,它不处理sock代理。我想使用sock代理,我们可以通过ssh隧道轻松获得它。ssh-D5005user@server你可以使用socks库,让你的Python代码通过SOCKS代理传递所有流量。这个库可以让你在套接字级别上指定代......
  • 如何在streamlit python中流式传输由LLM生成的输出
    代码:fromlangchain_community.vectorstoresimportFAISSfromlangchain_community.embeddingsimportHuggingFaceEmbeddingsfromlangchainimportPromptTemplatefromlangchain_community.llmsimportLlamaCppfromlangchain.chainsimportRetrievalQAimports......