webunique

Freelanc ฟรีแลนด์ Web Develop พัฒนาเว็บไซน์ Graphice งานออกแบบ Programming เขียนโปรแกรม

มาเขียนเกมส์ด้วย PYTHON กัน ตอน 2

มาในขั้นที่สอง เราจะมาสร้างฉากหลังให้ scorll ไปเรี่อยๆให้เมือนเครื่องบินวิ่งไปเลื่อยๆครับ

code ตามนี้ครับ ที่เป็นสีแดงคือ class ที่เพิ่มเข้ามาครับ

import pygame ### อันนี้เป็นการบอกว่าจะใช้ Module Pygame

pygame.init() ### บอกให้ Pygame พร้อมทำงาน

class Ocean(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load('images/ocean.gif')
self.rect = self.image.get_rect()
self.dy = 5
self.reset()

def update(self):
self.rect.bottom += self.dy
if self.rect.bottom >= 1440:
self.reset()

def reset(self):
self.rect.top = -960

class Plan(pygame.sprite.Sprite): ### เป็นการประกาศ Class Plan

def __init__(self): ### เป็น class constructor คือค่าเริ่มต้นของ Class

pygame.sprite.Sprite.__init__(self) ### ทำให้ Class เป็น Sprite ใน Pygame

self.image = pygame.image.load('images/plane.png') ###สั่งให้ Class Plan โหลดภาพครับ

self.rect = self.image.get_rect()

def update(self): #### เป็นการสร้าง Function Update ใช้เมื่อมีการขยับ MOUSE ของ USER

mousex,mousey = pygame.mouse.get_pos() ### สร้างตัวแปร mousex,mousey เพื่อรับค่าำตำแหน่ง Mouse

self.rect.center = (mousex,mousey) ### set ให้ตำแหน่ง Class นีอยู่ในตำแหน่งที่ Mouse อยู่

def main(): ### Function Main เป็นจุดเริ่มต้นของโปรแกรม

screen = pygame.display.set_mode((640, 480)) ### สร้างตัวแปรว่า Screen คือหน้าจอและเซ็ตขนาดหน้าจอ

pygame.display.set_caption("My Game") ### เซ็ตไตเติลหน้าจอ

backgrund = pygame.Surface(screen.get_size()) ### สร้าง Surface ที่ชื่อ Backgrund ให้มีขนาดเท่ากับ Screen

backgrund.fill((0,0,255)) ### ลงสีให้กับ backgrund เป็นแบบ RGB ผมลง B= Bule ครับ

screen.blit(backgrund, (0, 0)) ### บอกให้ Screen โหลด backgrund เข้าไป

plan = Plan() ### สร้าง ตัว Class Plan ขึ้นมาเพื่อใช้งาน(ที่เราเขียนไว้ด้านบน)

ocean = Ocean()

allsprite = pygame.sprite.Group(ocean,plan)

clock = pygame.time.Clock() ### สร้างตัวนับเวลาให้ในการบอก Frame ว่าจะทำการรีเฟรชวินาทีละกี่ครัง

Keepgoing = True ### สร้างตัวแปรให้ Keepgoing เป็น True

while Keepgoing: ### เป็นเงื่อนไขทำจนกว่า Keepgoing จะเป็น False

clock.tick(30) ### กำหนดการ Frame

pygame.mouse.set_visible(False); ### ไม่ให้แสดง Mouse บนหน้าจอ

for event in pygame.event.get(): ### เป็นการ Loop รับค่า Event ว่า User กดปุ่มอะำไรบ้าง

if event.type == pygame.QUIT: ### ถ้าเป็นการกดปุ่มปิด

Keepgoing = False ### Keepgoing เป็น False โปรแกรมจะปิด

 

allsprite.update() ### เรียกให้ Function update

allsprite.draw(screen) ### วาดหน้าจอใหม่

pygame.display.flip()

if __name__ == "__main__":

main() ### เรียกใช้ Function Main

ตอนต่อไปจะมาทำการ rundom คู่ต่อสู้แล้วยิงกันครับ

ลอง Download Source ไปเล่นดูครับ ถ้ามีปัญหาสงสัยสามารถสอบถามได้ทาง Email ครับ ยินดึครับ

DownLoad Source Code