Pygame:初始菜单导致游戏循环

时间:2015-06-23 02:19:51

标签: python pygame

我正在制作this game的版本,而我正试图制作这样的起始菜单:
starting menu

我的计划是先做surface.fill(overlaycolor)然后将此图像显示在屏幕上。这将是一个循环。之后,在用户想要播放之后(将其保存为另一个问题),我们将进入另一个while循环。

我尝试过这样做,但它只是给了我一个黑屏。

这是我的代码:

import pygame, sys, random
from pygame.locals import *

# set up pygame
pygame.init()
mainClock = pygame.time.Clock()

# set up the window
width = 800
height = 600
thesurface = pygame.display.set_mode((width, height), 0, 32)
pygame.display.set_caption('')

bg = pygame.image.load("bg.png")
menu1 = pygame.image.load("menu1.png")

basicFont = pygame.font.SysFont('calibri', 36)

# set up the colors
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
overlay = (121, 126, 128)
playercolor = BLUE
# set up the player and food data structure
foodCounter = 0
NEWFOOD = 20
FOODSIZE = 10
splitting = False
player = pygame.draw.circle(thesurface, playercolor, (60, 250), 40)

foods = []
for i in range(20):
    foods.append(pygame.Rect(random.randint(0, width - FOODSIZE), random.randint(0, height - FOODSIZE), FOODSIZE, FOODSIZE))

# set up movement variables
moveLeft = False
moveRight = False
moveUp = False
moveDown = False

MOVESPEED = 10
size = 10
score = size
gameisplaying = False
while True:
    thesurface.fill(overlay)
    thesurface.blit(menu1, (400,400))
    for event in pygame.event.get():
        if event.type == pygame.MOUSEBUTTONUP:
            pos = pygame.mouse.get_pos()

            gameisplaying = True
    break
# run the game loop
while gameisplaying:
    thesurface.blit(bg, (0, 0))
    # check for events
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        if event.type == KEYDOWN:
            # change the keyboard variables
            if event.key == K_LEFT or event.key == ord('a'):
                moveRight = False
                moveLeft = True
            if event.key == K_RIGHT or event.key == ord('d'):
                moveLeft = False
                moveRight = True
            if event.key == K_UP or event.key == ord('w'):
                moveDown = False
                moveUp = True
            if event.key == K_DOWN or event.key == ord('s'):
                moveUp = False
                moveDown = True
            if event.key == K_SPACE and size >= 32: # XXX if size and space set splitting to true
                splitting = True
        if event.type == KEYUP:
            if event.key == K_ESCAPE:
                pygame.quit()
                sys.exit()
            if event.key == K_LEFT or event.key == ord('a'):
                moveLeft = False
            if event.key == K_RIGHT or event.key == ord('d'):
                moveRight = False
            if event.key == K_UP or event.key == ord('w'):
                moveUp = False
            if event.key == K_DOWN or event.key == ord('s'):
                moveDown = False
            if event.key == ord('x'):
                player.top = random.randint(0, height - player.height)
                player.left = random.randint(0, width - player.width)
        if event.type == MOUSEBUTTONUP:
            foods.append(pygame.Rect(event.pos[0], event.pos[1], FOODSIZE, FOODSIZE))



    foodCounter += 1
    if foodCounter >= NEWFOOD:
        # add new food
        foodCounter = 0
        foods.append(pygame.Rect(random.randint(0, width - FOODSIZE), random.randint(0, height - FOODSIZE), FOODSIZE, FOODSIZE))
    if 100>score>50:
        MOVESPEED = 9
    elif 150>score>100:
        MOVESPEED = 8
    elif 250>score>150:
        MOVESPEED = 6
    elif 400>score>250:
        MOVESPEED = 5
    elif 600>score>400:
        MOVESPEED = 3
    elif 800>score>600:
        MOVESPEED = 2
    elif score>800:
        MOVESPEED = 1
    # move the player
    if moveDown and player.bottom < height:
        player.top += MOVESPEED
    if moveUp and player.top > 0:
        player.top -= MOVESPEED
    if moveLeft and player.left > 0:
        player.left -= MOVESPEED
    if moveRight and player.right < width:
        player.right += MOVESPEED

    # splitting
    if not splitting:
        pygame.draw.circle(thesurface, playercolor, player.center, size)
    else:
        pygame.draw.circle(thesurface, playercolor,(player.centerx,player.centery),int(size/2))
        pygame.draw.circle(thesurface, playercolor,(player.centerx+size,player.centery+size),int(size/2))
    # check if the player has intersected with any food squares.
    for food in foods[:]:
        if player.colliderect(food):
            foods.remove(food)
            size+=1

    # draw the food
    for i in range(len(foods)):
        pygame.draw.rect(thesurface, GREEN, foods[i])

    printscore = basicFont.render("Score: %d" % size, True, (0,0,0))
    thesurface.blit(printscore, (10, 550))

    pygame.display.update()
    # draw the window onto the thesurface
    pygame.display.update()
    mainClock.tick(80)

非常感谢帮助!

1 个答案:

答案 0 :(得分:1)

我们来看看这段代码:

...
gameisplaying = False
while True:
    thesurface.fill(overlay)
    thesurface.blit(menu1, (400,400))
    for event in pygame.event.get():
        if event.type == pygame.MOUSEBUTTONUP:
            pos = pygame.mouse.get_pos()

            gameisplaying = True
    break
# run the game loop
while gameisplaying:
   ...

