elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Estamos en la red social de Mastodon


+  Foro de elhacker.net
|-+  Programación
| |-+  Scripting
| | |-+  Hacer un tetris
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Hacer un tetris  (Leído 4,535 veces)
Meta


Desconectado Desconectado

Mensajes: 3.438



Ver Perfil WWW
Hacer un tetris
« en: 26 Enero 2011, 00:51 am »

Quiero hacer un tetris bajo Linux y python en modo consola.

He estado buscando por google pero son encuentro códigos para hacerlo sólo en modo consola, no modo visual como windows.
http://zetcode.com/wxpython/thetetrisgame/

Código
  1. #!/usr/bin/python
  2.  
  3. # tetris.py
  4.  
  5. import wx
  6. import random
  7.  
  8. class Tetris(wx.Frame):
  9.    def __init__(self, parent, id, title):
  10.        wx.Frame.__init__(self, parent, id, title, size=(180, 380))
  11.  
  12.        self.statusbar = self.CreateStatusBar()
  13.        self.statusbar.SetStatusText('0')
  14.        self.board = Board(self)
  15.        self.board.SetFocus()
  16.        self.board.start()
  17.  
  18.        self.Centre()
  19.        self.Show(True)
  20.  
  21.  
  22. class Board(wx.Panel):
  23.    BoardWidth = 10
  24.    BoardHeight = 22
  25.    Speed = 300
  26.    ID_TIMER = 1
  27.  
  28.    def __init__(self, parent):
  29.        wx.Panel.__init__(self, parent)
  30.  
  31.        self.timer = wx.Timer(self, Board.ID_TIMER)
  32.        self.isWaitingAfterLine = False
  33.        self.curPiece = Shape()
  34.        self.nextPiece = Shape()
  35.        self.curX = 0
  36.        self.curY = 0
  37.        self.numLinesRemoved = 0
  38.        self.board = []
  39.  
  40.        self.isStarted = False
  41.        self.isPaused = False
  42.  
  43.        self.Bind(wx.EVT_PAINT, self.OnPaint)
  44.        self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
  45.        self.Bind(wx.EVT_TIMER, self.OnTimer, id=Board.ID_TIMER)
  46.  
  47.        self.clearBoard()
  48.  
  49.    def shapeAt(self, x, y):
  50.        return self.board[(y * Board.BoardWidth) + x]
  51.  
  52.    def setShapeAt(self, x, y, shape):
  53.        self.board[(y * Board.BoardWidth) + x] = shape
  54.  
  55.    def squareWidth(self):
  56.        return self.GetClientSize().GetWidth() / Board.BoardWidth
  57.  
  58.    def squareHeight(self):
  59.        return self.GetClientSize().GetHeight() / Board.BoardHeight
  60.  
  61.    def start(self):
  62.        if self.isPaused:
  63.            return
  64.  
  65.        self.isStarted = True
  66.        self.isWaitingAfterLine = False
  67.        self.numLinesRemoved = 0
  68.        self.clearBoard()
  69.  
  70.        self.newPiece()
  71.        self.timer.Start(Board.Speed)
  72.  
  73.    def pause(self):
  74.        if not self.isStarted:
  75.            return
  76.  
  77.        self.isPaused = not self.isPaused
  78.        statusbar = self.GetParent().statusbar
  79.  
  80.        if self.isPaused:
  81.            self.timer.Stop()
  82.            statusbar.SetStatusText('paused')
  83.        else:
  84.            self.timer.Start(Board.Speed)
  85.            statusbar.SetStatusText(str(self.numLinesRemoved))
  86.  
  87.        self.Refresh()
  88.  
  89.    def clearBoard(self):
  90.        for i in range(Board.BoardHeight * Board.BoardWidth):
  91.            self.board.append(Tetrominoes.NoShape)
  92.  
  93.    def OnPaint(self, event):
  94.  
  95.        dc = wx.PaintDC(self)        
  96.  
  97.        size = self.GetClientSize()
  98.        boardTop = size.GetHeight() - Board.BoardHeight * self.squareHeight()
  99.  
  100.        for i in range(Board.BoardHeight):
  101.            for j in range(Board.BoardWidth):
  102.                shape = self.shapeAt(j, Board.BoardHeight - i - 1)
  103.                if shape != Tetrominoes.NoShape:
  104.                    self.drawSquare(dc,
  105.                        0 + j * self.squareWidth(),
  106.                        boardTop + i * self.squareHeight(), shape)
  107.  
  108.        if self.curPiece.shape() != Tetrominoes.NoShape:
  109.            for i in range(4):
  110.                x = self.curX + self.curPiece.x(i)
  111.                y = self.curY - self.curPiece.y(i)
  112.                self.drawSquare(dc, 0 + x * self.squareWidth(),
  113.                    boardTop + (Board.BoardHeight - y - 1) * self.squareHeight(),
  114.                    self.curPiece.shape())
  115.  
  116.  
  117.    def OnKeyDown(self, event):
  118.        if not self.isStarted or self.curPiece.shape() == Tetrominoes.NoShape:
  119.            event.Skip()
  120.            return
  121.  
  122.        keycode = event.GetKeyCode()
  123.  
  124.        if keycode == ord('P') or keycode == ord('p'):
  125.            self.pause()
  126.            return
  127.        if self.isPaused:
  128.            return
  129.        elif keycode == wx.WXK_LEFT:
  130.            self.tryMove(self.curPiece, self.curX - 1, self.curY)
  131.        elif keycode == wx.WXK_RIGHT:
  132.            self.tryMove(self.curPiece, self.curX + 1, self.curY)
  133.        elif keycode == wx.WXK_DOWN:
  134.            self.tryMove(self.curPiece.rotatedRight(), self.curX, self.curY)
  135.        elif keycode == wx.WXK_UP:
  136.            self.tryMove(self.curPiece.rotatedLeft(), self.curX, self.curY)
  137.        elif keycode == wx.WXK_SPACE:
  138.            self.dropDown()
  139.        elif keycode == ord('D') or keycode == ord('d'):
  140.            self.oneLineDown()
  141.        else:
  142.            event.Skip()
  143.  
  144.  
  145.    def OnTimer(self, event):
  146.        if event.GetId() == Board.ID_TIMER:
  147.            if self.isWaitingAfterLine:
  148.                self.isWaitingAfterLine = False
  149.                self.newPiece()
  150.            else:
  151.                self.oneLineDown()
  152.        else:
  153.            event.Skip()
  154.  
  155.  
  156.    def dropDown(self):
  157.        newY = self.curY
  158.        while newY > 0:
  159.            if not self.tryMove(self.curPiece, self.curX, newY - 1):
  160.                break
  161.            newY -= 1
  162.  
  163.        self.pieceDropped()
  164.  
  165.    def oneLineDown(self):
  166.        if not self.tryMove(self.curPiece, self.curX, self.curY - 1):
  167.            self.pieceDropped()
  168.  
  169.  
  170.    def pieceDropped(self):
  171.        for i in range(4):
  172.            x = self.curX + self.curPiece.x(i)
  173.            y = self.curY - self.curPiece.y(i)
  174.            self.setShapeAt(x, y, self.curPiece.shape())
  175.  
  176.        self.removeFullLines()
  177.  
  178.        if not self.isWaitingAfterLine:
  179.            self.newPiece()
  180.  
  181.  
  182.    def removeFullLines(self):
  183.        numFullLines = 0
  184.  
  185.        statusbar = self.GetParent().statusbar
  186.  
  187.        rowsToRemove = []
  188.  
  189.        for i in range(Board.BoardHeight):
  190.            n = 0
  191.            for j in range(Board.BoardWidth):
  192.                if not self.shapeAt(j, i) == Tetrominoes.NoShape:
  193.                    n = n + 1
  194.  
  195.            if n == 10:
  196.                rowsToRemove.append(i)
  197.  
  198.        rowsToRemove.reverse()
  199.  
  200.        for m in rowsToRemove:
  201.            for k in range(m, Board.BoardHeight):
  202.                for l in range(Board.BoardWidth):
  203.                        self.setShapeAt(l, k, self.shapeAt(l, k + 1))
  204.  
  205.            numFullLines = numFullLines + len(rowsToRemove)
  206.  
  207.            if numFullLines > 0:
  208.                self.numLinesRemoved = self.numLinesRemoved + numFullLines
  209.                statusbar.SetStatusText(str(self.numLinesRemoved))
  210.                self.isWaitingAfterLine = True
  211.                self.curPiece.setShape(Tetrominoes.NoShape)
  212.                self.Refresh()
  213.  
  214.  
  215.    def newPiece(self):
  216.        self.curPiece = self.nextPiece
  217.        statusbar = self.GetParent().statusbar
  218.        self.nextPiece.setRandomShape()
  219.        self.curX = Board.BoardWidth / 2 + 1
  220.        self.curY = Board.BoardHeight - 1 + self.curPiece.minY()
  221.  
  222.        if not self.tryMove(self.curPiece, self.curX, self.curY):
  223.            self.curPiece.setShape(Tetrominoes.NoShape)
  224.            self.timer.Stop()
  225.            self.isStarted = False
  226.            statusbar.SetStatusText('Game over')
  227.  
  228.    def tryMove(self, newPiece, newX, newY):
  229.        for i in range(4):
  230.            x = newX + newPiece.x(i)
  231.            y = newY - newPiece.y(i)
  232.            if x < 0 or x >= Board.BoardWidth or y < 0 or y >= Board.BoardHeight:
  233.                return False
  234.            if self.shapeAt(x, y) != Tetrominoes.NoShape:
  235.                return False
  236.  
  237.        self.curPiece = newPiece
  238.        self.curX = newX
  239.        self.curY = newY
  240.        self.Refresh()
  241.        return True
  242.  
  243.  
  244.    def drawSquare(self, dc, x, y, shape):
  245.        colors = ['#000000', '#CC6666', '#66CC66', '#6666CC',
  246.                  '#CCCC66', '#CC66CC', '#66CCCC', '#DAAA00']
  247.  
  248.        light = ['#000000', '#F89FAB', '#79FC79', '#7979FC',
  249.                 '#FCFC79', '#FC79FC', '#79FCFC', '#FCC600']
  250.  
  251.        dark = ['#000000', '#803C3B', '#3B803B', '#3B3B80',
  252.                 '#80803B', '#803B80', '#3B8080', '#806200']
  253.  
  254.        pen = wx.Pen(light[shape])
  255.        pen.SetCap(wx.CAP_PROJECTING)
  256.        dc.SetPen(pen)
  257.  
  258.        dc.DrawLine(x, y + self.squareHeight() - 1, x, y)
  259.        dc.DrawLine(x, y, x + self.squareWidth() - 1, y)
  260.  
  261.        darkpen = wx.Pen(dark[shape])
  262.        darkpen.SetCap(wx.CAP_PROJECTING)
  263.        dc.SetPen(darkpen)
  264.  
  265.        dc.DrawLine(x + 1, y + self.squareHeight() - 1,
  266.            x + self.squareWidth() - 1, y + self.squareHeight() - 1)
  267.        dc.DrawLine(x + self.squareWidth() - 1,
  268.        y + self.squareHeight() - 1, x + self.squareWidth() - 1, y + 1)
  269.  
  270.        dc.SetPen(wx.TRANSPARENT_PEN)
  271.        dc.SetBrush(wx.Brush(colors[shape]))
  272.        dc.DrawRectangle(x + 1, y + 1, self.squareWidth() - 2,
  273.        self.squareHeight() - 2)
  274.  
  275.  
  276. class Tetrominoes(object):
  277.    NoShape = 0
  278.    ZShape = 1
  279.    SShape = 2
  280.    LineShape = 3
  281.    TShape = 4
  282.    SquareShape = 5
  283.    LShape = 6
  284.    MirroredLShape = 7
  285.  
  286.  
  287. class Shape(object):
  288.    coordsTable = (
  289.        ((0, 0),     (0, 0),     (0, 0),     (0, 0)),
  290.        ((0, -1),    (0, 0),     (-1, 0),    (-1, 1)),
  291.        ((0, -1),    (0, 0),     (1, 0),     (1, 1)),
  292.        ((0, -1),    (0, 0),     (0, 1),     (0, 2)),
  293.        ((-1, 0),    (0, 0),     (1, 0),     (0, 1)),
  294.        ((0, 0),     (1, 0),     (0, 1),     (1, 1)),
  295.        ((-1, -1),   (0, -1),    (0, 0),     (0, 1)),
  296.        ((1, -1),    (0, -1),    (0, 0),     (0, 1))
  297.    )
  298.  
  299.    def __init__(self):
  300.        self.coords = [[0,0] for i in range(4)]
  301.        self.pieceShape = Tetrominoes.NoShape
  302.  
  303.        self.setShape(Tetrominoes.NoShape)
  304.  
  305.    def shape(self):
  306.        return self.pieceShape
  307.  
  308.    def setShape(self, shape):
  309.        table = Shape.coordsTable[shape]
  310.        for i in range(4):
  311.            for j in range(2):
  312.                self.coords[i][j] = table[i][j]
  313.  
  314.        self.pieceShape = shape
  315.  
  316.    def setRandomShape(self):
  317.        self.setShape(random.randint(1, 7))
  318.  
  319.    def x(self, index):
  320.        return self.coords[index][0]
  321.  
  322.    def y(self, index):
  323.        return self.coords[index][1]
  324.  
  325.    def setX(self, index, x):
  326.        self.coords[index][0] = x
  327.  
  328.    def setY(self, index, y):
  329.        self.coords[index][1] = y
  330.  
  331.    def minX(self):
  332.        m = self.coords[0][0]
  333.        for i in range(4):
  334.            m = min(m, self.coords[i][0])
  335.  
  336.        return m
  337.  
  338.    def maxX(self):
  339.        m = self.coords[0][0]
  340.        for i in range(4):
  341.            m = max(m, self.coords[i][0])
  342.  
  343.        return m
  344.  
  345.    def minY(self):
  346.        m = self.coords[0][1]
  347.        for i in range(4):
  348.            m = min(m, self.coords[i][1])
  349.  
  350.        return m
  351.  
  352.    def maxY(self):
  353.        m = self.coords[0][1]
  354.        for i in range(4):
  355.            m = max(m, self.coords[i][1])
  356.  
  357.        return m
  358.  
  359.    def rotatedLeft(self):
  360.        if self.pieceShape == Tetrominoes.SquareShape:
  361.            return self
  362.  
  363.        result = Shape()
  364.        result.pieceShape = self.pieceShape
  365.        for i in range(4):
  366.            result.setX(i, self.y(i))
  367.            result.setY(i, -self.x(i))
  368.  
  369.        return result
  370.  
  371.    def rotatedRight(self):
  372.        if self.pieceShape == Tetrominoes.SquareShape:
  373.            return self
  374.  
  375.        result = Shape()
  376.        result.pieceShape = self.pieceShape
  377.        for i in range(4):
  378.            result.setX(i, -self.y(i))
  379.            result.setY(i, self.x(i))
  380.  
  381.        return result
  382.  
  383.  
  384. app = wx.App()
  385. Tetris(None, -1, 'Tetris')
  386. app.MainLoop()
  387.  

