在按钮游戏功能中插入分数 [英] Insert score in a button game function

查看:201
本文介绍了在按钮游戏功能中插入分数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可按下按钮的代码:

  def按钮(msg,xloc,yloc,xlong,ylong ,b1,b2,action =无):

hover = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()

如果xloc <悬停[0]< xloc + xlong和yloc<悬停[1]< yloc + ylong:
如果点击[0] == 1并且动作!=无:
,则显示
pygame.draw.rect(显示,b1,(xloc,yloc,xlong,ylong))
action()

else:
pygame.draw.rect(gameDisplay,inactiveButton,(xloc,yloc,xlong,ylong))
label = pygame.font.SysFont( arial,16)
textSurf,textBox = textMsg(msg,label)
textBox.center =((xloc +(300)),((yloc +(150))
gameDisplay。 blit(textSurf,textBox)

并且得分的代码是:

 用于pygame.event.get()中的事件:
if event.type == pygame.QUIT:
pygame.quit )
退出()

if event.type == pygame.MOUSEBUTTONDOWN:
score + = 1
print(score)

我想得到一个分数 - 按下正确的按钮以在测验游戏中回答 - ndash将显示并增加1.我该怎么做这是实现一个我知道的按钮的最简单的方法。

为按钮创建一个矩形,并使用 pygame.draw.rect (或者对图片进行blit)绘制矩形。对于碰撞检测,检查 pygame.MOUSEBUTTONDOWN 事件的 event.pos 是否与rect碰撞,然后只是增加得分变量。

 导入pygame为pg 


pg.init()
screen = pg.display.set_mode((640,480))

GRAY = pg.Color('gray15')
BLUE = pg.Color('dodgerblue1')


def main():
clock = pg.time.Clock()
font = pg .font.Font(None,30)
button_rect = pg.Rect(200,200,50,30)

得分= 0
完成= False

未完成:
为pg.event.get()中的事件:
如果event.type == pg.QUIT:
完成=真
如果事件。键入== pg.MOUSEBUTTONDOWN:
if event.button == 1:
if button_rect.collidepoint(event.pos):
print('Button pressed。')
得分+ = 1

screen.fill(GRAY)
pg.draw.rect(screen,BLUE,button_rect)
txt = font.render(str(score),True,BLUE)
screen.blit(txt,(260,206))

pg.display.flip()
clock.tick(30)


if __name__ =='__main__':
main()
pg.quit()






附录:其实,我会在类,精灵和精灵组的帮助下实现一个按钮。如果你不知道类和精灵是如何工作的,我建议查看

 导入pygame为pg 


pg.init()
GRAY = pg.Color('gray12')
BLUE = pg.Color('dodgerblue1')
FONT = pg.font。字体(无,30)


#Button是一个pygame精灵,这意味着我们可以将
#实例添加到一个精灵组中,然后更新并渲染它们
#通过调用`sprite_group.update()`和`sprite_group.draw(screen)`。
class Button(pg.sprite.Sprite):

def __init __(self,pos,callback):
pg.sprite.Sprite .__ init __(self)
self.image = pg.Surface((50,30))
self.image.fill(BLUE)
self.rect = self.image.get_rect(topleft = pos)
self。 callback = callback
$ b $ def handle_event(self,event):
处理从事件循环传递过来的事件。
if event.type == pg .MOUSEBUTTONDOWN:
如果self.rect.collidepoint(event.pos):
print('Button pressed。')
#调用我们在
#实例化过程中传递的函数。 (在这种情况下只是'increase_x`。)
self.callback()


类游戏:

def __init __(self):
self.screen = pg.display.set_mode((800,600))
self.clock = pg.time.Clock()

self.x = 0
self.button = Button((200,200),callback = self.increase_x)
self.buttons = pg.sprite.Group(self.button)
self.done = False

#我们传递给按钮实例的回调函数。
#如果检测到handle_event方法
#中发生冲突,它会被调用。
def increase_x(self):
如果按下按钮,则增加self.x.
self.x + = 1

def run( self):
而不是self.done:
self.handle_events()
self.run_logic()
self.draw()
self.clock.tick 30)

def handle_events(self):
for pg.event.get()中的事件:
if event.type == pg.QUIT:
self .done = True

for self.buttons中的按钮:
button.handle_event(event)

def run_logic(self):
self.buttons .update()

def draw(self):
self.screen.fill(GRAY)
self.buttons.draw(self.screen)
txt = FONT.render(str(self.x),True,BLUE)
self.screen.blit(txt,(260,206))

pg.display.flip()

