Invalid destination position for blit как исправить

The wrong info is: Traceback (most recent call last): File "C:Documents and SettingsAdministrator.MICRO-C17310A13桌面pygame例子vectorfish.py", line 24, in screen.blit(sprite,

The wrong info is:

Traceback (most recent call last):
  File "C:Documents and SettingsAdministrator.MICRO-C17310A13桌面pygame例子vectorfish.py", line 24, in <module>
    screen.blit(sprite, position)
TypeError: invalid destination position for blit

The code is:

background_image_filename = 'sushiplate.jpg'    
sprite_image_filename = 'fugu.bmp'    
import pygame    
from pygame.locals import *    
from sys import exit    
from vector2 import Vector2    
pygame.init()    
screen = pygame.display.set_mode((640, 480), 0, 32)    
background = pygame.image.load(background_image_filename).convert()    
sprite = pygame.image.load(sprite_image_filename).convert_alpha()    
clock = pygame.time.Clock()

position = Vector2(100.0, 100.0)

speed = 250.0

heading = Vector2()

while True:

    for event in pygame.event.get():
        if event.type == QUIT:
            exit()
    if event.type == MOUSEBUTTONDOWN:
        destination = Vector2(*event.pos) - Vector2(*sprite.get_size())/2.
        heading = Vector2.from_points(position, destination)
        heading.normalize()
    screen.blit(background, (0,0))
    screen.blit(sprite, position)
    time_passed = clock.tick()
    time_passed_seconds = time_passed / 1000.0
    distance_moved = time_passed_seconds * speed
    position += heading * distance_moved
    pygame.display.update()

The code of vector2 is:

import math

class Vector2(object):

    def __init__(self, x=0.0, y=0.0):
        self.x = x
        self.y = y
    def __str__(self):
        return "(%s, %s)"%(self.x, self.y)
    @staticmethod
    def from_points(P1, P2):
        return Vector2( P2[0] - P1[0], P2[1] - P1[1] )
    def get_magnitude(self):
        return math.sqrt( self.x**2 + self.y**2 )
    def normalize(self):
        magnitude = self.get_magnitude()
        self.x /= magnitude
        self.y /= magnitude

Not only this code,but all the codes that needs vector2 met this question:
invalid destination position for blit

am I doing something wrong ?

Any help is much needed.

Gilbert chan

Please help. I’ve been searching but i still don’t quite grasp how to fix the problem. I don’t know if i;m forgetting something or the values of x and y are not considered int’s for some reason (i have put in past tries to fix it: int(x))

I want to create the dinosaur game from Google, but the .blit of the «Hidrante» class is failing (but the player one is functioning). I have put it normal values instead of self.x and self.y but still get the problem, i’ve tried to said it x and y are ints, tried to change the names, the image i’m loading, and replicate the code of the player but doesn’t seem to work.

here is all the code

import pygame


pygame.init()

window = pygame.display.set_mode((1000, 1000))

pygame.display.set_caption("Dinosaurio")

clock = pygame.time.Clock()
char = pygame.image.load('dino.png')
bg = pygame.image.load('bg2.jpg')
img = pygame.image.load("H2.jpg")


class Player(object):
#values of player
    def __init__(self, x, y, width, height):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.vel = 5
        self.isJump = False
        self.jumpCount = 10
        self.hitbox = (self.x + 20, self.y, 30, 64)
#putting the player on screem
    def draw(self, window):
        window.blit(char, (self.x, self.y))
        self.hitbox = (self.x + 20, self.y, 30, 64)
        pygame.draw.rect(window, (255, 0, 0), self.hitbox, 2)

#Obstacle
class Hidrante(object):

    def __init__(self, x, y, width, height):
        self.x = x
        self.y = y
        self.width = width
        self. height = height
        self.vel = 8
        self.hitbox = (self.x + 17, self.y + 2, 31, 57)
        self.walkCount = 10
        self.path = 0
#putting the obstacle in screem
    def draw(self, win):
        if self.walkCount + 1 >= 33: #fill code, trying things not actual util
            self.walkCount = 0

        if self.vel > 0:
            window.blit(img, (self.x, self.y)) #here is the problem
            self.walkCount += 1
        else:
            window.blit(img, (self.x, self.y))#these too
            self.walkCount += 1
        self.hitbox = (self.x + 17, self.y + 2, 30, 60)  
        pygame.draw.rect(window, (255, 0, 0), self.hitbox, 2)


def gmv():
#putting on creem the objects
    window.blit(bg, (0, 0))
    dino.draw(window)
    hidrante.draw(window)
    pygame.display.update()

#creating the objects
dino = Player(110, 620, 64, 64)
hidrante = Hidrante(1100, 620, 64, 64)
run = True
neg = 1
while run:
    clock.tick(30) #frames
    hidrante.x = (hidrante.x ** 2) * -1 #Function to not jump infinit.

    for event in pygame.event.get():
        if event.type == pygame.QUIT: 
            run = False
#Space to jump
    keys = pygame.key.get_pressed()

    if not (dino.isJump):
        if keys[pygame.K_SPACE]:
            dino.isJump = True
    else:
        if dino.jumpCount >= -10:
            dino.y -= (dino.jumpCount * abs(dino.jumpCount)) * 0.5
            dino.jumpCount -= 1
        else:
            dino.jumpCount = 10
            dino.isJump = False

    gmv()


pygame.quit()

i’ve only want to know the reason why the values of object are interfering with .blit and learn how to fix it.

Please help. I’ve been searching but i still don’t quite grasp how to fix the problem. I don’t know if i;m forgetting something or the values of x and y are not considered int’s for some reason (i have put in past tries to fix it: int(x))

I want to create the dinosaur game from Google, but the .blit of the «Hidrante» class is failing (but the player one is functioning). I have put it normal values instead of self.x and self.y but still get the problem, i’ve tried to said it x and y are ints, tried to change the names, the image i’m loading, and replicate the code of the player but doesn’t seem to work.

here is all the code

import pygame


pygame.init()

window = pygame.display.set_mode((1000, 1000))

pygame.display.set_caption("Dinosaurio")

clock = pygame.time.Clock()
char = pygame.image.load('dino.png')
bg = pygame.image.load('bg2.jpg')
img = pygame.image.load("H2.jpg")


class Player(object):
#values of player
    def __init__(self, x, y, width, height):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.vel = 5
        self.isJump = False
        self.jumpCount = 10
        self.hitbox = (self.x + 20, self.y, 30, 64)
#putting the player on screem
    def draw(self, window):
        window.blit(char, (self.x, self.y))
        self.hitbox = (self.x + 20, self.y, 30, 64)
        pygame.draw.rect(window, (255, 0, 0), self.hitbox, 2)

#Obstacle
class Hidrante(object):

    def __init__(self, x, y, width, height):
        self.x = x
        self.y = y
        self.width = width
        self. height = height
        self.vel = 8
        self.hitbox = (self.x + 17, self.y + 2, 31, 57)
        self.walkCount = 10
        self.path = 0
#putting the obstacle in screem
    def draw(self, win):
        if self.walkCount + 1 >= 33: #fill code, trying things not actual util
            self.walkCount = 0

        if self.vel > 0:
            window.blit(img, (self.x, self.y)) #here is the problem
            self.walkCount += 1
        else:
            window.blit(img, (self.x, self.y))#these too
            self.walkCount += 1
        self.hitbox = (self.x + 17, self.y + 2, 30, 60)  
        pygame.draw.rect(window, (255, 0, 0), self.hitbox, 2)


def gmv():
#putting on creem the objects
    window.blit(bg, (0, 0))
    dino.draw(window)
    hidrante.draw(window)
    pygame.display.update()

#creating the objects
dino = Player(110, 620, 64, 64)
hidrante = Hidrante(1100, 620, 64, 64)
run = True
neg = 1
while run:
    clock.tick(30) #frames
    hidrante.x = (hidrante.x ** 2) * -1 #Function to not jump infinit.

    for event in pygame.event.get():
        if event.type == pygame.QUIT: 
            run = False
#Space to jump
    keys = pygame.key.get_pressed()

    if not (dino.isJump):
        if keys[pygame.K_SPACE]:
            dino.isJump = True
    else:
        if dino.jumpCount >= -10:
            dino.y -= (dino.jumpCount * abs(dino.jumpCount)) * 0.5
            dino.jumpCount -= 1
        else:
            dino.jumpCount = 10
            dino.isJump = False

    gmv()


pygame.quit()

i’ve only want to know the reason why the values of object are interfering with .blit and learn how to fix it.

Неправильная информация:

Traceback (most recent call last):
  File "C:Documents and SettingsAdministrator.MICRO-C17310A13桌面pygame例子vectorfish.py", line 24, in <module>
    screen.blit(sprite, position)
TypeError: invalid destination position for blit

Код:

background_image_filename = 'sushiplate.jpg'    
sprite_image_filename = 'fugu.bmp'    
import pygame    
from pygame.locals import *    
from sys import exit    
from vector2 import Vector2    
pygame.init()    
screen = pygame.display.set_mode((640, 480), 0, 32)    
background = pygame.image.load(background_image_filename).convert()    
sprite = pygame.image.load(sprite_image_filename).convert_alpha()    
clock = pygame.time.Clock()

position = Vector2(100.0, 100.0)

speed = 250.0

heading = Vector2()

while True:

    for event in pygame.event.get():
        if event.type == QUIT:
            exit()
    if event.type == MOUSEBUTTONDOWN:
        destination = Vector2(*event.pos) - Vector2(*sprite.get_size())/2.
        heading = Vector2.from_points(position, destination)
        heading.normalize()
    screen.blit(background, (0,0))
    screen.blit(sprite, position)
    time_passed = clock.tick()
    time_passed_seconds = time_passed / 1000.0
    distance_moved = time_passed_seconds * speed
    position += heading * distance_moved
    pygame.display.update()

Код вектора2:

import math

class Vector2(object):

    def __init__(self, x=0.0, y=0.0):
        self.x = x
        self.y = y
    def __str__(self):
        return "(%s, %s)"%(self.x, self.y)
    @staticmethod
    def from_points(P1, P2):
        return Vector2( P2[0] - P1[0], P2[1] - P1[1] )
    def get_magnitude(self):
        return math.sqrt( self.x**2 + self.y**2 )
    def normalize(self):
        magnitude = self.get_magnitude()
        self.x /= magnitude
        self.y /= magnitude

Не только этот код, но и все коды, которым нужен vector2, отвечали на этот вопрос: недопустимая позиция назначения для blit

Я делаю что-то неправильно ?

Любая помощь очень нужна.

Гилберт Чан

2 ответа

Лучший ответ

Surface.blit ожидает tuple в качестве dest параметр. если вы хотите работать со своим собственным векторным классом, измените его следующим образом:

class Vector2(tuple):

    def __new__(typ, x=1.0, y=1.0):
        n = tuple.__new__(typ, (int(x), int(y)))
        n.x = x
        n.y = y
        return n

    def __mul__(self, other):
        return self.__new__(type(self), self.x*other, self.y*other)

    def __add__(self, other):
        return self.__new__(type(self), self.x+other.x, self.y+other.y)

    def __str__(self):
        return "(%s, %s)"%(self.x, self.y)
    @staticmethod
    def from_points(P1, P2):
        return Vector2( P2[0] - P1[0], P2[1] - P1[1] )
    def get_magnitude(self):
        return math.sqrt( self.x**2 + self.y**2 )
    def normalize(self):
        magnitude = self.get_magnitude()
        self.x /= magnitude
        self.y /= magnitude

Теперь это подклассы из tuple, и вы можете передать его в функцию blit. (Также обратите внимание, что кортеж должен содержать int s).

Я также добавил __add__ и __mul__, чтобы он поддерживал сложение и умножение.

Таким образом, никаких дополнительных изменений в вашем коде не требуется, и вы можете использовать свой векторный класс по назначению.


4

sloth
11 Сен 2012 в 09:00

Попробуйте следующее:

screen.blit(sprite, (position.x, position.y))

Проблема в том, что ваш Vector2 не имеет перегрузки для __iter__, который является итератором, поэтому вы можете вызывать tuple для вашего объекта. Это означает, что он не может быть преобразован в кортеж с помощью вызова функции blit и, следовательно, параметр недопустим.

Ваш Vector2 будет содержать:

def __iter__(self):
        return [self.x, self.y].__iter__()

И твой блин был бы

screen.blit(sprite, tuple(position))


2

Konstantin Dinev
11 Сен 2012 в 08:37

Я слежу за учебным пособием на YouTube о том, как создать игру о космических захватчиках, но столкнулся с проблемой, из-за которой я получаю сообщение об ошибке: invalid destination position for blit, как я могу исправить эту ошибку? Спасибо.
Я использую python 3.10.4 с IDE spyder на домашнем компьютере с Windows 10.
Любой ответ очень ценится.

Консоль сообщает, что ошибка исходит из строки 54, в данном случае это код:

53> def enemy(x, y, i):
54>     screen.blit(enemyImg[i], (x, y))

Код:

import pygame
import random
import math

# Intiatize the pygame
pygame.init()

# Create the screen
screen = pygame.display.set_mode((800, 600))

# Background
background = pygame.image.load("background.png")

# Caption and Icon
pygame.display.set_caption("Space Invaders")
icon = pygame.image.load("icon.png")
pygame.display.set_icon(icon)

# Player
playerImg = pygame.image.load("player.png")
playerX = 370
playerY = 480
playerX_change = 0

# Enemy
enemyImg = []
enemyX = []
enemyY = []
enemyX_change = []
enemyY_change = []
num_of_enemies = 6

for i in range(num_of_enemies):
    enemyImg.append(pygame.image.load("enemy.png"))
    enemyX.append(random.randint(0, 735))
    enemyY.append(random.randint(50, 150))
    enemyX_change.append(0.1)
    enemyY_change.append(40)

# Bullet1
bullet1Img = pygame.image.load("bullet1.png")
bullet1X = 0
bullet1Y = 480
bullet1X_change = 0
bullet1Y_change = 0.5
bullet_state = "ready"

score = 0

def player(x, y):
    screen.blit(playerImg, (x, y))
    
def enemy(x, y, i):
    screen.blit(enemyImg[i], (x, y))
    
def fire_bullet1(x, y): 
    global bullet_state
    bullet_state = "fire"
    screen.blit(bullet1Img, (x, y + 10))
    
def isCollision(enemyX, enemyY, bullet1X, bullet1Y):
    distance = math.sqrt(math.pow(enemyX-bullet1X,2)) + (math.pow(enemyY-bullet1Y,2))
    if distance < 27:
        return True
    else:
        return False

# Game Loop
running = True
while running:
    screen.fill((255, 255, 255))
    # Background Image
    screen.blit(background, (0,0))
    
    # Checking for boundaries of spaceship
    playerX += playerX_change
    
    if playerX <=0:
        playerX = 0
    elif playerX >=736:
        playerX = 736
    
    # Enemy Movement
    for i in range(num_of_enemies):
        enemyX[i] += enemyX_change[i]
        if enemyX[i] <=0:
            enemyX_change[i] = 0.1
            enemyY[i] += enemyY_change[i]
        elif enemyX[i] >=736:
            enemyX_change[i] = -0.1
            enemyY[i] += enemyY_change[i]
            
        # Collision
        collision = isCollision(enemyX[i], enemyY[i], bullet1X, bullet1Y)
        if collision:
            bullet1Y = 480
            bullet_state = "ready"
            score += 1
            print(score)
            enemyX[i] = random.randint(0, 735)
            enemyY[i] = random.randint(50, 150)
            
        enemy(enemyX[i], enemyY[i], i)
        
    # Bullet Movement
    if bullet1Y <=0:
        bullet1Y = 480
        bullet_state = "ready"
        
    if bullet_state is "fire":
        fire_bullet1(bullet1X, bullet1Y)
        bullet1Y -= bullet1Y_change
    
    player(playerX, playerY)
    enemy(enemyX, enemyY, i)
    pygame.display.update()
    
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
            pygame.quit()
            
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                playerX_change = -0.3
            if event.key == pygame.K_RIGHT:
                playerX_change = +0.3
            if event.key == pygame.K_SPACE:
                if bullet_state is "ready":
                    bullet1X = playerX
                    fire_bullet1(bullet1X, bullet1Y)
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                playerX_change = 0 

I’m new to python, and can’t fix this. When trying to run my game, I get this error:

Traceback (most recent call last):
  File "C:Userssoni801DocumentsGitHubvolleyballPlayer.py", line 15, in draw
    window.blit(pygame.image.load("player.png"), 100, 100)
TypeError: invalid destination position for blit

I know other people that have done very similar code without getting this error, and I have no idea why i am getting this.

How do I fix this? I’ve tried changing literally every single variable, with no luck. Any help appreciated. Here is my code:

In Game.py:

import pygame

from Player import Player

running = True
clock = pygame.time.Clock()

# Images
background = pygame.image.load("bg.png")

# Global variables
WIDTH = 800
HEIGHT = 600

# Player variables
player_size = 70
player_pos = [(WIDTH / 4) - (player_size / 2), HEIGHT - player_size]
player_speed = 5
jump_height = 22

jumping = False
jump_time = -jump_height

window = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Volleyball")

player = Player(player_pos, player_size, player_speed, jump_height, pygame.image.load("player.png"))


def tick():
    player.movement()


def render():
    window.blit(background, (0, 0))

    player.draw(window)

    pygame.display.update()


if __name__ == '__main__':
    while running:
        clock.tick(60)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

        tick()
        render()

pygame.quit()

In Player.py:

import pygame


class Player(object):
    def __init__(self, pos, size, speed, jump_height, image):
        self.jump_height = jump_height
        self.speed = speed
        self.pos = pos
        self.image = image

        self.jumping = False
        self.jump_time = -jump_height

    def draw(self, window):
        window.blit(self.image, self.pos[0], self.pos[1])

    def movement(self):
        keys = pygame.key.get_pressed()

        if keys[pygame.K_a] and self.pos[0] > 0:
            self.pos[0] -= self.speed
        if keys[pygame.K_d] and self.pos[0] < 800 - self.pos:
            self.pos[0] += self.speed
        if not self.jumping:
            if keys[pygame.K_SPACE]:
                self.jumping = True
        else:
            if self.jump_time <= self.jump_height:
                self.pos[1] += self.jump_time
                self.jump_time += 1
            else:
                self.jumping = False
                self.jump_time = -self.jump_height

Понравилась статья? Поделить с друзьями:
  • Invalid data about errors перевод ошибка obd
  • Invalid data about errors ошибка авто
  • Invalid d3d version error reinstall directx 9
  • Invalid d2s header section at offset 0 как исправить
  • Invalid credentials supplied steam как исправить