簡體   English   中英

Python / PyGame從列表中選擇一個隨機布爾值

[英]Python/PyGame Select a Random Boolean From List

Python版本:2.7.8

目標:使用PyGame庫在python上進行掃雷游戲(至少嘗試)。

編碼:

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

pygame.init()
width, height = 400, 400
clock = pygame.time.Clock()
DRAWSURF = pygame.display.set_mode((width, height))
pygame.display.set_caption("Matt's Minesweeper")
background = pygame.Surface(DRAWSURF.get_size())
background.fill((255, 255, 255))
DRAWSURF.blit(background, (0, 0))
pygame.display.flip()
board = []


class Square():
    isMine = None

    val = 0
    count = 0

    def draw(self):
        BLACK = (0, 0, 0)
        val = self.val
        count = self.count
        x = 100 + val * 60
        y = 0 + 60 * count
        pygame.draw.rect(DRAWSURF, BLACK, (x, y, 60, 60), 5)
        return self.isMine



class DrawBoard():

    def draw(self, grid):
        item = Square()
        for i in range(0, grid):
            item.val = i
            select = item.draw()
            board.append(select)
            for j in range(grid):
                item.count = j
                select_2 = item.draw()
                board.append(select_2)

class MineSet():
    temp = Square()
    def mineSet(self, mines):
        temp = self.temp
        for i in range(0, mines):
            test = random.choice(board)




while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    clock.tick(30)

    # Insert drawings here
    game = DrawBoard()
    game.draw(5)
    print board
    pygame.display.update()

問題:我將每個單獨的正方形作為自己的對象,如類Square()所示。 在Square類的draw函數中,它返回布爾值None(變量isMine),稍后當我在DrawBoard類中調用它時,它將對象附加到列表“ board”上。 要為游戲分配地雷,我想隨機選擇一個創建的Square對象,並將布爾值從None更改為True。 也許這不是分配地雷的最佳方法,但是我正在盡力而為。 任何幫助表示贊賞。

只是生成介於0len(list)之間的隨機值。 然后,您可以使用以下語法訪問該值: list[random_val]如果要更改值: list[random_val] = True

 from collections import OrderedDict
 from random import sample

class Square():
    def __init__(self):
        self.val = 0
        self.count = 0
    def draw(self):
        BLACK = (0, 0, 0)
        x = 100 + self.val * 60
        y = 0 + 60 * self.count
        pygame.draw.rect(DRAWSURF, BLACK, (x, y, 60, 60), 5)


class DrawBoard():
    def __init__(self, grid, mines): # size of grid and how many mines to set
        self.grid_size = grid
        # create x,y coordinates and set all mains to False initially
        self.board = OrderedDict(((i,j),False) for i in range(grid) for j in range(grid))      
        self.mines = mines
        # pick random coords to place mines
        samp = sample(list(self.board),self.mines)
        for k in samp:
            self.board[k]=True
    def draw(self):
        item = Square()
        for i, j in self.board:
            item.val, item.count = i,j
            item.draw()

game = DrawBoard(5,5) # create board
game.draw() # draw

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    clock.tick(30)
   # game logic goes here
    pygame.display.update()

這應該可以幫助您入門,您需要讓用戶知道他們在地雷附近時如何處理以及何時贏得:

import pygame, sys
from pygame.locals import *

pygame.init()
width, height = 40, 40
clock = pygame.time.Clock()
DRAWSURF = pygame.display.set_mode((width, height))
pygame.display.set_caption("Matt's Minesweeper")
background = pygame.Surface(DRAWSURF.get_size())
DRAWSURF.blit(background, (0, 0))
pygame.display.flip()
size = [255, 255]
screen = pygame.display.set_mode(size)

margin = 5

from collections import OrderedDict
from random import sample


class DrawBoard():
    def __init__(self, grid, mines):
        self.grid_size = grid
        self.board = OrderedDict(((i, j), False) for i in range(grid) for j in range(grid))
        self.mines = mines
        samp = sample(list(self.board), self.mines)
        for k in samp:
            self.board[k] = True

    def draw(self):
        for i, j in self.board:
            x = 100 + i * 60
            y = 0 + 60 * j
            pygame.draw.rect(DRAWSURF,(0,0,0), (x, y, 60, 60), margin)


game = DrawBoard(5, 5)
game.draw()


def game_over():
    font = pygame.font.SysFont(None, 50)
    text = font.render('Game over!', True, (255, 0, 0), (255, 255, 255))
    text_rect = text.get_rect()
    text_rect.centerx = screen.get_rect().centerx
    text_rect.centery = screen.get_rect().centery
    screen.blit(text, text_rect)
    pygame.display.update()
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()


user_won = False
user_lost = False

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.MOUSEBUTTONDOWN:
            # get mouse pos 
            pos = pygame.mouse.get_pos()
            # change to grid coordinates
            column = pos[0] // (width + margin)
            row = pos[1] // (height + margin)
            print(game.board[row, column])
            if game.board[row, column]:
                user_lost = True
            else:
                game.board[row, column] = "picked"

    if user_lost:
        game_over()

    screen.fill((0, 0, 0))
    for row, column in game.board:
        color = (255, 255, 255)
        if game.board[row, column] == "picked":
            color = (0, 255, 0)
        pygame.draw.rect(screen,
                         color,
                         [(margin + width) * column + margin,
                          (margin + height) * row + margin,
                          width,
                          height])

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

    pygame.display.update()

如果您希望通過“教程”了解該程序的實現,則可以在ActiveState的Python Cookbook上查看此MineSweep食譜。 該代碼的版本2引入了__push__build_mines方法來處理各個地雷的創建。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM