5 ألعاب مثيرة للاهتمام في بايثون يمكن للأطفال صنعها

This post is also available in: English (الإنجليزية) हिन्दी (الهندية)

يعد إنشاء ألعاب الكمبيوتر الخاصة بك في Python طريقة رائعة لتعلم اللغة.

لبناء لعبة ، ستحتاج إلى استخدام العديد من مهارات البرمجة الأساسية. أنواع المهارات التي ستراها في البرمجة الواقعية. في تطوير اللعبة ، ستستخدم المتغيرات والحلقات والعبارات الشرطية والوظائف والبرمجة الموجهة للكائنات ومجموعة كاملة من تقنيات وخوارزميات البرمجة.

كميزة إضافية ، ستشعر بالرضا عن لعب اللعبة التي أنشأتها للتو!

أطر بايثون لتطوير الألعاب

في نظام Python البيئي ، ستجد مجموعة غنية من الأدوات والمكتبات والأطر التي ستساعدك على إنشاء ألعابك بسرعة.

Games in Python That Kids Can Make

بعض الأطر الأكثر أهمية المتوفرة في Python لإنشاء اللعبة هي:

1. Pygame

Pygame هي مكتبة Python مفتوحة المصدر لإنشاء تطبيقات الوسائط المتعددة مثل الألعاب المبنية على مكتبة SDL الممتازة. هذه المكتبة عبارة عن مزيج من C و Python و Native و OpenGL. تتيح Pygame للمستخدمين إنشاء ألعاب مميزة تمامًا بالإضافة إلى برامج الوسائط المتعددة باستخدام برمجة Python. إنه محمول للغاية ويعمل على كل منصة ونظام تشغيل تقريبًا.

بعض الميزات هي: –

  • يمكن استخدام وحدات المعالجة المركزية متعددة النواة بسهولة
  • يستخدم C المحسن ورمز التجميع للوظائف الأساسية
  • بسيط ومحمول
  • مطلوب كمية صغيرة من التعليمات البرمجية

2. PyKyra

PyKyraهي واحدة من أسرع أطر تطوير الألعاب في Python والتي تعتمد على كل من SDL (توطين البرامج والتوثيق) ومحرك Kyra. إلى جانب الميزات القياسية لهذا الإطار ، فإنه يدعم أيضًا فيديو MPEG ، وأصوات مثل MP3 ، و Ogg Vorbis ، و Wav ، وما إلى ذلك ، وقراءة الصور المباشرة ، وغير ذلك الكثير.

3. بيجليت

Pyglet عبارة عن مكتبة مفتوحة المصدر وعبر الأنظمة الأساسية للنوافذ والوسائط المتعددة لـ Python. إنها مكتبة Python قوية يمكن استخدامها لتطوير الألعاب والتطبيقات الأخرى الغنية بصريًا على Windows و Mac OS X و Linux. يدعم Pyglet النوافذ ، ومعالجة أحداث واجهة المستخدم ، وعصا التحكم ، ورسومات OpenGL ، وتحميل الصور ، ومقاطع الفيديو ، وتشغيل الأصوات والموسيقى. يعمل Pyglet تحت Python 3.5+ ويعمل أيضًا على مترجمي Python الآخرين مثل PyPy.

بعض الميزات هي-

  • لا تبعيات خارجية أو متطلبات التثبيت
  • نوافذ أصلية مرنة
  • دعم مدمج للصور والصوت
  • مكتوبة بلغة بيثون نقية

4. PyOpenGL

يعد PyOpenGL أحد أكثر روابط Python شيوعًا عبر الأنظمة الأساسية لـ OpenGL وواجهات برمجة التطبيقات ذات الصلة. في PyOpenGL ، يتم إنشاء الربط باستخدام مكتبة الأنواع القياسية. PyOpenGL قابل للتشغيل المتبادل مع عدد كبير من مكتبات واجهة المستخدم الرسومية الخارجية لبيثون بما في ذلك PyGame و PyQt و Raw XLib وغيرها.

5. كيفي

تم تجهيز Kivy بواجهات مستخدم جديدة مثل تطبيقات اللمس المتعدد ، وهي مكتبة Python مفتوحة المصدر ومتعددة المنصات للتطوير السريع للتطبيقات. يعمل Kivy على Linux و Windows و OS X و Android و iOS و Raspberry Pi ويمكنه استخدام معظم المدخلات والبروتوكولات والأجهزة في الأصل بما في ذلك WM_Touch و WM_Pen و Mac OS X Trackpad و Magic Mouse و Mtdev و Linux Kernel HID و TUIO . يتم تسريع المكتبة بواسطة GPU ، وهي تأتي مع أكثر من 20 عنصر واجهة مستخدم جميعها قابلة للتوسعة بشكل كبير.

6. Panda3D

مكتوب بلغة Python و C ++ ، Panda3Dهو محرك مفتوح المصدر ومجاني تمامًا للاستخدام للألعاب ثلاثية الأبعاد في الوقت الفعلي والتصورات والمحاكاة والتجارب والمزيد. يتضمن Panda3D أدوات سطر الأوامر لمعالجة وتحسين أصول المصدر التي تسمح للمستخدمين بأتمتة خط إنتاج المحتوى وبرمجته. وهو يدعم العديد من مكتبات الطرف الثالث الشائعة ، مثل محرك Bullet physics ومحمل نموذج Assimp ومكتبات الصوت OpenAL و FMOD والمزيد.

7. Cocos2d

يعد Cocos2d ، المكتوب بلغة Python و C ++ و Objective C ، إطار عمل برمجي مفتوح المصدر يمكن استخدامه لبناء الألعاب والتطبيقات والبرامج التفاعلية الأخرى القائمة على واجهة المستخدم الرسومية عبر الأنظمة الأساسية. تتكون عائلة Cocos2d من Cocos2d-x و Cocos2d-JS و Cocos2d-XNA و Cocos2d (Python). Cocos2d-x عبارة عن إطار لعبة مفتوح المصدر مكتوب بلغة C ++ ، مع طبقة رقيقة تعتمد على النظام الأساسي ، ويمكن استخدامه لبناء الألعاب والتطبيقات والبرامج التفاعلية الأخرى القائمة على واجهة المستخدم الرسومية عبر الأنظمة الأساسية. أيضًا ، Cocos2d-JS هو إصدار جافا سكريبت لمحرك Cocos2d-x والذي يدعم وظائف Cocos2d-x الكاملة مع مجموعة من واجهات برمجة التطبيقات المبسطة الملائمة لجافا سكريبت.

8. بايثون الغول

Python-Ogre أو PyOgre عبارة عن رابط Python لمكتبة C ++ لمحرك OGRE 3D. PyOgre عبارة عن منصة مشتركة وترث السرعة والمرونة. Ogre هو محرك عرض ثلاثي الأبعاد مكتوب بالكامل بلغة C ++ يدعم مجموعة ميزات رائعة وقد تم استخدامه لإنشاء ألعاب رائعة. يتكون PyOgre في الواقع من مكتبتين. الأول هو Ogre3d ، وهو محرك عرض ثلاثي الأبعاد والثاني هو CEGUi ، وهو نظام واجهة مستخدم رسومية مضمن.

9. Ren’Py

يعد Ren’Py، المكتوب بلغة Python و Cython ، محركًا مجانيًا متعدد الأنظمة الأساسية لسرد القصص رقميًا يجعل من السهل الجمع بين الكلمات والصور والأصوات لإنشاء روايات مرئية وألعاب محاكاة للحياة. يتيح دعم Ren’Py للغة برمجة Python للمطورين العمل باستخدام منطق اللعبة المعقد. واحدة من أكبر مزايا Ren’Py هي أنه يعمل على كل نظام كمبيوتر تقريبًا.

ألعاب في بايثون يمكن للأطفال صنعها

نقدم لك 5 أنشطة وألعاب شيقة يمكن للأطفال القيام بها في بايثون.

1. الطلاء

معظمنا على دراية بتطبيق الطلاء في Windows الذي نستخدمه لرسم الصور وتلوينها. ولكن ماذا لو أنشأت برنامج الرسم الخاص بك باستخدام Pygame. أليست مثيرة؟

Games in Python That Kids Can Make

