创建简单的python游戏——按钮函数

我正在创建一个简单的 python 游戏,在其中,一个角色四处移动以收集物品。我创建了四处移动的角色,当他们经过一个项目(图像)时,会弹出文本询问他们是否要拿起该项目以及说“是”和“否”的按钮。

如果他们点击是,该项目应该消失,然后他们返回游戏。如果他们单击否,该项目将保留在那里,他们应该返回游戏。为了摆脱这个项目,我试图在没有他们收集的项目的情况下重新绘制屏幕。但是,我不知道点击是或否后如何返回游戏。如果按钮功能将它们返回到,game_loop()则该redrawGameWindow()功能将激活,将角色移回其起始位置并返回项目。有谁知道如何解决这个问题/在我的按钮中放置什么功能?谢谢!


跃然一笑
浏览 106回答 1
1回答

MMTTMM

我会这样做的方法是为一个对象创建一个类,然后创建对象并将它们放在一个列表中,当你绘制窗口时,循环遍历列表并绘制每个对象,如果你想“摆脱”一个对象,将其从列表中删除,如果要添加对象,将其添加到列表中这是一个例子class Object:&nbsp; &nbsp; def __init__(self, x, y, image):&nbsp; &nbsp; &nbsp; &nbsp; self.x = x&nbsp; &nbsp; &nbsp; &nbsp; self.y = y&nbsp; &nbsp; &nbsp; &nbsp; self.image = image&nbsp; &nbsp; &nbsp; &nbsp; self.rect = image.get_rect()&nbsp; &nbsp; &nbsp; &nbsp; self.rect.topleft = (self.x, self.y)objs = []objs.append(Object(100, 100, swordIMG))objs.append(Object(300, 400, staffIMG))objs.append(Object(200, 340, chestIMG))def redrawGameWindow():&nbsp; &nbsp; for obj in objs:&nbsp; &nbsp; &nbsp; &nbsp; win.blit(obj.image, obj.rect)def game_loop():&nbsp; &nbsp; while run:&nbsp; &nbsp; &nbsp; &nbsp; for obj in reversed(objs): #if delete obj in list while looping through it, the loop will still try to get the deleted obj, so reverse to fix this&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if obj.rect.collidpoint((x + vel, y + vel)):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; collect_item(obj) #give the object so we know which one to deletedef button(msg,x,y,w,h,ic,ac, action=None, arg = None):&nbsp; mouse = pygame.mouse.get_pos()&nbsp; click = pygame.mouse.get_pressed()&nbsp; pygame.draw.rect(win, ic, (x,y,w,h))&nbsp; &nbsp; #print(mouse)&nbsp; if x + w > mouse[0] > x and y+h > mouse[1] > y:&nbsp; &nbsp; pygame.draw.rect(win, ac, (x,y,w,h))&nbsp; &nbsp; if click[0] == 1 and action != None:&nbsp; &nbsp; &nbsp; if arg:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;action(arg)&nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;action()&nbsp; else:&nbsp; &nbsp; pygame.draw.rect(win, ic, (x,y,w,h))&nbsp; smallText = pygame.font.Font("Gameplay.ttf", 20)&nbsp; textSurf, textRect = text_objects(msg, smallText)&nbsp; textRect.center = ((x+(w/2), y+(h/2)))&nbsp; win.blit(textSurf, textRect)def collect_items(obj):&nbsp; button("YES",150,450,100,50,green, bright_green, remove_image,obj)&nbsp; button("NO",550,450,100, 50, red, bright_red)&nbsp; message_display('Do you want to pick up item?')def remove_image(obj):&nbsp; &nbsp; del objs[objs.index(obj)]按钮功能看起来不错,我最近尝试在这里为 pygame 制作一个可自定义但简单的按钮,如果你想要一些灵感的话import timeimport sysimport pygame#we need to initiate pygame at the start of all our codepygame.init()display_width = 800display_height = 600#creating window, in tuple is width and height of screenwin = pygame.display.set_mode((display_width, display_height))x = (display_width * 0.45)y = (display_height * 0.8)black = (0,0,0)white = (255,255,255)red = (200,0,0)green = (0,200,0)bright_red = (255, 0, 0)bright_green = (0,255,0)purple = (183,52,235)pink = (255, 209, 237)blue = (184, 243, 255)bright_blue = (120, 232, 255)bright_pink = (247, 148, 208)transparent = (0, 0, 0, 0)#allows us to change our fps in the gameclock = pygame.time.Clock()swordIMG = pygame.Surface((40,40))swordIMG.fill((255,0,0))staffIMG = swordIMGchestIMG = swordIMGcoinIMG = swordIMG#good idea to create a screen width variablescreenWidth = 800#Name of our windowpygame.display.set_caption("First Game")#Code for importing multiple images of the animated spriteimg = pygame.Surface((50,50))img.fill((0,255,0))#walk right animationwalkRight = [img, img, img]#walk left animationwalkLeft = walkRight#back ground image load inbg = pygame.Surface((800,800))bg.fill((255,255,255))#Basic standing sprite, it is the still image. shows this character when they are not movingchar = pygame.Surface((50,50))char.fill((0,255,0))#velocity is how fast the character movesvel = 5left = Falseright = FalsewalkCount = 0&nbsp;#creating characterx = 60y = 450#width and height of spritewidth = 100&nbsp;height = 100#staffstaffwidth = 94staffheight = 106#coincoinwidth = 74coinheight = 74#chestchestwidth = 84chestheight = 84class Object:&nbsp; &nbsp; def __init__(self, x, y, image):&nbsp; &nbsp; &nbsp; &nbsp; self.x = x&nbsp; &nbsp; &nbsp; &nbsp; self.y = y&nbsp; &nbsp; &nbsp; &nbsp; self.image = image&nbsp; &nbsp; &nbsp; &nbsp; self.rect = image.get_rect()&nbsp; &nbsp; &nbsp; &nbsp; self.rect.topleft = (self.x, self.y)objs = []objs.append(Object(600, 400, swordIMG))objs.append(Object(70, 60, staffIMG))objs.append(Object(600, 100, chestIMG))objs.append(Object(350, 300, coinIMG))can_pickup = Trueprev_frame_over_Object = Falsedef crash():&nbsp; &nbsp; message_display('Item collected')#buttondef button(msg,x,y,w,h,ic,ac, action=None, arg=None):&nbsp; &nbsp; mouse = pygame.mouse.get_pos()&nbsp; &nbsp; click = pygame.mouse.get_pressed()&nbsp; &nbsp; pygame.draw.rect(win, ic, (x,y,w,h))&nbsp; &nbsp; #print(mouse)&nbsp; &nbsp; if x + w > mouse[0] > x and y+h > mouse[1] > y:&nbsp; &nbsp; &nbsp; &nbsp; pygame.draw.rect(win, ac, (x,y,w,h))&nbsp; &nbsp; &nbsp; &nbsp; if click[0] == 1 and action != None:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if arg:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; action(arg)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; action()&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; pygame.draw.rect(win, ic, (x,y,w,h))&nbsp; &nbsp; &nbsp; &nbsp; smallText = pygame.font.Font(pygame.font.match_font('calibri'), 20)&nbsp; &nbsp; &nbsp; &nbsp; textSurf, textRect = text_objects(msg, smallText)&nbsp; &nbsp; &nbsp; &nbsp; textRect.center = ((x+(w/2), y+(h/2)))&nbsp; &nbsp; &nbsp; &nbsp; win.blit(textSurf, textRect)def NO():&nbsp; &nbsp; global can_pickup&nbsp; &nbsp; can_pickup = Falsedef collect_item(obj):&nbsp; &nbsp; button("YES",150,450,100,50,green, bright_green, remove_image, obj)&nbsp; &nbsp; message_display('Do you want to pick up item?')&nbsp; &nbsp; button("NO",550,450,100, 50, red, bright_red, NO)def puff(x,y):&nbsp; &nbsp; win.blit(char (x,y))def text_objects(text, font):&nbsp; &nbsp; textSurface = font.render(text, True, black)&nbsp; &nbsp; return textSurface, textSurface.get_rect()def message_display(text):&nbsp; &nbsp; largeText = pygame.font.Font('freesansbold.ttf', 115)&nbsp; &nbsp; TextSurf, TextRect = text_objects(text, largeText)&nbsp; &nbsp; TextRect.center = ((display_width/2)), ((display_height/2))&nbsp; &nbsp; win.blit(TextSurf, TextRect)def quitgame():&nbsp; &nbsp; pygame.quit()&nbsp; &nbsp; quit()def game_intro():&nbsp; &nbsp; intro = True&nbsp; &nbsp; while intro:&nbsp; &nbsp; &nbsp; &nbsp; for event in pygame.event.get():&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if event.type == pygame.QUIT:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pygame.quit()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; quit()&nbsp; &nbsp; &nbsp; &nbsp; win.fill(white)&nbsp; &nbsp; &nbsp; &nbsp; largeText = pygame.font.Font(pygame.font.match_font('calibri'), 115)&nbsp; &nbsp; &nbsp; &nbsp; TextSurf, TextRect = text_objects("Title", largeText)&nbsp; &nbsp; &nbsp; &nbsp; TextRect.center = ((display_width/2)), ((display_height/2))&nbsp; &nbsp; &nbsp; &nbsp; win.blit(TextSurf, TextRect)&nbsp; &nbsp; &nbsp; &nbsp; #Button&nbsp; &nbsp; &nbsp; &nbsp; button("GO!",150,450,100,50, blue, bright_blue, game_loop)&nbsp; &nbsp; &nbsp; &nbsp; button("Quit",550,450,100, 50, pink, bright_pink, quitgame)&nbsp; &nbsp; &nbsp; &nbsp; pygame.display.update()def remove_image(obj):&nbsp; &nbsp; del objs[objs.index(obj)]#function which redraws the game window, this area is for drawing, we do not draw in main loopdef redrawGameWindow():&nbsp; &nbsp; global walkCount&nbsp; &nbsp; win.blit(bg, (0,0)) #back ground image&nbsp; &nbsp; for obj in objs:&nbsp; &nbsp; &nbsp; &nbsp; win.blit(obj.image, obj.rect)&nbsp; &nbsp; if walkCount + 1 >= 0:&nbsp; &nbsp; &nbsp; &nbsp; walkCount = 0&nbsp; &nbsp; if left:&nbsp; &nbsp; &nbsp; &nbsp; win.blit(walkLeft[walkCount], (x,y)) #displaying walk left sprite&nbsp; &nbsp; &nbsp; &nbsp; walkCount += 1&nbsp; &nbsp; elif right:&nbsp; &nbsp; &nbsp; &nbsp; win.blit(walkRight[walkCount], (x,y))&nbsp; &nbsp; &nbsp; &nbsp; walkCount += 1&nbsp; &nbsp; #repeat for up and down&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; win.blit(char, (x,y)) #if we are not moving we blit our characterdef game_loop():&nbsp;&nbsp; &nbsp; global x, y, left, right, up, down, walkCount, prev_frame_over_Object, can_pickup&nbsp; &nbsp; x_change = 0&nbsp; &nbsp; dodged = 0&nbsp; &nbsp; run = True&nbsp; &nbsp; while run:&nbsp; &nbsp; &nbsp; &nbsp; #redrawGameWindow()&nbsp; &nbsp; &nbsp; &nbsp; #game_intro()&nbsp; &nbsp; &nbsp; &nbsp; clock.tick(27) #sets fps to 20 seconds&nbsp; &nbsp; &nbsp; &nbsp; #pygame.time.delay(100) #clock in pgyame, parameter is milliseconds&nbsp; &nbsp; &nbsp; &nbsp; for event in pygame.event.get(): #event is what player does eg. mouse click or key press&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if event.type == pygame.QUIT: #if they click the x button (quit)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; run = False #loop = false&nbsp; &nbsp; &nbsp; &nbsp; #using arrow keys to move shape&nbsp; &nbsp; &nbsp; &nbsp; # all of the and's mean the shape cannot move off the screen&nbsp; &nbsp; &nbsp; &nbsp; keys = pygame.key.get_pressed()&nbsp; &nbsp; &nbsp; &nbsp; if keys[pygame.K_LEFT] and x > vel:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; x -= vel&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; left = True&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; right = False&nbsp; &nbsp; &nbsp; &nbsp; elif keys[pygame.K_RIGHT] and x < 800 - width - vel: #screen width - width of character&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; x += vel&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; right = True&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; left = False&nbsp; &nbsp; &nbsp; &nbsp; elif keys[pygame.K_UP] and y > vel:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; y -= vel&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; up = True&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; down = False&nbsp; &nbsp; &nbsp; &nbsp; elif keys[pygame.K_DOWN] and y <&nbsp; 600 - height - vel:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; y += vel&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; down = True&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; up = False&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; right = False&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; left = False&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; up = False&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; down = False&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; walkCount = 0&nbsp; &nbsp; &nbsp; &nbsp; redrawGameWindow()&nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; is_over = False&nbsp; &nbsp; &nbsp; &nbsp; for obj in reversed(objs): #if delete obj in list while looping through it, the loop will still try to get the deleted obj, so reverse to fix this&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if obj.rect.collidepoint((x + vel, y + vel)):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; is_over = True&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if prev_frame_over_Object == False:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; can_pickup = True&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if can_pickup:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; collect_item(obj) #give the object so we know which one to delete&nbsp; &nbsp; &nbsp; &nbsp; prev_frame_over_Object = is_over&nbsp; &nbsp; &nbsp; &nbsp; pygame.display.update() #if we want something to show on the screen in pygame, we must update the screengame_intro()pygame.quit #game ends```}这段代码有效,我发现你在文本显示中有 time.sleep 所以 fps 下降到每秒半帧,但是一旦它出来并且我移动了绘图的顺序,一切似乎都有效,我没有图像你有所以我把它们改成了正方形,它们在顶部,不要复制粘贴它们
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python