Si encuentran algo mejor que yo, lo ponen por aquí.


En línea

Novlucker
Ninja y
Colaborador
***
Desconectado Desconectado

Mensajes: 10.683

Yo que tu lo pienso dos veces


Ver Perfil
Re: Hacer un tetris
« Respuesta #1 en: 26 Enero 2011, 11:29 am »

Citar
Quiero hacer un tetris bajo Linux y python en modo consola.
¿No entiendo, entonces cual es la gracia si vas a copiar el código? :huh:


En línea

Contribuye con la limpieza del foro, reporta los "casos perdidos" a un MOD XD
"Hay dos cosas infinitas: el Universo y la estupidez  humana. Y de la primera no estoy muy seguro."
Albert Einstein
Meta


Desconectado Desconectado

Mensajes: 3.438



Ver Perfil WWW
Re: Hacer un tetris
« Respuesta #2 en: 26 Enero 2011, 15:17 pm »

La gracia es no copiarlo. Sino entenderlo.

De todas forma este no funciona, al menos a mi porque me dice algo de la librería WS.
En línea

Maik33

Desconectado Desconectado

Mensajes: 128


Ver Perfil
Re: Hacer un tetris
« Respuesta #3 en: 26 Enero 2011, 15:23 pm »

La gracia es no copiarlo. Sino entenderlo.

