Pygame表面突然反转变数

Pygame surface suddenly inverting variables

我试图制作一个游戏,让你砍掉一些树并卖掉它,但在这样做的过程中我设法发现了一个令人心碎的错误——第一棵树会倒转所有其他树!我知道这没有意义,但我的意思是我已经将树分类为 class 并且我创建了一个名为 self.tree_property 的变量实例,它确定树是否已被砍伐或不是。当你砍倒第一棵树时,所有其他 tree_property 再次设置为 True。当你砍掉任何其他树时,第一棵树的 tree_property 再次设置为 True 谁能告诉我如何修复它,以及为什么会这样? 代码如下:

import pygame
import time
pygame.init()
print('Loading game...')
icon = pygame.image.load('C:\Program Files\Foraging Simulator\icon.png')
market = pygame.image.load('C:\Program Files\Foraging Simulator\market.png')
house = pygame.image.load('C:\Program Files\Foraging Simulator\house.png')
pygame.display.set_icon(icon)
market = pygame.transform.scale(market, (100, 100))
house = pygame.transform.scale(house, (100, 100))
root = pygame.display.set_mode((603, 573))
pygame.display.set_caption("Foraging Simulator")
window_is_open = True
white = (255, 255, 255)
black = (0, 0, 0)
width = 10
leaves_width = 30
height = 20
leaves_height = 10
x = 0
tree_trunk_x = 10
y = 0
tree_trunk_y = 10
vel = 5
brown = (150, 75, 0)
green = (58, 95, 11)
grass = (124, 252, 0)
score = 0
chop_wood = 'C:\Program Files\Foraging Simulator\chopping.mp3'
clock = pygame.time.Clock()
time = 0
happiness = 10
def test(string):
    print(string)
def reset_trees():
    for tree in trees:
        tree.tree_property = True
def open_house():
    reset_trees()
    score = 0
def open_market():
    happiness = score / 2
class Tree: # The class for the trees
    def __init__(self, tree_x, tree_y):
        self.tree_x = tree_x
        self.tree_y = tree_y
        self.tree_property = True # Creating instance tree_property
        self.trunk = None
        self.leaves = None
    def destroy(self):
        self.tree_property = False
    def create_tree(self):
        if self.tree_property:
            trunk_x = self.tree_x + 10
            trunk_y = self.tree_y + 10
            self.trunk = pygame.draw.rect(root, brown, (trunk_x, trunk_y, width, height))
            self.leaves = pygame.draw.rect(root, green, (self.tree_x, self.tree_y, leaves_width, leaves_height))
    def redraw(self):
        self.create_tree()
trees = []
for x in range(5):
    for y in range (5):
        trees.append(Tree(x*50, y*50))
root.fill(grass)
destroy_tree = None
countdown = 3
clock.tick(60)
say = True
print('Loading and attributes finsihed! Using mainloop...')
while window_is_open:
    if say:
        print('Mainloop loaded! Ready to go.')
        say = False
    time = pygame.time.delay(100)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            window_is_open = False
        if event.type == pygame.MOUSEBUTTONDOWN:
            mouse_x, mouse_y = event.pos
            if market.get_rect().collidepoint(mouse_x, mouse_y):
                dx = mouse_x - x
                dy = mouse_y - y
                if abs(dx) <= 50 and abs(dy) <= 50:
                    open_market()
            mouse_x, mouse_y = event.pos
            if house.get_rect().collidepoint(mouse_x, mouse_y):
                dx = mouse_x - x
                dy = mouse_y - y
                if abs(dx) <= 50 and abs(dy) <= 50:
                    open_house()
            for tree in trees: # Clicking detection
                mouse_x, mouse_y = pygame.mouse.get_pos()
                if tree.trunk.collidepoint(mouse_x, mouse_y):
                    dx = mouse_x - x
                    dy = mouse_y - y
                    if abs(dx) <= 50 and abs(dy) <= 50:
                        countdown = 3
                        destroy_tree = tree

    keys = pygame.key.get_pressed()
    if keys[pygame.K_RIGHT]:
        x += vel
    if keys[pygame.K_LEFT]:
        x -= vel
    if keys[pygame.K_UP]:
        y -= vel
    if keys[pygame.K_DOWN]:
        y += vel
    if destroy_tree != None:
        if countdown == 3:
            pygame.time.delay(950)
            countdown = countdown - 1
            pygame.mixer.music.load(chop_wood)
            pygame.mixer.music.play()
            while pygame.mixer.music.get_busy(): 
                pygame.time.Clock().tick(1)
        elif countdown > 0:
            pygame.mixer.music.load(chop_wood)
            pygame.mixer.music.play()
            while pygame.mixer.music.get_busy(): 
                pygame.time.Clock().tick(1)
            pygame.time.delay(950)
            countdown = countdown - 1
        else:
            destroy_tree.destroy()
            destroy_tree = None
            countdown = 3
            score = score + 1
    font = pygame.font.SysFont('Tahoma', 18, True, False)
    count = font.render(str(countdown), True, (0, 0, 0))
    screen_score = font.render("Score: " + str(score), True, (0, 0, 0))
    rendered_happiness = font.render("Happines: " + str(happiness), True, (0, 0, 0))
    root.blit(rendered_happiness, (410, 40))
    root.blit(count, (410, 0))
    root.blit(screen_score, (410, 20))
    rectangle = pygame.draw.rect(root, (0, 0, 0), (x, y, width, 10)) 
    for tree in trees:
        tree.redraw()
    root.blit(market, (400, 300))
    seconds = clock.tick()
    pre = time + seconds / 1000
    time = int(pre)
    root.blit(house, (400, 100))
    pygame.display.update()
    root.fill(grass)
pygame.quit()




谢谢!

A pygame.Surface object has no location. The position of the rectangle which is returned by get_rect() 总是 (0, 0).
请注意,当表面为 blit:

时指定位置
root.blit(house, (400, 100))

当您检索碰撞矩形时,您必须设置相同的位置。您可以将关键字参数值传递给此函数,这些值设置为 pygame.Rect 对象:

house.get_rect(topleft = (400, 100))

例如:

while window_is_open:
    # [...]

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

        if event.type == pygame.MOUSEBUTTONDOWN:
            mouse_x, mouse_y = event.pos
            dx = mouse_x - x
            dy = mouse_y - y

            if market.get_rect(topleft = (400, 300)).collidepoint(mouse_x, mouse_y):
                if abs(dx) <= 50 and abs(dy) <= 50:
                    open_market()

            if house.get_rect(topleft = (400, 100)).collidepoint(mouse_x, mouse_y):
                if abs(dx) <= 50 and abs(dy) <= 50:
                    open_house()

            for tree in trees:
                if tree.trunk.collidepoint(mouse_x, mouse_y):
                    if abs(dx) <= 50 and abs(dy) <= 50:
                        countdown = 3
                        destroy_tree = tree
    # [...]

此外,您必须在函数 open_market:

中使用 global statementhappiness 视为全局命名空间中的变量
def open_market():
    global happiness
    happiness = score / 2