Поиск:

Ответ в темуСоздание новой темы Создание опроса
> TETRIS, v1. 
:(
    Опции темы
RM2010
  Дата 13.3.2010, 16:55 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Шустрый
*


Профиль
Группа: Участник
Сообщений: 74
Регистрация: 29.1.2010

Репутация: 3
Всего: 2



Ребята, зацените! smile 
Написал тетрис в Python / tkinter. Это еще рабочая версия, так как падают пока не фигурки, а просто кубики.

user posted image

Код

from tkinter import *
import time
import random


app = Tk()
app.title("TETRIS 101")
app.geometry('304x426+600+300')

canvas = Canvas(app, width=304, height=404)
canvas.pack(side=TOP)

freecol=[0,0,0,0,0,0,0,0,0,0]

lbtext=StringVar()
lbl = Label(app, textvariable = lbtext ).pack(side=BOTTOM)


#################### - FUNCTIONS - ##############################

def recallabel():
    lbt="        "
    for lcvar in range(10):
        lbt=lbt+str(freecol[lcvar])+"        "
    lbtext.set(lbt)

def gameover():
    global playgame,freecol
    playgame = False
    canvas.create_rectangle(20,75,284,155, fill="white",outline="white")
    canvas.create_text(151,100, text="GAME OVER!", fill="purple", font=("Elephant", "24"))
    canvas.create_text(151,135, text="PRESS 'R' TO RESTART", fill="purple", font=("calibri", "12"))
    population = 0
    for i in freecol:
        population = population + i
    print("Population: %s" % population)

def resetgame():
    global freecol,playgame
    canvas.delete(ALL)
    freecol=[0,0,0,0,0,0,0,0,0,0]
    recallabel()
    playgame = True
    startgame()

#################### - FUNCTIONS - ##############################

def key(event):
    global randomline,freecol,slidedownblock,drop,dropspeed,blocks
    if playgame == True:
        if event.keysym == "Left":
            if randomline > 0:
                if 404-slidedownblock-freecol[randomline-1]*30 > 30:
                    canvas.move( blocks[len(blocks)-1] , -30, 0)
                    canvas.update()
                    freecol[randomline]=freecol[randomline]-1
                    randomline=randomline-1
                    freecol[randomline]=freecol[randomline]+1
                    recallabel()
                    
        if event.keysym == "Right":
            if randomline < 9:
                if 404-slidedownblock-freecol[randomline+1]*30 > 30:
                    canvas.move( blocks[len(blocks)-1] , +30, 0)
                    canvas.update()
                    freecol[randomline]=freecol[randomline]-1
                    randomline=randomline+1
                    freecol[randomline]=freecol[randomline]+1
                    recallabel()
                    
        if event.keysym == "Down" : dropspeed=0.001

#################### - FUNCTIONS - ##############################

def bounceline():     
    for i in range(20):
        tup = canvas.find_withtag ( 'sup%s'%i )     
        if len(tup)==10:
            kl(i)

    
def kl(killline):     
    global randomline

    canvas.delete('sup%s' % killline )

    for btk in range(20) :
        canvas.move('sup%s' % (killline+btk+1) ,0,30)
        canvas.itemconfigure('sup%s' % (killline+btk+1), tag = 'sup%s' % (killline+btk) )
    
    for x in range(10):
        if freecol[x] >= killline : freecol[x]=freecol[x]-1

    recallabel()
   
#################### - FUNCTIONS - ##############################

def startgame():
    global playgame,dropspeed,randomline,freecol,recallabel,slidedownblock,square
    while playgame:
        dropspeed=0.015
        sqcolor = random.choice(["red","blue","green","yellow"])

        randomline = random.randrange(10)
        freecol[randomline]=freecol[randomline]+1

        recallabel()

        blocks.append(canvas.create_rectangle(randomline*30+2,0,randomline*30+30,28, tag="falling",fill=sqcolor))

        for slidedownblock in range(404):
            time.sleep(dropspeed)
            canvas.move( blocks[len(blocks)-1] , 0, 1)
            canvas.update()
            app.bind_all('<Key>', key)
            if 404-slidedownblock - freecol[randomline]*30 < 0 :
                canvas.itemconfigure( blocks[len(blocks)-1] ,tag = 'sup%s' % freecol[randomline] )
                bounceline()
                if freecol[randomline]>12:
                    gameover()          
                    break
                else:
                    break



blocks=[]

playgame = True
startgame()

app.bind_all('<Key>', key)

app.mainloop()




PM MAIL   Вверх
RM2010
  Дата 24.3.2010, 18:44 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Шустрый
*


Профиль
Группа: Участник
Сообщений: 74
Регистрация: 29.1.2010

Репутация: 3
Всего: 2



Господа, представляю вашему вниманию вторую версию своего ТЕТРИСА.
Практически всё переделано заново. Разворачивать фигуру можно кнопкой 'z'.

user posted image

Осталась пара небольших глюков,
- падающие фигуры 'сверяются' со стоящими постоянно, что тормозит процесс, сделают, чтоб сверялись только при необходимости.
Исправлено строчкой if canvas.bbox('falling')[3] % 30 == 2 : сверяемся со стоящими.

- падающей фигурой можно наехать на бок стоящей, или разворачивая её, выйти за границы поля.
ну вот, и сие исправил! smile if (canvas.bbox(f)[2]-30 == canvas.bbox(s)[2]) and (canvas.bbox(f)[1] < canvas.bbox(s)[1]) and (canvas.bbox(f)[3] > canvas.bbox(s)[1]): oktomove = False

Код

from tkinter import *
import time
import random

app = Tk()
app.title("TETRIS 101")
app.geometry('305x426+600+300')
canvas = Canvas(app, width=304, height=392)
canvas.pack(side=TOP)

svar= 0
score=StringVar()
score.set('Tetris %s' % svar)

Label(app, textvariable = score ).pack(side=BOTTOM,pady=10)


blocks=[] 
freeblocks=[]


def populate_with_free_blocks():  # функция, наполняющая канвас пустыми кубиками, для фона.
    freeblocks=[]
    for y in range(3,393,30):
        for x in range(3,300,30):
            freeblocks.append(canvas.create_rectangle(x,y,x+28,y+28, tag='free',fill='#f7f7f7',outline='#b8cfdc'))
    for x in range(3,300,30):
            freeblocks.append(canvas.create_rectangle(x,y+30,x+28,y+30+28, tag='stopped',fill='#64899d',outline='#64899d'))



def makerandomfig():            # функция, выбирающая случайным образом, какую из 7 фигуру создавать.
    global figbox,color,ingame
    if ingame == 'play':
        randm = random.randrange(1,7)
        if randm == 1 : figbox =[1,0,0,0,   1,0,0,0,   1,1,0,0,   0,0,0,0,]; color='#AED4B0'
        if randm == 2 : figbox =[0,1,0,0,   0,1,0,0,   1,1,0,0,   0,0,0,0,]; color='#9BBE9D'
        if randm == 3 : figbox =[1,1,0,0,   1,1,0,0,   0,0,0,0,   0,0,0,0,]; color='#916959'
        if randm == 4 : figbox =[0,1,0,0,   1,1,1,0,   0,0,0,0,   0,0,0,0,]; color='#79ABCE'
        if randm == 5 : figbox =[1,0,0,0,   1,0,0,0,   1,0,0,0,   1,0,0,0,]; color='#E93200'
        if randm == 6 : figbox =[1,0,0,0,   1,1,0,0,   0,1,0,0,   0,0,0,0,]; color='#F2AC29'
        if randm == 7 : figbox =[0,1,0,0,   1,1,0,0,   1,0,0,0,   0,0,0,0,]; color='#E99800'    
        makefig('none')
    elif ingame == 'gameover':
        canvas.create_rectangle(20,75,284,155, fill="white",outline="#b8cfdc")
        canvas.create_text(151,100, text="GAME OVER!", fill="purple", font=("Elephant", "24"))
        canvas.create_text(151,135, text="YOUR SCORE IS %s" % svar , fill="purple", font=("calibri", "12"))


def makefig(rotate):       # функция, создающая новую фигуру или поворачивающая уже имеющеюся.
    global figbox,color
    
    if rotate == 'left':   # будем поворачивать
        y=500;randomx=500
        falling = canvas.find_withtag('falling')
        for f in falling:
            if canvas.bbox(f)[1] < y : y =canvas.bbox(f)[1]
            if canvas.bbox(f)[0] < randomx : randomx =canvas.bbox(f)[0]+1
        canvas.delete('falling')
        canvas.update()
    else:                    # делаем новую
        randomx = random.randrange(3,213,30)
        y=0

    if figbox[0] == 1: blocks.append(canvas.create_rectangle(randomx,y,randomx+28,y+28, tag="falling",fill=color,outline='#303030'))
    if figbox[1] == 1: blocks.append(canvas.create_rectangle(randomx+30,y,randomx+58,y+28, tag="falling",fill=color,outline='#303030'))
    if figbox[2] == 1: blocks.append(canvas.create_rectangle(randomx+60,y,randomx+88,y+28, tag="falling",fill=color,outline='#303030'))
    if figbox[3] == 1: blocks.append(canvas.create_rectangle(randomx+90,y,randomx+118,y+28, tag="falling",fill=color,outline='#303030'))

    if figbox[4] == 1: blocks.append(canvas.create_rectangle(randomx,y+30,randomx+28,y+58, tag="falling",fill=color,outline='#303030'))
    if figbox[5] == 1: blocks.append(canvas.create_rectangle(randomx+30,y+30,randomx+58,y+58, tag="falling",fill=color,outline='#303030'))
    if figbox[6] == 1: blocks.append(canvas.create_rectangle(randomx+60,y+30,randomx+88,y+58, tag="falling",fill=color,outline='#303030'))
    if figbox[7] == 1: blocks.append(canvas.create_rectangle(randomx+90,y+30,randomx+118,y+58, tag="falling",fill=color,outline='#303030'))

    if figbox[8] == 1: blocks.append(canvas.create_rectangle(randomx,y+60,randomx+28,y+88, tag="falling",fill=color,outline='#303030'))
    if figbox[9] == 1: blocks.append(canvas.create_rectangle(randomx+30,y+60,randomx+58,y+88, tag="falling",fill=color,outline='#303030'))
    if figbox[10] == 1: blocks.append(canvas.create_rectangle(randomx+60,y+60,randomx+88,y+88, tag="falling",fill=color,outline='#303030'))
    if figbox[11] == 1: blocks.append(canvas.create_rectangle(randomx+90,y+60,randomx+118,y+88, tag="falling",fill=color,outline='#303030'))

    if figbox[12] == 1: blocks.append(canvas.create_rectangle(randomx,y+90,randomx+28,y+118, tag="falling",fill=color,outline='#303030'))
    if figbox[13] == 1: blocks.append(canvas.create_rectangle(randomx+30,y+90,randomx+58,y+118, tag="falling",fill=color,outline='#303030'))
    if figbox[14] == 1: blocks.append(canvas.create_rectangle(randomx+60,y+90,randomx+88,y+118, tag="falling",fill=color,outline='#303030'))
    if figbox[15] == 1: blocks.append(canvas.create_rectangle(randomx+90,y+90,randomx+118,y+118, tag="falling",fill=color,outline='#303030'))

    dropping_block() 




def dropping_block():    # функция, роняющая фигуру
    global dropspeed
    dropspeed=0.01

    while ingame == 'play' :
        time.sleep(dropspeed)
        canvas.move( 'falling' , 0, 1)
        canvas.update()
        app.bind_all('<Key>', keydown)

        if canvas.bbox('falling')[3] % 30 == 2 :
            falling = canvas.find_withtag('falling')
            stopped = canvas.find_withtag('stopped')
            for f in falling:
                for s in stopped:
                    if (canvas.bbox(f)[3] == canvas.bbox(s)[1])and(canvas.bbox(f)[0] == canvas.bbox(s)[0]):
                        canvas.itemconfigure( 'falling' ,tag='stopped')
                        checkrows()


def fastdrop():                 # функция, роняющая все фигуру, после того как заполненный ряд был удалён
    for i in range(500):
        time.sleep(0.001)
        canvas.move( 'fastdrop' , 0, 1)
        canvas.update()

        fastdrop = canvas.find_withtag('fastdrop')
        stopped = canvas.find_withtag('stopped')
        for f in fastdrop:
            for s in stopped:
                if (canvas.bbox(f)[3] == canvas.bbox(s)[1])and(canvas.bbox(f)[0] == canvas.bbox(s)[0]):
                    canvas.itemconfigure( 'fastdrop' ,tag='stopped')


def checkrows():                  # функция, проверяющая все ряды на заполнение
    global svar, ingame
    for y in range(15,380,30):
        linelist = canvas.find_overlapping(10, y, 295,y+5)
        linechk=0
        for l in linelist:
            if canvas.itemcget(l,'tag') == 'stopped':
                linechk+=1
                if y == 15 : ingame = 'gameover'
        if linechk==10:
            for l in linelist:
                if canvas.itemcget(l,'tag') == 'stopped':
                    canvas.delete(l)

            stopped = canvas.find_withtag('stopped')
            for s in stopped:
                if canvas.bbox(s)[1] < y : canvas.itemconfigure(s,tag='fastdrop')
            fastdrop()
            svar +=1
            score.set('Tetris %s' % svar)
    
    makerandomfig()
        


def keydown(event):              # функция, 'при нажатии кнопки'
    global dropspeed,figbox,ingame

    if event.keysym == 'Left':   # двигаем фигуру влево
        oktomove = True
        falling = canvas.find_withtag('falling')
        stopped = canvas.find_withtag('stopped')
        for f in falling:   
            if canvas.bbox(f)[0] == 2 : oktomove = False
            for s in stopped:
                if (canvas.bbox(f)[2]-30 == canvas.bbox(s)[2]) and (canvas.bbox(f)[1] < canvas.bbox(s)[1]) and (canvas.bbox(f)[3] > canvas.bbox(s)[1]): oktomove = False
        if oktomove : canvas.move( 'falling' , -30, 0)

   
    if event.keysym == 'Right':   # двигаем фигуру вправо 
        oktomove = True
        falling = canvas.find_withtag('falling')
        stopped = canvas.find_withtag('stopped')
        for f in falling:
            if canvas.bbox(f)[0] == 272 : oktomove = False
            for s in stopped:
                if (canvas.bbox(f)[2]+30 == canvas.bbox(s)[2]) and (canvas.bbox(f)[1] < canvas.bbox(s)[1]) and (canvas.bbox(f)[3] > canvas.bbox(s)[1]): oktomove = False
        if oktomove : canvas.move( 'falling' , +30, 0)

    if event.keysym == 'Down': dropspeed=0.00001  # бросаем фигуру вниз

    if event.keysym == 'p':
        if ingame == 'play' :
            ingame = 'pause'
            canvas.create_rectangle(70,100,234,155, tag='pause', fill="white",outline="#b8cfdc")
            canvas.create_text(151,130, text="PAUSE",  tag='pause', fill="red", font=("calibri", "16"))
        elif ingame == 'pause' :
            canvas.delete('pause')
            ingame = 'play'
            dropping_block()

    if event.keysym == 'z': # поворачиваем фигуру
        if figbox == [1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,] : figbox = [0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,] ; makefig('left') ### if longthing vertical
        elif figbox == [0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,] :figbox = [1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,] ; makefig('left') ### if longthing horizontal
        else:
            a=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]           ### creating temp.array
            for i in range(len(figbox)): a[i]=figbox[i]   ### assing values from 'figbox' to temp
            figbox[0]=a[8];   figbox[1]=a[4];   figbox[2]=a[0];   figbox[3]=0   ### turn everything right
            figbox[4]=a[9];   figbox[5]=a[5];   figbox[6]=a[1];   figbox[7]=0   ### turn everything right
            figbox[8]=a[10];  figbox[9]=a[6];   figbox[10]=a[2];  figbox[11]=0   ### turn everything right
            figbox[12]=0;     figbox[13]=0;     figbox[14]=0;     figbox[15]=0   ### turn everything right
            if (figbox[0]==0) and (figbox[4]==0) and (figbox[8]==0) and (figbox[12]==0):  ### if first column is empty
                for i in range(len(figbox)): a[i]=figbox[i]   ### assing values from 'figbox' to temp
                figbox[0]=a[1];   figbox[1]=a[2];   figbox[2]=a[3];   figbox[3]=0   ### move one col. left
                figbox[4]=a[5];   figbox[5]=a[6];   figbox[6]=a[7];   figbox[7]=0   ### move one col. left
                figbox[8]=a[9];   figbox[9]=a[10];  figbox[10]=a[11]; figbox[11]=0   ### move one col. left
                figbox[12]=a[13]; figbox[13]=a[14]; figbox[14]=a[15]; figbox[15]=0   ### move one col. left
            makefig('left')