De todas forma este no funciona, al menos a mi porque me dice algo de la librería WS.

Pues yo por curiosidad lo copie, compile, y funciona muy bien.
En línea

RyogiShiki


Desconectado Desconectado

Mensajes: 745


げんしけん - Hikkikomori FTW!!!


Ver Perfil WWW
Re: Hacer un tetris
« Respuesta #4 en: 27 Enero 2011, 00:11 am »

La gracia es no copiarlo. Sino entenderlo.

De todas forma este no funciona, al menos a mi porque me dice algo de la librería WS.

Creo que te refieres a 'wx', para que te funcione correctamente tienes que tener instalado los modulos de wxpython para linux, a continuación los puedes encontrar:
http://www.wxpython.org/download.php

Saludos
En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
[Batch Game] Tetris v 1 - by SmartGenius
Scripting
SmartGenius 1 3,592 Último mensaje 3 Agosto 2010, 00:05 am
por <<J.R>>
Jugar al tetris ayuda a olvidar los traumas
Foro Libre
KarlosVid(ÊÇ) 3 3,329 Último mensaje 24 Abril 2011, 03:09 am
por flacc
Vuelve el 'Tetris' con realidad aumentada y en 3D
Noticias
wolfbcn 1 3,251 Último mensaje 23 Octubre 2011, 07:58 am
por BlackZeroX
[ayuda]el jugo de tetris en c
Programación C/C++
chivis cristian 1 4,168 Último mensaje 26 Noviembre 2011, 05:09 am
por Unbr0ken
Tetris con Balones SDL y C
Juegos y Consolas
linkingcrk 7 4,942 Último mensaje 18 Abril 2012, 02:31 am
por flacc
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines