Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 显示列表中的某个元素_Python_List_Selection - Fatal编程技术网

Python 显示列表中的某个元素

Python 显示列表中的某个元素,python,list,selection,Python,List,Selection,现在,我们的代码从左上角开始创建一个网格,从左到右逐行填充行和列。目前,它可以从一堆图像中挑选。它是使用一些IF语句设置的,这些语句在形状和稀有形状之间进行选择。我想弄清楚的是如何改变代码,这样我就可以决定什么样的稀有物种产生,而不是随机挑选一个稀有物种。对Python还是新手,从其他语言中找到很多对我有意义的小东西在Python中不起作用,所以这让我有点不舒服 编辑: 这是完整的代码。由cactusbin编写并由Gareth Rees修订的基本代码 import pygame, random,

现在,我们的代码从左上角开始创建一个网格,从左到右逐行填充行和列。目前,它可以从一堆图像中挑选。它是使用一些IF语句设置的,这些语句在形状和稀有形状之间进行选择。我想弄清楚的是如何改变代码,这样我就可以决定什么样的稀有物种产生,而不是随机挑选一个稀有物种。对Python还是新手,从其他语言中找到很多对我有意义的小东西在Python中不起作用,所以这让我有点不舒服

编辑:

这是完整的代码。由cactusbin编写并由Gareth Rees修订的基本代码

import pygame, random, time, sys
from pygame.locals import *
import itertools
import os

WHITE = (255, 255, 255)
BLACK = (0, 0, 0)

SHAPE_WIDTH = 64                # Width of each shape (pixels).
SHAPE_HEIGHT = 64               # Height of each shape (pixels).
PUZZLE_COLUMNS = 10              # Number of columns on the board.
PUZZLE_ROWS = 11                # Number of rows on the board.
MARGIN = 118                     # Margin around the board (pixels).
WINDOW_WIDTH = PUZZLE_COLUMNS * SHAPE_WIDTH + 2 * MARGIN + 485
WINDOW_HEIGHT = PUZZLE_ROWS * SHAPE_HEIGHT + 2 * MARGIN - 150
FONT_SIZE = 60
TEXT_OFFSET = MARGIN + 950

# Map from number of matches to points scored.
MINIMUM_MATCH = 10
EXTRA_LENGTH_POINTS = .1
RANDOM_POINTS = .3
DELAY_PENALTY_SECONDS = 1
DELAY_PENALTY_POINTS = 0

FPS = 30
EXPLOSION_SPEED = 15            # In frames per second.
SPIN_SPEED = 15
REFILL_SPEED = 10               # In cells per second.

VERTICAL = False

class Cell(object):
"""
A cell on the board, with properties:
`image` -- a `Surface` object containing the sprite to draw here.
`offset` -- vertical offset in pixels for drawing this cell.
"""
def __init__(self, image):
    self.offset = 0.0
    self.image = image

def tick(self, dt):
    self.offset = max(0.0, self.offset - dt * REFILL_SPEED)

class Board(object):
"""
A rectangular board of cells, with properties:
`w` -- width in cells.
`h` -- height in cells.
`size` -- total number of cells.
`board` -- list of cells.
`matches` -- list of matches, each being a list of exploding cells.
`refill` -- list of cells that are moving up to refill the board.
`score` -- score due to chain reactions.
"""
def __init__(self, width, height):
    self.explosion = [pygame.image.load('images/explosion{}.png'.format(i))
                      for i in range(1, 7)]
    self.spin = [pygame.image.load('images/powerframe{}.png'.format(i))
                  for i in range (1, 12)]
    self.image_color = {}
    self.shapes = []
    self.rareshapes = []

    colors = 'red blue yellow'
    letters = 'acgtu'

    for c in colors.split():
        im = pygame.image.load('images/{}.png'.format(c))
        self.shapes.append(im)
        self.image_color[im] = c
        for l in letters:
            im = pygame.image.load('rareimages/{}{}.png'.format(c, l))
            self.rareshapes.append(im)
            self.image_color[im] = l

    self.background = pygame.image.load("images/bg.png")
    self.blank = pygame.image.load("images/blank.png")
    self.x = pygame.image.load("images/x.png")
    self.w = width
    self.h = height
    self.size = width * height
    self.board = [Cell(self.blank) for _ in range(self.size)]
    self.matches = []
    self.refill = []
    self.score = 0.0
    self.spin_time = 15


