动漫界面
当前位置:首页 - 博客 >

会玩游戏的AI(1)--用pygame编写游戏

2019-07-04来源:魅力天津

有几周没更新公号了,一是由于学校日常琐事耽误,二是新的AI项目有难度。

上次完成股市预测项目后,花了些时间想把tensorflow弄个大致,不过,完成用tensorflow运行mnist后,发现tf不是地球人玩的,就没有继续下去的意愿。


继续keras吧,适合keras的项目很多,而且很有趣。

监督学习暂告一段落,学用Keras做聚类与增强学习。


目前进行的项目是,让AI学习玩一个简单的游戏:接球。

游戏很简单,在游戏窗口中,有一个球从窗口上部任意位置匀速下落,窗口底部有个接球板,水平移动接球板,让小球落到板上得10分,否则扣10分。

 

(20*20的是球,50*10的是接球板)

游戏用pygame编写。

一、先制作一个简单的手控游戏,下面代码:

import pygame

import random

score=0#得分

pygame.init()

pygame.key.set_repeat(10,100)#长按某键,10毫秒后产生一个KEYDOWN事件,之后每隔100毫秒产生一个KEYDOWN事件。

screen=pygame.display.set_mode((400,400))#窗口尺寸为400*400

clock=pygame.time.Clock()#生成延时对象clock

 

ball_x=random.randint(0,380) #在窗口上部10像素处随机(0~380)出现ball

ball_y=10#ball的水平位置为10

paddle_x=random.randint(0,350)#在窗口底处随机(0~350)出现paddle

 

game_over=False#   游戏结束标志

while not game_over:

      ball_y=ball_y+10# ball以每隔30毫秒下落10像素

      for event in pygame.event.get(): #方向键控制paddle水平移动,Esc键退出游戏           

            if event.type==pygame.QUIT:

                  exit()

            if event.type==pygame.KEYDOWN:

                  if event.key==pygame.K_ESCAPE:

                        game_over=True

                        break

                  if event.key==pygame.K_LEFT:

                        paddle_x=paddle_x-10#10像素为水平移动的速度

                  if event.key==pygame.K_RIGHT:

                        paddle_x=paddle_x+10

      screen.fill((0,0,0))#窗口全黑,可理解为擦除窗口内的对象            

      ball=pygame.draw.rect(screen,(255,255,255),((ball_x,ball_y),(20,20)))#在新的位置画球

      paddle=pygame.draw.rect(screen,(255,255,255),((paddle_x,350),(50,10)))#在新的位置画板

      pygame.display.flip()#显示内容

      clock.tick(30)#延时30毫秒

检测paddle是否有接到ball) 


      if ball_y>=340:#检测paddle是否有接到ball340=350-球高的一半10

            if ball.colliderect(paddle):#ball paddle是否碰到

                  score+=10

            else:

                  score-=10

            #另一个球从窗口上部下落

            ball_y=10

            ball_x=random.randint(0,380)

            print(score)

 

二、再把一些参数进行定义,以便后期调试,并用类的方式改写代码:

# -*- coding: utf-8 -*-

import collections #截取游戏窗口,用于神经网络训练。

import numpy as np

import pygame

import random

import matplotlib.pyplot as plt#查看截取窗口的效果

class MyGame(object):    

    def __init__(self):

        pygame.init()

        pygame.key.set_repeat(10, 100)

        

        # 定义游戏对象参数

        self.COLOR_WHITE = (255, 255, 255)

        self.COLOR_BLACK = (0, 0, 0)

        self.GAME_WIDTH = 400

        self.GAME_HEIGHT = 400

        self.BALL_WIDTH = 20

        self.BALL_HEIGHT = 20

        self.PADDLE_WIDTH = 50

        self.PADDLE_HEIGHT = 10

        self.GAME_FLOOR = 350

        self.GAME_CEILING = 10

        self.BALL_VELOCITY = 10

        self.PADDLE_VELOCITY = 20

        self.MAX_TRIES_PER_GAME = 100

        self.CUSTOM_EVENT = pygame.USEREVENT + 1

        

        self.frames = collections.deque(maxlen=4)

        self.game_over = False       

        self.paddle_x = self.GAME_WIDTH // 2

        self.game_score = 0

        self.ball_x = random.randint(0, self.GAME_WIDTH)

        self.ball_y = self.GAME_CEILING

        self.num_tries = 0

        # 设置窗口及时钟

        self.screen = pygame.display.set_mode( (self.GAME_WIDTH, self.GAME_HEIGHT))

        self.clock = pygame.time.Clock()        

        

    def play(self):

        while not self.game_over:

            if self.num_tries > self.MAX_TRIES_PER_GAME:

                self.game_over = True

                break

            

            for event in pygame.event.get():

                if event.type == pygame.QUIT:

                    break

                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:

                    self.game_over = True

                    break

                if event.type == pygame.KEYDOWN and event.key == pygame.K_LEFT:

                    self.paddle_x -= self.PADDLE_VELOCITY

                    if self.paddle_x < 0:#球移出左边界

                        self.paddle_x = 0

                if event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT:

                    self.paddle_x += self.PADDLE_VELOCITY

                    if self.paddle_x > self.GAME_WIDTH - self.PADDLE_WIDTH:#球出右边界

                        self.paddle_x = self.GAME_WIDTH - self.PADDLE_WIDTH

                    

            self.screen.fill(self.COLOR_BLACK)

                           

            # 更新球的位置

            self.ball_y += self.BALL_VELOCITY

            ball = pygame.draw.rect(self.screen, self.COLOR_WHITE,

                                    pygame.Rect(self.ball_x, self.ball_y,

                                                self.BALL_WIDTH,

                                                self.BALL_HEIGHT))

            # 更新板的位置

            paddle = pygame.draw.rect(self.screen, self.COLOR_WHITE,

                                      pygame.Rect(self.paddle_x,

                                                  self.GAME_FLOOR,

                                                  self.PADDLE_WIDTH,

                                                  self.PADDLE_HEIGHT))

            # 接球检测

            if self.ball_y >= self.GAME_FLOOR - self.BALL_HEIGHT // 2:

                if ball.colliderect(paddle):

                    self.game_score += 1

                else:

                    self.game_score -= 1

                self.ball_x = random.randint(0, self.GAME_WIDTH)

                self.ball_y = self.GAME_CEILING

                self.num_tries += 1

            

            pygame.display.flip()            

            self.frames.append(pygame.surfarray.array2d(self.screen))#将当前画面加入暂存#变量中,最多只存4帧            

            self.clock.tick(30)#延时30毫秒        

        S = np.array(self.frames)#frames中的4帧图存于S,并转为numpy格式

            print(S.shape)#4400400

         

            for i in range(4):#查看截图效果

                  plt.subplot(221+i)

                  plt.imshow(S[i].T)#S中画面与实际画面方向不同,需转置            

            plt.show()

    

if __name__ == "__main__":

    game = MyGame()

    game.play()


实际运行效果没有截图。



作者个人微信



转载文章地址:http://www.showerdoorexpo.com/boke/266.html
(本文来自动漫界面整合文章:http://www.showerdoorexpo.com)未经允许,不得转载!
标签:
相关推荐
网站简介 联系我们 网站申明 网站地图

版权所有:www.showerdoorexpo.com ©2017 动漫界面

动漫界面提供的所有内容均是网络转载或网友提供,本站仅提供内容展示服务,不承认任何法律责任。