يمكن النظر إلى التطبيق الكامل على أنه الوحدات الفرعية التالية: إنشاء نافذة للرسم: كخطوة أولى ، سننشئ نافذة نرسم عليها. سيتم استخدام هذه النافذة لتثبيت الصور التي يتم رسمها. تحديد ألوان القلم الرصاص: من أجل رسم صور متعددة الألوان ، تحتاج إلى خيار اختيار أقلام الرصاص بألوان مختلفة. وأخيرًا ، رمز لرسم صورة عند تحريك الماوس عبر النافذة.

import pygameimport pygame.gfxdraw#Initializing pygame modulepygame.init() #Screen variablesscreen_width = 700screen_height =500 # Defining Colorswhite = (255, 255, 255)blue = (67,238,250)red = (255, 0, 0)black = (0, 0, 0)green = (38,245,45)pink = (255,192,203)orange = (255,165,0)yellow = (255,255,0)violet = (177, 3, 252) #Setting default color to blackpencolour = black drawingwindow = pygame.display.set_mode((screen_width,screen_height))pygame.display.set_caption(“Paint – By Bhavik Agarwal”)drawingwindow.fill((255,255,255)) #Loading backgroud image and drawing it on screenbackimg = pygame.image.load(“paint.png”).convert_alpha()drawingwindow.blit(backimg, (0,0)) #rect for the drawing areaclearrect = (119, 17, 562, 465) #Defining rect value for colors in colorboxcol1= (22, 81, 30, 34)col2= (56, 81, 34, 34)col3= (22, 120, 30, 33)col4= (56, 120, 34, 32)col5= (22, 156, 30, 33)col6= (56, 156, 34, 32)col7= (22, 192, 30, 33)col8= (56, 192, 34, 32) #Rect that highlight which button is selectedbuttonselect = (22, 81, 30, 34) #Function to draw color boxdef drawrectangle(): pygame.gfxdraw.box(drawingwindow, col1, black) pygame.gfxdraw.box(drawingwindow, col2, blue) pygame.gfxdraw.box(drawingwindow, col3, red) pygame.gfxdraw.box(drawingwindow, col4, green) pygame.gfxdraw.box(drawingwindow, col5, pink) pygame.gfxdraw.box(drawingwindow, col6, orange) pygame.gfxdraw.box(drawingwindow, col7, yellow) pygame.gfxdraw.box(drawingwindow, col8, violet)drawrectangle() #Set mouse cursor for pencil (default)pygame.mouse.set_cursor(*pygame.cursors.broken_x)exit_game = False #Gameloopwhile not exit_game: for event in pygame.event.get(): if event.type == pygame.QUIT: exit_game = True #Check for button clicks t = pygame.mouse.get_pressed() if t[0] == 1: mousepos = pygame.mouse.get_pos() if 122 < mousepos[0] < 678 and 21 < mousepos[1] < 480: pygame.gfxdraw.filled_ellipse(drawingwindow,mousepos[0], mousepos[1],4,4,pencolour) elif 22 < mousepos[0] < 52 and 81 < mousepos[1] < 115: pencolour = black drawrectangle() buttonselect = (22, 81, 30, 34) elif 56 < mousepos[0] < 90 and 81 < mousepos[1] < 115: pencolour = blue drawrectangle() buttonselect = (56, 81, 34, 34) elif 22 < mousepos[0] < 52 and 120 < mousepos[1] < 153: pencolour = red drawrectangle() buttonselect = (22, 120, 30, 33) elif 56 < mousepos[0] < 90 and 120 < mousepos[1] < 152: pencolour = green drawrectangle() buttonselect = (56, 120, 34, 32) elif 22 < mousepos[0] < 52 and 156 < mousepos[1] < 189: pencolour = pink drawrectangle() buttonselect = (22, 156, 30, 33) elif 56 < mousepos[0] < 90 and 156 < mousepos[1] < 188: pencolour = orange drawrectangle() buttonselect = (56, 156, 34, 32) elif 22 < mousepos[0] < 52 and 192 < mousepos[1] < 225: pencolour = yellow drawrectangle() buttonselect = (22, 192, 30, 33) elif 56 < mousepos[0] < 90 and 192 < mousepos[1] < 224: pencolour = violet drawrectangle() buttonselect = (56, 192, 34, 32) #Eraser elif 13 < mousepos[0] < 54 and 247 < mousepos[1] < 285: pencolour = white drawrectangle() pygame.mouse.set_cursor(*pygame.cursors.diamond) #Pencil elif 59 < mousepos[0] < 97 and 247 < mousepos[1] < 288: pencolour = black drawrectangle() pygame.mouse.set_cursor(*pygame.cursors.broken_x) buttonselect = (22, 81, 30, 34) elif 15 < mousepos[0] < 96 and 363 < mousepos[1] < 400: pygame.gfxdraw.box(drawingwindow, clearrect, white) pygame.gfxdraw.rectangle(drawingwindow, buttonselect, white) pygame.display.update() pygame.quit()