def randomize(self):
    """
    Replace the entire board with fresh shapes.
    """
    rare_shapes = [1, 9, 23, 27, 40, 42, 50, 56, 70, 81, 90]

    for i in range(self.size):
        if i in rare_shapes:
            self.board[i] = Cell(random.choice(self.rareshapes))
        else:
            self.board[i] = Cell(random.choice(self.shapes))

def pos(self, i, j):
    """
    Return the index of the cell at position (i, j).
    """
    assert(0 <= i < self.w)
    assert(0 <= j < self.h)
    return j * self.w + i

def busy(self):
    """
    Return `True` if the board is busy animating an explosion or a
    refill and so no further swaps should be permitted.
    """
    return self.refill or self.matches

def tick(self, dt):
    """
    Advance the board by `dt` seconds: move rising blocks (if
    any); otherwise animate explosions for the matches (if any);
    otherwise check for matches.
    """
    if self.refill:
        for c in self.refill:
            c.tick(dt)
        self.refill = [c for c in self.refill if c.offset > 0]
        if self.refill:
            return
    elif self.matches:
        self.explosion_time += dt
        f = int(self.explosion_time * EXPLOSION_SPEED)
        if f < len(self.explosion):
            self.update_matches(self.explosion[f])
            return
        self.update_matches(self.blank)
        self.refill = list(self.refill_columns())
    self.explosion_time = 0
    self.matches = self.find_matches()