ingame = 'play'

populate_with_free_blocks()

makerandomfig()


app.mainloop()


С уважением,
smile 

Это сообщение отредактировал(а) RM2010 - 25.3.2010, 14:19
PM MAIL   Вверх
RM2010
Дата 26.3.2010, 16:15 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Шустрый
*


Профиль
Группа: Участник
Сообщений: 74
Регистрация: 29.1.2010

Репутация: 3
Всего: 2



Цитата
3 mēnešus mācijies un tādu kodu uzrakstīji???
laikam plaģiātu tu te esi ielicis....

Привет коллегам из bootа! Es tas esmu! smile 

Это сообщение отредактировал(а) RM2010 - 26.3.2010, 16:16
PM MAIL   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Правила форума "Тестирование программ"
mr.Anderson

Правила должны соблюдаться всеми без исключения.

  • Темы, в которых будут обнаружены нарушения, будут закрыты или удалены.
  • К пользователям, многократно нарушившим правила, будут применены отдельные санкции.

Для тех, кто создаёт темы:

В данном разделе запрещается размещать программы, которые в той или иной степени могут принести вред потенциальному тестеру программы (например, трояны, вирусы и т.д.)

  • Публикуя ссылку на программу, обязательно проверьте её работоспособность.
  • ОБЯЗАТЕЛЬНО: напишите название программы, а главное - её описание и приведите хотя бы один скриншот. Скриншот по размерам не более 500х500 пикселов, для скриншотов большего размера приводите ссылки на них.
  • Программа, которую Вы даёте на тестирование, должна быть откомпилирована, так как не каждый является программистом, да и мало кто будет ради тестирования устанавливать соответствующий софт.

Для тех, кто тестирует:

Описывая результаты тестирования программы, указывайте тип и версию ОС, а также характеристики компьютера и прочую информацию, которая может повлиять на работоспособность.


Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, mr.Anderson.

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Разное тестирование | Следующая тема »


 




[ Время генерации скрипта: 0.0900 ]   [ Использовано запросов: 22 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.