2. لعبة الأفعى

لقد لعبت جميعًا لعبة Snake Game وبالتأكيد لم ترغب أبدًا في الخسارة. كأطفال ، أحببنا جميعًا البحث عن غشاشين حتى لا نرى أبدًا رسالة “انتهت اللعبة”. ولكن بصفتك تقنيًا ، قد ترغب في جعل رقصة “الأفعى” هذه على إيقاعاتك.

Games in Python That Kids Can Make

يمكنك بناء لعبة ثعبان من خلال إنشاء الوحدات – إنشاء الشاشة ، إنشاء الأفعى ، تحريك الأفعى ، انتهاء اللعبة عندما يضرب الأفعى الحدود ، إضافة الطعام ، زيادة طول الأفعى ، عرض النتيجة.

import pygameimport timeimport random pygame.init() white = (255, 255, 255)yellow = (255, 255, 102)black = (0, 0, 0)red = (213, 50, 80)green = (0, 255, 0)blue = (50, 153, 213) dis_width = 600dis_height = 400 dis = pygame.display.set_mode((dis_width, dis_height))pygame.display.set_caption(‘Snake Game’) clock = pygame.time.Clock() snake_block = 10snake_speed = 15 font_style = pygame.font.SysFont(“bahnschrift”, 25)score_font = pygame.font.SysFont(“comicsansms”, 35) def Your_score(score): value = score_font.render(“Your Score: ” + str(score), True, yellow) dis.blit(value, [0, 0]) def our_snake(snake_block, snake_list): for x in snake_list: pygame.draw.rect(dis, black, [x[0], x[1], snake_block, snake_block]) def message(msg, color): mesg = font_style.render(msg, True, color) dis.blit(mesg, [dis_width / 6, dis_height / 3]) def gameLoop(): game_over = False game_close = False x1 = dis_width / 2 y1 = dis_height / 2 x1_change = 0 y1_change = 0 snake_List = [] Length_of_snake = 1 foodx = round(random.randrange(0, dis_width – snake_block) / 10.0) * 10.0 foody = round(random.randrange(0, dis_height – snake_block) / 10.0) * 10.0 while not game_over: while game_close == True: dis.fill(blue) message(“You Lost! Press C-Play Again or Q-Quit”, red) Your_score(Length_of_snake – 1) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_q: game_over = True game_close = False if event.key == pygame.K_c: gameLoop() for event in pygame.event.get(): if event.type == pygame.QUIT: game_over = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: x1_change = -snake_block y1_change = 0 elif event.key == pygame.K_RIGHT: x1_change = snake_block y1_change = 0 elif event.key == pygame.K_UP: y1_change = -snake_block x1_change = 0 elif event.key == pygame.K_DOWN: y1_change = snake_block x1_change = 0 if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0: game_close = True x1 += x1_change y1 += y1_change dis.fill(blue) pygame.draw.rect(dis, green, [foodx, foody, snake_block, snake_block]) snake_Head = [] snake_Head.append(x1) snake_Head.append(y1) snake_List.append(snake_Head) if len(snake_List) > Length_of_snake: del snake_List[0] for x in snake_List[:-1]: if x == snake_Head: game_close = True our_snake(snake_block, snake_List) Your_score(Length_of_snake – 1) pygame.display.update() if x1 == foodx and y1 == foody: foodx = round(random.randrange(0, dis_width – snake_block) / 10.0) * 10.0 foody = round(random.randrange(0, dis_height – snake_block) / 10.0) * 10.0 Length_of_snake += 1 clock.tick(snake_speed) pygame.quit() quit() gameLoop()

3. دوت كونيكت