$ b $ if if __name__ ==__main__:
Game()。run()
pg.quit()


I have this code for a button that is pressable:

def button(msg,xloc,yloc,xlong,ylong,b1,b2,action=None):

    hover = pygame.mouse.get_pos() 
    click = pygame.mouse.get_pressed()

    if xloc < hover [0] < xloc+xlong and yloc< hover [1] < yloc+ylong:
        pygame.draw.rect(display, b1, (xloc ,yloc ,xlong,ylong))
        if click [0]==1 and action != None:
            action()

    else:
        pygame.draw.rect(gameDisplay, inactiveButton, (xloc ,yloc ,xlong,ylong))
    label = pygame.font.SysFont("arial",16)
    textSurf, textBox = textMsg(msg, label)
    textBox.center = ((xloc +(300)),((yloc +(150))
    gameDisplay.blit(textSurf,textBox)

and the code for the scoring is:

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

    if event.type == pygame.MOUSEBUTTONDOWN:
        score+=1
        print (score)

I would like have a score that – upon pressing the correct button in the choices in order to answer in a quiz game – will be displayed and incremented by 1. How can I do that?

Here's the simplest way to implement a button that I know. Create a rect for the button and draw it with pygame.draw.rect (or blit an image). For the collision detection, check if the event.pos of a pygame.MOUSEBUTTONDOWN event collides with the rect and then just increment the score variable.

import pygame as pg


pg.init()
screen = pg.display.set_mode((640, 480))

GRAY = pg.Color('gray15')
BLUE = pg.Color('dodgerblue1')


def main():
    clock = pg.time.Clock()
    font = pg.font.Font(None, 30)
    button_rect = pg.Rect(200, 200, 50, 30)

    score = 0
    done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
            if event.type == pg.MOUSEBUTTONDOWN:
                if event.button == 1:
                    if button_rect.collidepoint(event.pos):
                        print('Button pressed.')
                        score += 1

        screen.fill(GRAY)
        pg.draw.rect(screen, BLUE, button_rect)
        txt = font.render(str(score), True, BLUE)
        screen.blit(txt, (260, 206))

        pg.display.flip()
        clock.tick(30)


if __name__ == '__main__':
    main()
    pg.quit()


Addendum: Actually, I would implement a button with the help of classes, sprites and sprite groups. If you don't know how classes and sprites work, I'd recommend to check out Program Arcade Games (chapter 12 and 13).

import pygame as pg


pg.init()
GRAY= pg.Color('gray12')
BLUE = pg.Color('dodgerblue1')
FONT = pg.font.Font(None, 30)


# The Button is a pygame sprite, that means we can add the
# instances to a sprite group and then update and render them
# by calling `sprite_group.update()` and `sprite_group.draw(screen)`.
class Button(pg.sprite.Sprite):

    def __init__(self, pos, callback):
        pg.sprite.Sprite.__init__(self)
        self.image = pg.Surface((50, 30))
        self.image.fill(BLUE)
        self.rect = self.image.get_rect(topleft=pos)
        self.callback = callback

    def handle_event(self, event):
        """Handle events that get passed from the event loop."""
        if event.type == pg.MOUSEBUTTONDOWN:
            if self.rect.collidepoint(event.pos):
                print('Button pressed.')
                # Call the function that we passed during the
                # instantiation. (In this case just `increase_x`.)
                self.callback()


class Game:

    def __init__(self):
        self.screen = pg.display.set_mode((800, 600))
        self.clock = pg.time.Clock()

        self.x = 0
        self.button = Button((200, 200), callback=self.increase_x)
        self.buttons = pg.sprite.Group(self.button)
        self.done = False

    # A callback function that we pass to the button instance.
    # It gets called if a collision in the handle_event method
    # is detected.
    def increase_x(self):
        """Increase self.x if button is pressed."""
        self.x += 1

    def run(self):
        while not self.done:
            self.handle_events()
            self.run_logic()
            self.draw()
            self.clock.tick(30)

    def handle_events(self):
        for event in pg.event.get():
            if event.type == pg.QUIT:
                self.done = True

            for button in self.buttons:
                button.handle_event(event)

    def run_logic(self):
        self.buttons.update()

    def draw(self):
        self.screen.fill(GRAY)
        self.buttons.draw(self.screen)
        txt = FONT.render(str(self.x), True, BLUE)
        self.screen.blit(txt, (260, 206))

        pg.display.flip()


if __name__ == "__main__":
    Game().run()
    pg.quit()

这篇关于在按钮游戏功能中插入分数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