首先,您立即在第一次迭代结束时中断第一个while循环。所以你离开循环而没有将gameisplaying设置为True,这反过来意味着第二个while循环永远不会运行。

其次,您在第一个循环中在屏幕上绘制了一些内容,但是您从不致电pygame.display.flip()以使更改实际可见。

这是我在无聊时一起入侵的一个小例子。请注意当游戏处于MENU状态时,操作如何在后台进行,您可以通过单击鼠标切换到RUNNING状态:

import pygame
import math
import random
from collections import namedtuple
from itertools import cycle

def magnitude(v):
    return math.sqrt(sum(v[i]*v[i] for i in range(len(v))))

def add(u, v):
    return [(a+b) for (a, b) in zip(u, v)]

def sub(u, v):
    return [(a-b) for (a, b) in zip(u, v)]

def dot(u, v):
    return sum((a*b) for a, b in zip(u, v))

def normalize(v):
    vmag = magnitude(v)
    return [ v[i]/vmag  for i in range(len(v)) ]

def length(v):
  return math.sqrt(dot(v, v))

def angle(v1, v2):
  return math.acos(dot(v1, v2) / (length(v1) * length(v2)))

class Cell(object):

    id = 0

    def __init__(self, pos, color, speed, size, controller):
        self.x, self.y = pos
        self.speed = speed
        self.color = color
        self.size = size
        self.target_vector = [0, 0]
        self.controller = controller
        Cell.id += 1
        self.id = Cell.id

    @property
    def pos(self):
        return self.x, self.y

    @property
    def int_pos(self):
        return [int(v) for v in self.pos]

    @property
    def int_size(self):
        return int(self.size)

    def update(self, surroundings):

        if self.size > 6:
            self.size *= 0.999 

        eatting = [c for c in surroundings if can_a_eat_b(self, c)]
        for c in eatting:
            self.size += int(c.size / 2.5)

        if self.speed == 0: return eatting
        self.target_vector = self.controller(self, surroundings)
        if length(self.target_vector ) < 1: return eatting
        move_vector = [c * self.speed for c in normalize(self.target_vector)]
        self.x, self.y = add(self.pos, move_vector)
        return eatting

    def draw(self, s):
        pygame.draw.circle(s, self.color, self.int_pos, self.int_size)
        if not str(self.id).startswith('Food'):
            s.blit(write(str(self.id)), add(self.int_pos, (5, 5)))

def can_a_eat_b(a, b):
    return a.id != b.id and a.size > b.size and length(sub(a.pos, b.pos)) <= a.size + b.size

def player_controller(cell, surroundings):
    return sub(pygame.mouse.get_pos(), cell.pos)

colors = [c for c in pygame.color.THECOLORS.values()]
def rand_color(): 
    return random.choice(colors)

def rand_pos(rect):
    return random.randint(0, rect.width), random.randint(0, rect.height)

def food_controller(cell, surroundings):
    return (0, 0)

def food_factory(rect):
    cell = Cell(rand_pos(rect), rand_color(), 0, 5, food_controller)
    cell.id = 'Food' + str(cell.id)
    return cell

def ai_controller(cell, surroundings):
    targets = [(c, length(sub(cell.pos, c.pos))) for c in surroundings if c.size < cell.size and cell.id != c.id]
    targets_sorted = sorted(targets, key=lambda i: i[1])

    if targets_sorted:
        return sub(targets_sorted[0][0].pos, cell.pos)

    return (0, 0)

def ai_factory(rect):
    return Cell(rand_pos(rect), rand_color(), 0.7, 6, ai_controller)

Info = namedtuple('Info', ['size', 'pos', 'id'])

MENU, RUNNING = 0, 1

font = None
def write(text):
    return font.render(text, True, (0, 0, 0))

def main():    
    state = MENU
    pygame.init()
    global font
    font = pygame.font.SysFont('Consolas', 17)
    s = pygame.display.set_mode((800, 600))
    s_rect = s.get_rect()
    c = pygame.time.Clock()
    CREATEFOOD = pygame.USEREVENT + 1
    CREATEAI = pygame.USEREVENT + 2
    pygame.time.set_timer(CREATEFOOD, 1000)
    pygame.time.set_timer(CREATEAI, 3000)

    marquee = cycle(range(800))

    player = None
    for _ in range(10): pygame.event.post(pygame.event.Event(CREATEFOOD))
    for _ in range(4): pygame.event.post(pygame.event.Event(CREATEAI))

    actors = []

    while True:

        for e in pygame.event.get():
            if e.type == pygame.QUIT: return
            if e.type == CREATEFOOD: actors.append(food_factory(s_rect))
            if e.type == CREATEAI: actors.append(ai_factory(s_rect))
            if state == MENU:
                if e.type == pygame.MOUSEBUTTONUP: 
                    player = Cell((200, 200), rand_color(), 0.7, 6, player_controller)
                    actors.append(player)
                    player.id = 'Player'
                    state = RUNNING


        surroundings = [Info(c.size, c.int_pos, c.id) for c in actors]
        killed = []
        for ar in actors:
            for eaten in ar.update(surroundings):
                killed.append(eaten)

        actors = [a for a in actors if not a.id in [k.id for k in killed]]

        s.fill((255, 255, 255))

        for ar in actors:
            ar.draw(s)

        if state == MENU:
            s.blit(write('Click anywhere to start'), (next(marquee), 300))

        pygame.display.flip()
        c.tick(60)

if __name__ == '__main__':
    main()

enter image description here enter image description here

我希望你能有所启发。