لعبة Dot Connect هي اللعبة التي يربط فيها اللاعب النقاط لعمل مربعات. القواعد معروفة: يجب على كل لاعب إنشاء خط جديد بين نقطتين (نقرة واحدة بالقرب من الخط الذي ترغب في إنشائه). إذا قام لاعب بإنشاء صندوق ، فإنه يحصل على نقطة ويعود مرة أخرى. (صندوقان يحصلان على نقطتين ، لكن دورة إضافية واحدة فقط). أعلى نتيجة من 81 صندوقًا هي الفائز!

Games in Python That Kids Can Make

from Tkinter import *import tkFont TOL = 8CELLSIZE = 40OFFSET = 10CIRCLERAD = 2DOTOFFSET = OFFSET + CIRCLERADGAME_H = 400GAME_W = 400 class Player(object): def __init__(self, name, color=”black”): self.score = 0 self.str = StringVar() self.name = name self.color = color def update(self): self.str.set(self.name + “: %d” % self.score) class MyFrame(Frame): def __init__(self, master): Frame.__init__(self, master) self.GO_font = tkFont.Font(self, name=”GOFont”, family = “Times”, weight=”bold”, size=36) self.canvas = Canvas(self, height = GAME_H, width = GAME_W) self.canvas.bind(“<Button-1>”, lambda e:self.click(e)) self.canvas.grid(row=0,column=0) self.dots = [[self.canvas.create_oval(CELLSIZE*i+OFFSET, CELLSIZE*j+OFFSET, CELLSIZE*i+OFFSET+2*CIRCLERAD, CELLSIZE*j+OFFSET+2*CIRCLERAD, fill=”black”) for j in range(10)] for i in range(10)] self.lines = [] self.infoframe = Frame(self) self.players = [Player(“Player 1″,”blue”), Player(“Player 2″,”red”)] self.infoframe.players = [Label(self.infoframe, textvariable = i.str) for i in self.players] for i in self.infoframe.players: i.grid() self.turn = self.players[0] self.update_players() self.infoframe.grid(row = 0, column = 1, sticky = N) self.grid() def update_players(self): for i in self.players: i.update() def click(self, event): x,y = event.x, event.y orient = self.isclose(x,y) if orient: if self.line_exists(x,y, orient): return l = self.create_line(x,y, orient) score = self.new_box_made(l) if score: self.turn.score += score self.turn.update() self.check_game_over() else: index = self.players.index(self.turn) self.turn = self.players[1-index] self.lines.append(l) def create_line(self, x, y, orient): startx = CELLSIZE * ((x-OFFSET)//CELLSIZE) + DOTOFFSET starty = CELLSIZE * ((y-OFFSET)//CELLSIZE) + DOTOFFSET tmpx = (x-OFFSET)//CELLSIZE tmpy = (y-OFFSET)//CELLSIZE if orient == HORIZONTAL: endx = startx + CELLSIZE endy = starty else: endx = startx endy = starty + CELLSIZE #print “line drawn: %d,%d to %d,%d” % (startx,starty,endx,endy) return self.canvas.create_line(startx,starty,endx,endy) def new_box_made(self, line): score = 0 x0,y0,x1,y1 = self.canvas.coords(line) if x0 == x1: # vertical line midx = x0 midy = (y0+y1)/2 pre = (x0 – CELLSIZE/2, midy) post = (x0 + CELLSIZE/2, midy) elif y0 == y1: # horizontal line midx = (x0 + x1)/2 midy = y0 pre = (midx, y0 – CELLSIZE/2) post = (midx, y0 + CELLSIZE/2) if len(self.find_lines(pre)) == 3: # not 4, because newly created line is self.fill_in(pre) # is not returned (?!) score += 1 if len(self.find_lines(post)) == 3: self.fill_in(post) score += 1 return score def find_lines(self, coords): x, y = coords if x < 0 or x > GAME_W: return [] if y < 0 or y > GAME_W: return [] #print “Cell center: %d,%d” % (x,y) lines = [x for x in self.canvas.find_enclosed(x-CELLSIZE, y-CELLSIZE, x+CELLSIZE, y+CELLSIZE) if x in self.lines] #print lines return lines def fill_in(self, coords): x,y = coords self.canvas.create_text(x,y,text=self.turn.name, fill=self.turn.color) def isclose(self, x, y): x -= OFFSET y -= OFFSET dx = x – (x//CELLSIZE)*CELLSIZE dy = y – (y//CELLSIZE)*CELLSIZE if abs(dx) < TOL: if abs(dy) < TOL: return None # mouse in corner of box; ignore else: return VERTICAL elif abs(dy) < TOL: return HORIZONTAL else: return None def line_exists(self, x,y, orient): id_ = self.canvas.find_closest(x,y,halo=TOL)[0] if id_ in self.lines: return True else: return False def check_game_over(self): total = sum([x.score for x in self.players]) if total == 81: self.canvas.create_text(GAME_W/2, GAME_H/2, text=”GAME OVER”, font=”GOFont”, fill=”#888″) mainw = Tk()mainw.f = MyFrame(mainw)mainw.mainloop()

4. بينج بونج

تعد لعبة Pong واحدة من أشهر ألعاب الأركيد ، حيث تحاكي تنس الطاولة. يتحكم كل لاعب في مجداف في اللعبة عن طريق سحبه عموديًا عبر الجانب الأيسر أو الأيمن من الشاشة. يستخدم اللاعبون المضارب لضرب الكرة ذهابًا وإيابًا.

Games in Python That Kids Can Make

السلاحف هي وحدة رسومية داخلية في بايثون. يستخدم لوحة وقلم لتصوير الرسوم التوضيحية.

فيما يلي الخطوات المستخدمة:

  • الخطوة 1) قم بإنشاء اثنين من المجاذيف A و B على الجانبين الأيسر والأيمن من الشاشة.
  • الخطوة 2) اصنع كرة.
  • الخطوة 3) قم بإنشاء حدث لتحريك المضرب عموديًا بالضغط على مفتاح معين.
  • الخطوة 4) قم بإنشاء الوظيفة لتحديث النتيجة بعد أن يفوت كل لاعب تصادمًا.

