python - Pygame表面突然反转变量

标签 python python-3.x pygame instance

这个问题在这里已经有了答案:





Why is my collision test always returning 'true' and why is the position of the rectangle of the image always wrong (0, 0)?

(1 个回答)


11 个月前关闭。




我试图制作一个游戏,你砍掉一些树然后卖掉它,但这样做时我设法找到了一个令人心碎的错误——第一棵树会反转所有其他树!我知道这没有意义,但我的意思是我已经将树分类到一个类中,并创建了一个名为 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()





谢谢!

最佳答案

pygame.Surface 对象没有位置。 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
    # [...]

此外,您必须使用 global statement治疗happiness作为函数中全局命名空间中的变量 open_market :

def open_market():
    global happiness
    happiness = score / 2

关于python - Pygame表面突然反转变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61921518/

相关文章:

python - Google AppEngine 应用程序版本

python - netstat 无法与 popen 一起正常工作

python - 如何处理 Jinja2 中的属性访问错误?

python - 文件和文件夹树的数据结构?

python - 为什么 import pygame_textinput 不起作用?

python - Pygame - 在某个特定时间渲染 Sprite

python - Pygame 和多处理策略

java - 解析未知的 XML 派生文件

Python安装工具: quick way to add scripts without "main" function as "console_scripts" entry points

python-3.x - 如何在 Python 中使用时区记录当前时间?