def draw(self, display):
    """
    Draw the board on the pygame surface `display`.
    """
    display.blit(self.background, (0, 0))
    for i, c in enumerate(self.board):
        display.blit(c.image,
                     (MARGIN + SHAPE_WIDTH * (i % self.w),
                      MARGIN + SHAPE_HEIGHT * (i // self.w - c.offset) - 68))
    display.blit(self.x, (995, 735))
    display.blit(self.x, (1112, 735))
    display.blit(self.x, (1228, 735))

def swap(self, cursor):
    """
    Swap the two board cells covered by `cursor` and update the
    matches.
    """
    i = self.pos(*cursor)
    b = self.board
    b[i], b[i+1] = b[i+1], b[i]
    self.matches = self.find_matches()


def find_matches(self):
    """
    Search for matches (lines of cells with identical images) and
    return a list of them, each match being represented as a list
    of board positions.
    """
    def lines():
        for j in range(self.h):
            yield range(j * self.w, (j + 1) * self.w)
        for i in range(self.w):
            yield range(i, self.size, self.w)
    def key(i):
        return self.image_color.get(self.board[i].image)
    def matches():
        for line in lines():
            for _, group in itertools.groupby(line, key):
                match = list(group)
                if len(match) >= MINIMUM_MATCH:
                    yield match
                    self.score = self.score + 1
    return list(matches())

def update_matches(self, image):
    """
    Replace all the cells in any of the matches with `image`.
    """
    for match in self.matches:
        for position in match:
            self.board[position].image = image

def refill_columns(self):
    """
    Move cells downwards in columns to fill blank cells, and
    create new cells as necessary so that each column is full. Set
    appropriate offsets for the cells to animate into place.
    """
    for i in range(self.w):
        target = self.size - i - 1
        for pos in range(target, -1, -self.w):
            if self.board[pos].image != self.blank:
                c = self.board[target]
                c.image = self.board[pos].image
                c.offset = (target - pos) // self.w
                target -= self.w
                yield c
        offset = 1 + (target - pos) // self.w
        for pos in range(target, -1, -self.w):
            c = self.board[pos]
            c.image = random.choice(self.shapes)
            c.offset = offset
            yield c

class Game(object):
"""
The state of the game, with properties:
`clock` -- the pygame clock.
`display` -- the window to draw into.
`font` -- a font for drawing the score.
`board` -- the board of cells.
`cursor` -- the current position of the (left half of) the cursor.
`score` -- the player's score.
`last_swap_ticks` -- 
`swap_time` -- time since last swap (in seconds).
"""
def __init__(self):
    pygame.init()
    pygame.display.set_caption("Nucleotide")
    self.clock = pygame.time.Clock()
    self.display = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT),
                                           DOUBLEBUF)
    self.board = Board(PUZZLE_COLUMNS, PUZZLE_ROWS)
    self.font = pygame.font.Font(None, FONT_SIZE)

def start(self):
    """
    Start a new game with a random board.
    """
    self.board.randomize()
    self.cursor = [0, 0]
    self.score = 0.0
    self.swap_time = 125

def quit(self):
    """
    Quit the game and exit the program.
    """
    pygame.quit()
    sys.exit()

def play(self):
    """
    Play a game: repeatedly tick, draw and respond to input until
    the QUIT event is received.
    """
    self.start()
    while True:
        self.draw()
        dt = min(self.clock.tick(FPS) / 1000, 1 / FPS)
        self.swap_time -= dt
        for event in pygame.event.get():
            if event.type == KEYUP:
                self.input(event.key)
            elif event.type == QUIT:
                self.quit()
            elif self.swap_time == 0:
                self.quit()
        self.board.tick(dt)

def input(self, key):
    """
    Respond to the player pressing `key`.
    """
    if key == K_q:
        self.quit()
    elif key == K_RIGHT and self.cursor[0] < self.board.w - 2:
        self.cursor[0] += 1
    elif key == K_LEFT and self.cursor[0] > 0:
        self.cursor[0] -= 1
    elif key == K_DOWN and self.cursor[1] < self.board.h - 1:
        self.cursor[1] += 1
    elif key == K_UP and self.cursor[1] > 0:
        self.cursor[1] -= 1
    elif key == K_SPACE and not self.board.busy():
        self.swap()

def swap(self):
    """
    Swap the two cells under the cursor and update the player's score.
    """
    self.board.swap(self.cursor)

def draw(self):
    self.board.draw(self.display)
    self.draw_score()
    self.draw_time()
    if VERTICAL == False:
        self.draw_cursor()
    elif VERTICAL == True:
        self.draw_cursor2()
    pygame.display.update()

def draw_time(self):
    s = int(self.swap_time)
    text = self.font.render(str(int(s/60)) + ":" + str(s%60).zfill(2),
                            True, BLACK)
    self.display.blit(text, (TEXT_OFFSET, WINDOW_HEIGHT - 170))

def draw_score(self):
    total_score = self.score

def draw_cursor(self):
    topLeft = (MARGIN + self.cursor[0] * SHAPE_WIDTH,
            MARGIN + self.cursor[1] * SHAPE_HEIGHT - 68)
    topRight = (topLeft[0] + SHAPE_WIDTH * 2, topLeft[1])
    bottomLeft = (topLeft[0], topLeft[1] + SHAPE_HEIGHT)
    bottomRight = (topRight[0], topRight[1] + SHAPE_HEIGHT)
    pygame.draw.lines(self.display, WHITE, True,
            [topLeft, topRight, bottomRight, bottomLeft], 3)

if __name__ == '__main__':
    Game().play()
import pygame,random,time,sys
从pygame.locals导入*
进口itertools
导入操作系统
白色=(255,255,255)
黑色=(0,0,0)
SHAPE_WIDTH=64#每个形状的宽度(像素)。
形状高度=64#每个形状的高度(像素)。
拼图_COLUMNS=10#板上的列数。
拼图行数=11#板上的行数。
边距=118#电路板周围的边距(像素)。
窗口宽度=拼图列*形状宽度+2*边距+485
窗口高度=拼图行*形状高度+2*边距-150
字体大小=60
文本偏移量=边距+950
#将比赛次数映射到得分。
最小匹配=10
额外长度点=.1
随机_点=.3
延迟\惩罚\秒=1
延迟\惩罚\分数=0
FPS=30
爆炸速度=每秒15帧。
旋转速度=15
重新填充速度=每秒10个单元。
垂直=假
类单元格(对象):
"""
电路板上的一个单元,具有以下属性:
`图像“”--一个“表面”对象,其中包含要在此处绘制的精灵。
`偏移量“---绘制此单元格的垂直偏移量(以像素为单位)。
"""
定义初始化(自我,图像):
self.offset=0.0
self.image=image
def勾选(自身,dt):
自偏移=最大值(0.0,自偏移-dt*加注速度)
班级委员会(对象):
"""
矩形电池板,具有以下特性:
`w`--单元格中的宽度。
`h`--单元格中的高度。
`size`--单元格的总数。
`board`--单元格列表。
`matches`--匹配项列表,每个匹配项都是正在分解的单元格列表。
`重新填充`--正在向上移动以重新填充电路板的单元列表。
`得分`--因连锁反应而得分。
"""
定义初始值(自身、宽度、高度):
self.explosion=[pygame.image.load('images/explosion{}.png'。格式(i))
对于范围(1,7)内的i)]
self.spin=[pygame.image.load('images/powerframe{}.png'.format(i))
对于范围(1,12)内的i)
self.image_color={}
self.shapes=[]
self.rareshapes=[]
颜色='红蓝黄'
字母='acgtu'
对于颜色中的c.split():
im=pygame.image.load('images/{}.png'.format(c))
self.shapes.append(im)
self.image_color[im]=c
对于字母形式的l:
im=pygame.image.load('rareimages/{}{}{}.png'。格式(c,l))
self.rareshapes.append(im)
自映像颜色[im]=l
self.background=pygame.image.load(“images/bg.png”)
self.blank=pygame.image.load(“images/blank.png”)
self.x=pygame.image.load(“images/x.png”)
self.w=宽度
self.h=高度
self.size=宽度*高度
self.board=[单元格(self.blank)用于uu范围内(self.size)]
self.matches=[]
self.refill=[]
self.score=0.0
self.spin_time=15
def随机化(自我):
"""
用新的形状替换整个电路板。
"""
稀有_形=[1,9,23,27,40,42,50,56,70,81,90]
对于范围内的i(自身尺寸):
如果我在罕见的形状:
self.board[i]=单元格(随机选择(self.rareshapes))
其他:
self.board[i]=单元格(随机选择(self.shapes))
def位置(自身、i、j):
"""
返回位于(i,j)位置的单元格索引。
"""
断言(0=最小匹配:
产量匹配
self.score=self.score+1
返回列表(匹配项())
def更新_匹配(自身、图像):
"""
将任何匹配项中的所有单元格替换为“image”。
"""
对于self.matches中的匹配:
在比赛中的位置:
self.board[position].image=image
def加注_列(自身):
"""
在列中向下移动单元格以填充空白单元格,以及
根据需要创建新单元格,以便每列都已满。Set
要设置动画的单元的适当偏移。
"""
对于范围内的i(self.w):
目标=self.size-i-1
对于范围内的位置(目标,-1,-self.w):
如果self.board[pos].image!=self.blank:
c=自我董事会[目标]
c、 image=self.board[pos]。image
c、 偏移量=(目标位置)//self.w
目标-=self.w
产量c
偏移量=1+(目标位置)//self.w
对于范围内的位置(目标,-1,-self.w):
c=自板[pos]
c、 image=random.choice(self.shapes)
c、 偏移量=偏移量
产量c
班级游戏(对象):
"""
游戏状态,具有以下属性:
`时钟`--游戏时钟。
`显示“---要绘制到其中的窗口。
`font`--用于绘制分数的字体。
`板`--单元板。
`光标“”--光标(左半部分)的当前位置。
`得分`--球员的得分。
`最后一次交换勾号`--
`swap_time`--自上次交换以来的时间(以秒为单位)。
"""
定义初始化(自):
pygame.init()
pygame.display.set_标题(“核苷酸”)
self.clock=pygame.time.clock()
self.display=pygame.display.set_模式((窗口宽度、窗口高度),
双BUF)
self.board=board(拼图列、拼图行)
self.font=pygame.font.font(无,字体大小)
def启动(自):
"""
使用随机棋盘开始新游戏。
"""
self.board.randomize()
self.cursor=[0,0]
self.score=0.0
self.swap_time=125
def退出(自我):
"""
def randomize(self):
    """
    Replace the entire board with fresh shapes.
    """

    specials = dict((x, self.rareshapes) for x in (9, 23, 27))
    get_shape_source = lambda x: specials.get(x, self.shapes) 

    for i in xrange(min(self.size, 41)):
        self.board[i] = Cell(random.choice(get_shape_source(i)))
from collections import ordereddict

def load_images(self)  
    self.image_color = {}
    self.shapes = []
    self.rareshapes = ordereddict()

    colors = 'red',  'blue', 'yellow'
    letters = 'acgtu'

    for c in colors:
        im = pygame.image.load('images/{}.png'.format(c))
        self.shapes.append(im)
        self.image_color[im] = c
        for l in letters:
            im = pygame.image.load('rareimages/{}{}.png'.format(c, l))
            self.rareshapes.[(c, l)] = im
            self.image_color[im] = l

def randomize(self):
    """
    Replace the entire board with fresh shapes.
    """

    raremap = {
       # spot index : rareshape
       9: ('red', 'a')],  
       23: ('blue', 'u'), 
       27: ('yellow', 'g') 
       }

    for i in xrange(self.size):
        if i in raremap:
            im = self.rareshapes[raremap[i]]
        else:
            im = random.choice(self.shapes)
        self.board[i] = Cell(im)
def randomize(self):
   """
   Replace the entire board with fresh shapes.
   """
   # locations we want to place a rare shape
   rare_shapes = [9, 23, 27]

   for i in range(self.size):
      if i in rare_shapes:
         self.board[i] = Cell(random.choice(self.rareshapes))
      else:
         self.board[i] = Cell (random.choice(self.shapes))