# Import required libraryimport turtle # Create screensc = turtle.Screen()sc.title(“Pong game”)sc.bgcolor(“white”)sc.setup(width=1000, height=600) # Left paddleleft_pad = turtle.Turtle()left_pad.speed(0)left_pad.shape(“square”)left_pad.color(“black”)left_pad.shapesize(stretch_wid=6, stretch_len=2)left_pad.penup()left_pad.goto(-400, 0) # Right paddleright_pad = turtle.Turtle()right_pad.speed(0)right_pad.shape(“square”)right_pad.color(“black”)right_pad.shapesize(stretch_wid=6, stretch_len=2)right_pad.penup()right_pad.goto(400, 0) # Ball of circle shapehit_ball = turtle.Turtle()hit_ball.speed(40)hit_ball.shape(“circle”)hit_ball.color(“blue”)hit_ball.penup()hit_ball.goto(0, 0)hit_ball.dx = 5hit_ball.dy = -5 # Initialize the scoreleft_player = 0right_player = 0 # Displays the scoresketch = turtle.Turtle()sketch.speed(0)sketch.color(“blue”)sketch.penup()sketch.hideturtle()sketch.goto(0, 260)sketch.write(“Left_player : 0 Right_player: 0″,align=”center”, font=(“Courier”, 24, “normal”)) # Functions to move paddle verticallydef paddleaup():y = left_pad.ycor()y += 20left_pad.sety(y) def paddleadown():y = left_pad.ycor()y -= 20left_pad.sety(y) def paddlebup():y = right_pad.ycor()y += 20right_pad.sety(y) def paddlebdown():y = right_pad.ycor()y -= 20right_pad.sety(y) # Keyboard bindingssc.listen()sc.onkeypress(paddleaup, “e”)sc.onkeypress(paddleadown, “x”)sc.onkeypress(paddlebup, “Up”)sc.onkeypress(paddlebdown, “Down”) while True:sc.update() hit_ball.setx(hit_ball.xcor()+hit_ball.dx)hit_ball.sety(hit_ball.ycor()+hit_ball.dy) # Checking bordersif hit_ball.ycor() > 280:hit_ball.sety(280)hit_ball.dy *= -1 if hit_ball.ycor() < -280:hit_ball.sety(-280)hit_ball.dy *= -1 if hit_ball.xcor() > 500:hit_ball.goto(0, 0)hit_ball.dy *= -1left_player += 1sketch.clear()sketch.write(“Left_player : {} Right_player: {}”.format(left_player, right_player), align=”center”,font=(“Courier”, 24, “normal”)) if hit_ball.xcor() < -500:hit_ball.goto(0, 0)hit_ball.dy *= -1right_player += 1sketch.clear()sketch.write(“Left_player : {} Right_player: {}”.format(left_player, right_player), align=”center”,font=(“Courier”, 24, “normal”)) # Paddle ball collisionif (hit_ball.xcor() > 360 andhit_ball.xcor() < 370) and(hit_ball.ycor() < right_pad.ycor()+40 andhit_ball.ycor() > right_pad.ycor()-40):hit_ball.setx(360)hit_ball.dx*=-1if (hit_ball.xcor()<-360 andhit_ball.xcor()>-370) and(hit_ball.ycor()<left_pad.ycor()+40 andhit_ball.ycor()>left_pad.ycor()-40):hit_ball.setx(-360)hit_ball.dx*=-1

5. تيك تاك تو

Tic Tac Toe هي واحدة من أكثر الألعاب التي يتم لعبها وهي أفضل لعبة قاتلة للوقت يمكنك لعبها في أي مكان باستخدام قلم وورقة فقط. إذا كنت لا تعرف كيفية لعب هذه اللعبة ، فلا تقلق ، دعنا نفهم ذلك أولاً.

Games in Python That Kids Can Make

يتم لعب اللعبة من قبل شخصين. أولاً ، نرسم لوحة بشبكة 3 × 3 مربعة. يختار اللاعب الأول “X” ويرسمها على أي شبكة مربعة ، ثم تكون فرصة اللاعب الثاني لرسم “O” على المساحات المتاحة. مثل هذا ، يقوم اللاعبون برسم “X” و “O” بدلاً من ذلك على المساحات الفارغة حتى ينجح اللاعب في رسم 3 علامات متتالية إما بطريقة أفقية أو رأسية أو قطرية. ثم يفوز اللاعب باللعبة وإلا ستتعادل اللعبة عندما تمتلئ جميع النقاط.

# Tic-Tac-Toe Program using# random number in Python# importing all necessary librariesimport numpy as npimport randomfrom time import sleep# Creates an empty boarddef create_board():return(np.array([[0, 0, 0],[0, 0, 0],[0, 0, 0]]))# Check for empty places on boarddef possibilities(board):l = []for i in range(len(board)):for j in range(len(board)):if board[i][j] == 0:l.append((i, j))return(l)# Select a random place for the playerdef random_place(board, player):selection = possibilities(board)current_loc = random.choice(selection)board[current_loc] = playerreturn(board)# Checks whether the player has three# of their marks in a horizontal rowdef row_win(board, player):for x in range(len(board)):win = Truefor y in range(len(board)):if board[x, y] != player:win = Falsecontinueif win == True:return(win)return(win)# Checks whether the player has three# of their marks in a vertical rowdef col_win(board, player):for x in range(len(board)):win = Truefor y in range(len(board)):if board[y][x] != player:win = Falsecontinueif win == True:return(win)return(win)# Checks whether the player has three# of their marks in a diagonal rowdef diag_win(board, player):win = Truey = 0for x in range(len(board)):if board[x, x] != player:win = Falseif win:return winwin = Trueif win:for x in range(len(board)):y = len(board) – 1 – xif board[x, y] != player:win = Falsereturn win# Evaluates whether there is# a winner or a tiedef evaluate(board):winner = 0for player in [1, 2]:if (row_win(board, player) orcol_win(board,player) ordiag_win(board,player)):winner = playerif np.all(board != 0) and winner == 0:winner = -1return winner# Main function to start the gamedef play_game():board, winner, counter = create_board(), 0, 1print(board)sleep(2)while winner == 0:for player in [1, 2]:board = random_place(board, player)print(“Board after ” + str(counter) + ” move”)print(board)sleep(2)counter += 1winner = evaluate(board)if winner != 0:breakreturn(winner)# Driver Codeprint(“Winner is: ” + str(play_game()))

أضف تعليق